blob: c0c4fc45e62dd53bbe7bd6561859787a617f9005 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000018#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000021#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000022#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000025#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall943fae92010-05-27 06:19:26 +000029static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
30 llvm::Value *Array,
31 llvm::Value *Value,
32 unsigned FirstIndex,
33 unsigned LastIndex) {
34 // Alternatively, we could emit this as a loop in the source.
35 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
36 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
37 Builder.CreateStore(Value, Cell);
38 }
39}
40
John McCalla1dee5302010-08-22 10:59:02 +000041static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000042 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000043 T->isMemberFunctionPointerType();
44}
45
Anton Korobeynikov244360d2009-06-05 22:08:42 +000046ABIInfo::~ABIInfo() {}
47
Mark Lacey3825e832013-10-06 01:33:34 +000048static bool isRecordReturnIndirect(const RecordType *RT,
49 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000050 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
51 if (!RD)
52 return false;
Mark Lacey3825e832013-10-06 01:33:34 +000053 return CXXABI.isReturnTypeIndirect(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000054}
55
56
Mark Lacey3825e832013-10-06 01:33:34 +000057static bool isRecordReturnIndirect(QualType T, CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000058 const RecordType *RT = T->getAs<RecordType>();
59 if (!RT)
60 return false;
Mark Lacey3825e832013-10-06 01:33:34 +000061 return isRecordReturnIndirect(RT, CXXABI);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000062}
63
64static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000065 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000066 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
67 if (!RD)
68 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000069 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000070}
71
72static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000073 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000074 const RecordType *RT = T->getAs<RecordType>();
75 if (!RT)
76 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000077 return getRecordArgABI(RT, CXXABI);
78}
79
80CGCXXABI &ABIInfo::getCXXABI() const {
81 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000082}
83
Chris Lattner2b037972010-07-29 02:01:43 +000084ASTContext &ABIInfo::getContext() const {
85 return CGT.getContext();
86}
87
88llvm::LLVMContext &ABIInfo::getVMContext() const {
89 return CGT.getLLVMContext();
90}
91
Micah Villmowdd31ca12012-10-08 16:25:52 +000092const llvm::DataLayout &ABIInfo::getDataLayout() const {
93 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000094}
95
John McCallc8e01702013-04-16 22:48:15 +000096const TargetInfo &ABIInfo::getTarget() const {
97 return CGT.getTarget();
98}
Chris Lattner2b037972010-07-29 02:01:43 +000099
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000100void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000101 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000102 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000103 switch (TheKind) {
104 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000105 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000106 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000107 Ty->print(OS);
108 else
109 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000110 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000111 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000112 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000113 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000114 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000115 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000116 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000117 case InAlloca:
118 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
119 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000120 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000121 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000122 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000123 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000124 break;
125 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127 break;
128 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000129 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000130}
131
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000132TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
133
John McCall3480ef22011-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 Northover9bb857a2013-01-31 12:13:10 +0000142 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000143 return 32;
144}
145
John McCalla729c622012-02-17 03:33:10 +0000146bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
147 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-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 Klecknere43f0fe2013-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 Dunbar626f1d82009-09-13 08:03:58 +0000165static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000166
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000167/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000168/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000169static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
170 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000171 if (FD->isUnnamedBitfield())
172 return true;
173
174 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000175
Eli Friedman0b3f2012011-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 Dunbar626f1d82009-09-13 08:03:58 +0000178 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000179 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
180 if (AT->getSize() == 0)
181 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000182 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000183 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000184
Daniel Dunbarcd20ce12010-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 Dunbar626f1d82009-09-13 08:03:58 +0000196 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000197}
198
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000199/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000200/// fields. Note that a structure with a flexible array member is not
201/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000202static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000203 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-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 Dunbarcd20ce12010-05-17 16:46:00 +0000209
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000210 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000211 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000212 for (const auto &I : CXXRD->bases())
213 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000214 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000215
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000216 for (const auto *I : RD->fields())
217 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-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. Spencerb2f376b2010-08-25 18:17:27 +0000240
Daniel Dunbar12ebb472010-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)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000243 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000244 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000245 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000246 continue;
247
248 // If we already found an element then this isn't a single-element struct.
249 if (Found)
250 return 0;
251
252 // If this is non-empty and not a single element struct, the composite
253 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000254 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000255 if (!Found)
256 return 0;
257 }
258 }
259
260 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000261 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000262 QualType FT = FD->getType();
263
264 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000265 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-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 McCalla1dee5302010-08-22 10:59:02 +0000280 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-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 Friedmanee945342011-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 Korobeynikov244360d2009-06-05 22:08:42 +0000294 return Found;
295}
296
297static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-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 Dunbar6b45b672010-05-14 03:40:53 +0000305 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000306 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-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 Dunbar11c08c82009-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 Friedmane5c85622011-11-18 01:32:26 +0000335 uint64_t Size = 0;
336
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000337 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-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 Friedmane5c85622011-11-18 01:32:26 +0000346
347 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000348 }
349
Eli Friedmane5c85622011-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 Korobeynikov244360d2009-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 Lattner2b037972010-07-29 02:01:43 +0000363public:
364 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000365
Chris Lattner458b2aa2010-07-29 02:16:43 +0000366 ABIArgInfo classifyReturnType(QualType RetTy) const;
367 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000368
Craig Topper4f12f102014-03-12 06:41:41 +0000369 void computeInfo(CGFunctionInfo &FI) const override {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000370 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000371 for (auto &I : FI.arguments())
372 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000373 }
374
Craig Topper4f12f102014-03-12 06:41:41 +0000375 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
376 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000377};
378
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000379class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
380public:
Chris Lattner2b037972010-07-29 02:01:43 +0000381 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
382 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-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 Lattner458b2aa2010-07-29 02:16:43 +0000390ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Jan Wen Voung180319f2011-11-03 00:59:44 +0000391 if (isAggregateTypeForABI(Ty)) {
Alp Tokerd4733632013-12-05 04:47:09 +0000392 // Records with non-trivial destructors/constructors should not be passed
Jan Wen Voung180319f2011-11-03 00:59:44 +0000393 // by value.
Mark Lacey3825e832013-10-06 01:33:34 +0000394 if (isRecordReturnIndirect(Ty, getCXXABI()))
Jan Wen Voung180319f2011-11-03 00:59:44 +0000395 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
396
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000397 return ABIArgInfo::getIndirect(0);
Jan Wen Voung180319f2011-11-03 00:59:44 +0000398 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000399
Chris Lattner9723d6c2010-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 Gregora71cc152010-02-02 20:10:50 +0000403
Chris Lattner9723d6c2010-03-11 18:19:55 +0000404 return (Ty->isPromotableIntegerType() ?
405 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000406}
407
Bob Wilsonbd4520b2011-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 Schuff09338a22012-09-06 17:37:28 +0000423//===----------------------------------------------------------------------===//
424// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-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 Schuff09338a22012-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 Bendersky4f6791c2013-04-08 21:31:01 +0000435 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000436
Craig Topper4f12f102014-03-12 06:41:41 +0000437 void computeInfo(CGFunctionInfo &FI) const override;
438 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
439 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-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
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000451 for (auto &I : FI.arguments())
452 I.info = classifyArgumentType(I.type);
Derek Schuff09338a22012-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 Bendersky4f6791c2013-04-08 21:31:01 +0000460/// \brief Classify argument of given type \p Ty.
461ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000462 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000463 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000464 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000465 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000466 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
467 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000468 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000469 } else if (Ty->isFloatingType()) {
470 // Floating-point types don't go inreg.
471 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000472 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000473
474 return (Ty->isPromotableIntegerType() ?
475 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000476}
477
478ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
479 if (RetTy->isVoidType())
480 return ABIArgInfo::getIgnore();
481
Eli Benderskye20dad62013-04-04 22:49:35 +0000482 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-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 Rosier651c1832013-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 Wendling5cd41c42010-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 Foad7c57be32011-07-11 09:56:20 +0000502static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000504 llvm::Type* Ty) {
Tim Northover0ae93912013-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 Collingbourne8f5cf742011-02-19 23:03:58 +0000511 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000512 }
513
514 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000515 return Ty;
516}
517
Chris Lattner0cf24192010-06-28 20:05:43 +0000518//===----------------------------------------------------------------------===//
519// X86-32 ABI Implementation
520//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000521
Reid Kleckner661f35b2014-01-18 01:12:41 +0000522/// \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;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000528 unsigned StackOffset;
529 bool UseInAlloca;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000530};
531
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000532/// X86_32ABIInfo - The X86-32 ABI information.
533class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000534 enum Class {
535 Integer,
536 Float
537 };
538
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000539 static const unsigned MinABIStackAlignInBytes = 4;
540
David Chisnallde3a0692009-08-17 23:08:21 +0000541 bool IsDarwinVectorABI;
542 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000543 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000544 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000545
546 static bool isRegisterSize(unsigned Size) {
547 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
548 }
549
Reid Kleckner4982b822014-01-31 22:54:50 +0000550 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
551 bool IsInstanceMethod) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000552
Daniel Dunbar557893d2010-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.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000555 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
556
557 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000558
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000559 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000560 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000561
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000562 Class classify(QualType Ty) const;
Reid Kleckner4982b822014-01-31 22:54:50 +0000563 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State,
564 bool IsInstanceMethod) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000565 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
566 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000567
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000568 /// \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;
575
Rafael Espindola75419dc2012-07-23 23:30:29 +0000576public:
577
Craig Topper4f12f102014-03-12 06:41:41 +0000578 void computeInfo(CGFunctionInfo &FI) const override;
579 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
580 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000581
Chad Rosier651c1832013-03-25 21:00:27 +0000582 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000583 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000584 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000585 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000586};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000587
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000588class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
589public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000590 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-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 Davis4ea31ab2010-02-13 15:54:06 +0000593
John McCall1fe2a8c2013-06-18 02:46:29 +0000594 static bool isStructReturnInRegABI(
595 const llvm::Triple &Triple, const CodeGenOptions &Opts);
596
Charles Davis4ea31ab2010-02-13 15:54:06 +0000597 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000598 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000599
Craig Topper4f12f102014-03-12 06:41:41 +0000600 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000601 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000602 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000603 return 4;
604 }
605
606 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000607 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000608
Jay Foad7c57be32011-07-11 09:56:20 +0000609 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000610 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000611 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000612 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
613 }
614
Craig Topper4f12f102014-03-12 06:41:41 +0000615 llvm::Constant *
616 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-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 Korobeynikov55bcea12010-01-10 12:58:08 +0000624};
625
626}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000627
628/// shouldReturnTypeInRegister - Determine if the given type should be
629/// passed in a register (for the Darwin ABI).
Reid Kleckner4982b822014-01-31 22:54:50 +0000630bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
631 bool IsInstanceMethod) const {
Anton Korobeynikov244360d2009-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 Dunbar4bd95c62010-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 Dunbar6b45b672010-05-14 03:40:53 +0000649 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000650 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000651 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000652 return true;
653
654 // Arrays are treated like records.
655 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman3c424412012-02-22 03:04:13 +0000656 return shouldReturnTypeInRegister(AT->getElementType(), Context,
Reid Kleckner4982b822014-01-31 22:54:50 +0000657 IsInstanceMethod);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000658
659 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000660 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000661 if (!RT) return false;
662
Anders Carlsson40446e82010-01-27 03:25:19 +0000663 // FIXME: Traverse bases here too.
664
Aaron Ballman3c424412012-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
Reid Kleckner4982b822014-01-31 22:54:50 +0000667 if (IsWin32StructABI && IsInstanceMethod && RT->isStructureType())
Aaron Ballman3c424412012-02-22 03:04:13 +0000668 return false;
Aaron Ballman3c424412012-02-22 03:04:13 +0000669
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000670 // Structure types are passed in register if all fields would be
671 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000672 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000673 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000674 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000675 continue;
676
677 // Check fields recursively.
Reid Kleckner4982b822014-01-31 22:54:50 +0000678 if (!shouldReturnTypeInRegister(FD->getType(), Context, IsInstanceMethod))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000679 return false;
680 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000681 return true;
682}
683
Reid Kleckner661f35b2014-01-18 01:12:41 +0000684ABIArgInfo 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
Reid Kleckner4982b822014-01-31 22:54:50 +0000694ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State,
695 bool IsInstanceMethod) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000696 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000697 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000698
Chris Lattner458b2aa2010-07-29 02:16:43 +0000699 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000700 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000701 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000702 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-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 Lattnerfe34c1d2010-07-29 06:26:06 +0000708 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000709 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-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 Lattnerfe34c1d2010-07-29 06:26:06 +0000715 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000716 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000717
Reid Kleckner661f35b2014-01-18 01:12:41 +0000718 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000719 }
720
721 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000722 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000723
John McCalla1dee5302010-08-22 10:59:02 +0000724 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000725 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Mark Lacey3825e832013-10-06 01:33:34 +0000726 if (isRecordReturnIndirect(RT, getCXXABI()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000727 return getIndirectReturnResult(State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000728
Anders Carlsson5789c492009-10-20 22:07:59 +0000729 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000730 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000731 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000732 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000733
David Chisnallde3a0692009-08-17 23:08:21 +0000734 // If specified, structs and unions are always indirect.
735 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000736 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000737
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000738 // Small structures which are register sized are generally returned
739 // in a register.
Reid Kleckner4982b822014-01-31 22:54:50 +0000740 if (shouldReturnTypeInRegister(RetTy, getContext(), IsInstanceMethod)) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000741 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-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 Friedmana98d1f82012-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 Friedmanee945342011-11-18 01:25:50 +0000748 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000749 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000750 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-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 Lattnerfe34c1d2010-07-29 06:26:06 +0000755 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000756 }
757
Reid Kleckner661f35b2014-01-18 01:12:41 +0000758 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000759 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000760
Chris Lattner458b2aa2010-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 Korobeynikov244360d2009-06-05 22:08:42 +0000767}
768
Eli Friedman7919bea2012-06-05 19:40:46 +0000769static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
770 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
771}
772
Daniel Dunbared23de32010-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))
Aaron Ballman574705e2014-03-13 15:41:46 +0000781 for (const auto &I : CXXRD->bases())
782 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000783 return false;
784
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000785 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000786 QualType FT = i->getType();
787
Eli Friedman7919bea2012-06-05 19:40:46 +0000788 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-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 Dunbardd38fbc2010-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 Dunbar8a6c91f2010-09-16 20:41:56 +0000802 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-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 Dunbar8a6c91f2010-09-16 20:41:56 +0000808 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000809 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000810
Daniel Dunbared23de32010-09-16 20:42:00 +0000811 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000812 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
813 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000814 return 16;
815
816 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000817}
818
Rafael Espindola703c47f2012-10-19 05:04:37 +0000819ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000820 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000821 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000822 if (State.FreeRegs) {
823 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000824 return ABIArgInfo::getIndirectInReg(0, false);
825 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000826 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000827 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000828
Daniel Dunbardd38fbc2010-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)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000833 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000834
835 // If the stack alignment is less than the type alignment, realign the
836 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000837 bool Realign = TypeAlign > StackAlign;
838 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000839}
840
Rafael Espindola06b2b4a2012-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
Reid Kleckner661f35b2014-01-18 01:12:41 +0000854bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
855 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000856 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000857 Class C = classify(Ty);
858 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000859 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000860
Rafael Espindola077dd592012-10-24 01:58:58 +0000861 unsigned Size = getContext().getTypeSize(Ty);
862 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000863
864 if (SizeInRegs == 0)
865 return false;
866
Reid Kleckner661f35b2014-01-18 01:12:41 +0000867 if (SizeInRegs > State.FreeRegs) {
868 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000869 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000870 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000871
Reid Kleckner661f35b2014-01-18 01:12:41 +0000872 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000873
Reid Kleckner661f35b2014-01-18 01:12:41 +0000874 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-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
Reid Kleckner661f35b2014-01-18 01:12:41 +0000887 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000888 NeedsPadding = true;
889
Rafael Espindola077dd592012-10-24 01:58:58 +0000890 return false;
891 }
892
Rafael Espindola703c47f2012-10-19 05:04:37 +0000893 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000894}
895
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000896ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
897 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000898 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000899 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000900 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000901 // 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 }
909
910 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000911 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000912 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000913
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000914 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000915 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000916 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000917 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000918
Eli Friedman9f061a32011-11-18 00:28:11 +0000919 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000920 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000921 return ABIArgInfo::getIgnore();
922
Rafael Espindolafad28de2012-10-24 01:59:00 +0000923 llvm::LLVMContext &LLVMContext = getVMContext();
924 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
925 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000926 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000927 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000928 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000929 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
930 return ABIArgInfo::getDirectInReg(Result);
931 }
Rafael Espindolafad28de2012-10-24 01:59:00 +0000932 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000933
Daniel Dunbar11c08c82009-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 Lattner458b2aa2010-07-29 02:16:43 +0000938 if (getContext().getTypeSize(Ty) <= 4*32 &&
939 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000940 return ABIArgInfo::getExpandWithPadding(
941 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000942
Reid Kleckner661f35b2014-01-18 01:12:41 +0000943 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000944 }
945
Chris Lattnerd774ae92010-08-26 20:05:13 +0000946 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-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 Lattnerd774ae92010-08-26 20:05:13 +0000949 if (IsDarwinVectorABI) {
950 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-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 Lattnerd774ae92010-08-26 20:05:13 +0000955 }
Bill Wendling5cd41c42010-10-18 03:41:31 +0000956
Chad Rosier651c1832013-03-25 21:00:27 +0000957 if (IsX86_MMXType(CGT.ConvertType(Ty)))
958 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000959
Chris Lattnerd774ae92010-08-26 20:05:13 +0000960 return ABIArgInfo::getDirect();
961 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000962
963
Chris Lattner458b2aa2010-07-29 02:16:43 +0000964 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
965 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000966
Rafael Espindolafad28de2012-10-24 01:59:00 +0000967 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000968 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-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 Korobeynikov244360d2009-06-05 22:08:42 +0000978}
979
Rafael Espindolaa6472962012-07-24 00:01:07 +0000980void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000981 CCState State(FI.getCallingConvention());
982 if (State.CC == llvm::CallingConv::X86_FastCall)
983 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +0000984 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000985 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +0000986 else
Reid Kleckner661f35b2014-01-18 01:12:41 +0000987 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000988
Reid Kleckner4982b822014-01-31 22:54:50 +0000989 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);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000999
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001000 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001001 for (auto &I : FI.arguments()) {
1002 I.info = classifyArgumentType(I.type, State);
1003 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001004 }
1005
1006 // 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);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001049 // On Windows, the hidden sret parameter is always returned in eax.
1050 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001051 }
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 Espindolaa6472962012-07-24 00:01:07 +00001082}
1083
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001084llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1085 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001086 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-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 Friedman1d7dd3b2011-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 Korobeynikov244360d2009-06-05 22:08:42 +00001110 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001111 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001112 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1113
1114 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001115 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001117 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001118 "ap.next");
1119 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1120
1121 return AddrTyped;
1122}
1123
Charles Davis4ea31ab2010-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 Wendlinga514ebc2012-10-15 20:36:26 +00001133 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001134 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001135 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1136 llvm::AttributeSet::get(CGM.getLLVMContext(),
1137 llvm::AttributeSet::FunctionIndex,
1138 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001139 }
1140 }
1141}
1142
John McCallbeec5a02010-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 McCallbeec5a02010-03-06 00:35:14 +00001147
Chris Lattnerece04092012-02-07 00:39:47 +00001148 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001149
John McCallbeec5a02010-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 McCall943fae92010-05-27 06:19:26 +00001153 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001154
John McCallc8e01702013-04-16 22:48:15 +00001155 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-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 Lattnerece04092012-02-07 00:39:47 +00001159 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001160 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001161
John McCallbeec5a02010-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 Lattnerece04092012-02-07 00:39:47 +00001170 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001171 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1172 }
John McCallbeec5a02010-03-06 00:35:14 +00001173
1174 return false;
1175}
1176
Chris Lattner0cf24192010-06-28 20:05:43 +00001177//===----------------------------------------------------------------------===//
1178// X86-64 ABI Implementation
1179//===----------------------------------------------------------------------===//
1180
1181
Anton Korobeynikov244360d2009-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 Lattnerd776fb12010-06-28 21:43:59 +00001205 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001206
Bruno Cardoso Lopes21a41bb2011-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 Korobeynikov244360d2009-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 Friedman96fd2642013-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 Korobeynikov244360d2009-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 Ledru33b5baf2012-09-27 10:16:10 +00001243 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-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 Friedman96fd2642013-06-12 00:13:45 +00001247 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1248 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001249
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001250 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-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. Spencerb2f376b2010-08-25 18:17:27 +00001257
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001258 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001259 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001260 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001261
1262 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001263 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-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 Korobeynikov244360d2009-06-05 22:08:42 +00001268
Chris Lattner458b2aa2010-07-29 02:16:43 +00001269 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001270
Bill Wendling5cd41c42010-10-18 03:41:31 +00001271 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001272 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001273 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001274 unsigned &neededSSE,
1275 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001276
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001277 bool IsIllegalVectorType(QualType Ty) const;
1278
John McCalle0fda732011-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 McCallc8e01702013-04-16 22:48:15 +00001285 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001286 }
1287
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001288 bool HasAVX;
Derek Schuffc7dd7222012-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 Friedmanbfd5add2011-12-02 00:11:43 +00001292
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001293public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001294 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001295 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001296 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001297 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001298
John McCalla729c622012-02-17 03:33:10 +00001299 bool isPassedUsingAVXType(QualType type) const {
1300 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001301 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001302 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1303 /*isNamedArg*/true);
John McCalla729c622012-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
Craig Topper4f12f102014-03-12 06:41:41 +00001312 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001313
Craig Topper4f12f102014-03-12 06:41:41 +00001314 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1315 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001316};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001317
Chris Lattner04dc9572010-08-31 16:44:54 +00001318/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001319class WinX86_64ABIInfo : public ABIInfo {
1320
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001321 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001322
Chris Lattner04dc9572010-08-31 16:44:54 +00001323public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001324 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1325
Craig Topper4f12f102014-03-12 06:41:41 +00001326 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001327
Craig Topper4f12f102014-03-12 06:41:41 +00001328 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1329 CodeGenFunction &CGF) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001330};
1331
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001332class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1333public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001334 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001335 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001336
John McCalla729c622012-02-17 03:33:10 +00001337 const X86_64ABIInfo &getABIInfo() const {
1338 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1339 }
1340
Craig Topper4f12f102014-03-12 06:41:41 +00001341 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001342 return 7;
1343 }
1344
1345 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001346 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001347 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001348
John McCall943fae92010-05-27 06:19:26 +00001349 // 0-15 are the 16 integer registers.
1350 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001351 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001352 return false;
1353 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001354
Jay Foad7c57be32011-07-11 09:56:20 +00001355 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001356 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001357 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001358 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1359 }
1360
John McCalla729c622012-02-17 03:33:10 +00001361 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001362 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-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 Friedmanf37bd2f2011-12-01 04:53:19 +00001365 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-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 Kleckner78af0702013-08-27 23:08:25 +00001369 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001370 bool HasAVXType = false;
John McCalla729c622012-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 Friedmanf37bd2f2011-12-01 04:53:19 +00001376 }
1377 }
John McCalla729c622012-02-17 03:33:10 +00001378
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001379 if (!HasAVXType)
1380 return true;
1381 }
John McCallcbc038a2011-09-21 08:08:30 +00001382
John McCalla729c622012-02-17 03:33:10 +00001383 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001384 }
1385
Craig Topper4f12f102014-03-12 06:41:41 +00001386 llvm::Constant *
1387 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-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 Korobeynikov55bcea12010-01-10 12:58:08 +00001395};
1396
Aaron Ballmanef50ee92013-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 Ueyama727025a2013-10-31 19:12:53 +00001401 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001402 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001403 return ArgStr;
1404}
1405
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001406class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1407public:
John McCall1fe2a8c2013-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 Klecknere43f0fe2013-05-08 13:44:39 +00001411
1412 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001413 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001414 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001415 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001416 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001417
1418 void getDetectMismatchOption(llvm::StringRef Name,
1419 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001420 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001421 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001422 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001423};
1424
Chris Lattner04dc9572010-08-31 16:44:54 +00001425class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1426public:
1427 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1428 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1429
Craig Topper4f12f102014-03-12 06:41:41 +00001430 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001431 return 7;
1432 }
1433
1434 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001435 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001436 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001437
Chris Lattner04dc9572010-08-31 16:44:54 +00001438 // 0-15 are the 16 integer registers.
1439 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001440 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001441 return false;
1442 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001443
1444 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001445 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001446 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001447 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001448 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001449
1450 void getDetectMismatchOption(llvm::StringRef Name,
1451 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001452 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001453 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001454 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001455};
1456
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001457}
1458
Bruno Cardoso Lopes21a41bb2011-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 Lattnerd776fb12010-06-28 21:43:59 +00001492X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-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 Lattnerd776fb12010-06-28 21:43:59 +00001520 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001521 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001522 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001523 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001524 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001525 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001526 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1527 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001528 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001529 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001530}
1531
Chris Lattner5c740f12010-06-30 19:14:05 +00001532void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001533 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-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 McCall9dd450b2009-09-21 23:43:11 +00001547 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-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 Schuff57b7e8f2012-10-11 16:55:58 +00001557 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1558 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001559 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-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 Lattnerd776fb12010-06-28 21:43:59 +00001567 return;
1568 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001569
Chris Lattnerd776fb12010-06-28 21:43:59 +00001570 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001571 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001572 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001573 return;
1574 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001575
Chris Lattnerd776fb12010-06-28 21:43:59 +00001576 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001577 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001578 return;
1579 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001580
Chris Lattnerd776fb12010-06-28 21:43:59 +00001581 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001582 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001583 Lo = Hi = Integer;
1584 else
1585 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001586 return;
1587 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001588
Chris Lattnerd776fb12010-06-28 21:43:59 +00001589 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001590 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-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 Lattner46830f22010-08-26 18:03:20 +00001608 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001609 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1610 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1611 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-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 Friedman96fd2642013-06-12 00:13:45 +00001620 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-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 Friedman96fd2642013-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 Korobeynikov244360d2009-06-05 22:08:42 +00001632 Lo = SSE;
1633 Hi = SSEUp;
1634 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001635 return;
1636 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001637
Chris Lattnerd776fb12010-06-28 21:43:59 +00001638 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001639 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001640
Chris Lattner2b037972010-07-29 02:01:43 +00001641 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001642 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001643 if (Size <= 64)
1644 Current = Integer;
1645 else if (Size <= 128)
1646 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001647 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001648 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001649 else if (ET == getContext().DoubleTy ||
1650 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001651 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001652 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001653 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-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 Lattner2b037972010-07-29 02:01:43 +00001659 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001660 if (Hi == NoClass && EB_Real != EB_Imag)
1661 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001662
Chris Lattnerd776fb12010-06-28 21:43:59 +00001663 return;
1664 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001665
Chris Lattner2b037972010-07-29 02:01:43 +00001666 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001667 // Arrays are treated like structures.
1668
Chris Lattner2b037972010-07-29 02:01:43 +00001669 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001670
1671 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001672 // than four eightbytes, ..., it has class MEMORY.
1673 if (Size > 256)
Anton Korobeynikov244360d2009-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 Lattner2b037972010-07-29 02:01:43 +00001680 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-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 Lattner2b037972010-07-29 02:01:43 +00001686 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001687 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-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 Korobeynikov244360d2009-06-05 22:08:42 +00001695 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1696 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001697 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-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 Lopes21a41bb2011-07-11 22:41:29 +00001704 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001705 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001706 return;
1707 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001708
Chris Lattnerd776fb12010-06-28 21:43:59 +00001709 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001710 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001711
1712 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001713 // than four eightbytes, ..., it has class MEMORY.
1714 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001715 return;
1716
Anders Carlsson20759ad2009-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 Lacey3825e832013-10-06 01:33:34 +00001720 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001721 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001722
Anton Korobeynikov244360d2009-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 Lattner2b037972010-07-29 02:01:43 +00001729 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001730
1731 // Reset Lo class, this will be recomputed.
1732 Current = NoClass;
Daniel Dunbare1cd0152009-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)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001736 for (const auto &I : CXXRD->bases()) {
1737 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001738 "Unexpected base class!");
1739 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001740 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-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 Kramer2ef30312012-07-04 18:45:14 +00001748 uint64_t Offset =
1749 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001750 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-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 Korobeynikov244360d2009-06-05 22:08:42 +00001759 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001760 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001761 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001762 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1763 bool BitField = i->isBitField();
1764
Bruno Cardoso Lopes98154a72011-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 Korobeynikov244360d2009-06-05 22:08:42 +00001767 //
Bruno Cardoso Lopes98154a72011-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 Korobeynikov244360d2009-06-05 22:08:42 +00001776 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001777 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-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 Smithcaf33902011-10-10 18:28:20 +00001799 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001800
1801 uint64_t EB_Lo = Offset / 64;
1802 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001803
Anton Korobeynikov244360d2009-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 Friedman96fd2642013-06-12 00:13:45 +00001813 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-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 Lopes21a41bb2011-07-11 22:41:29 +00001820 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001821 }
1822}
1823
Chris Lattner22a931e2010-06-29 06:01:59 +00001824ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-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 McCalla1dee5302010-08-22 10:59:02 +00001827 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-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 Friedmanbfd5add2011-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 Dunbarf07b5ec2012-03-10 01:03:58 +00001850ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1851 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-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 Dunbarf07b5ec2012-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 Friedmanbfd5add2011-12-02 00:11:43 +00001860 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-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 Korobeynikov18adbf52009-06-06 09:36:29 +00001865 return (Ty->isPromotableIntegerType() ?
1866 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001867 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001868
Mark Lacey3825e832013-10-06 01:33:34 +00001869 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001870 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001871
Chris Lattner44c2b902011-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 Dunbarf07b5ec2012-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 Lattner44c2b902011-05-22 23:21:23 +00001907 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001908}
1909
Bruno Cardoso Lopes21a41bb2011-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 Lattner4200fe42010-07-29 04:56:46 +00001912/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001913llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001914 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001915
Chris Lattner9fa15c32010-07-29 05:02:29 +00001916 // Wrapper structs that just contain vectors are passed just like vectors,
1917 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001918 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-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. Spencerb2f376b2010-08-25 18:17:27 +00001923
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001924 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001925 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1926 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001927 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001928 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-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. Spencerb2f376b2010-08-25 18:17:27 +00001935
Chris Lattner4200fe42010-07-29 04:56:46 +00001936 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1937}
1938
Chris Lattnerc8b7b532010-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 Lattner98076a22010-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. Spencerb2f376b2010-08-25 18:17:27 +00001964
Chris Lattner98076a22010-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. Spencerb2f376b2010-08-25 18:17:27 +00001973
Chris Lattnerc8b7b532010-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. Spencerb2f376b2010-08-25 18:17:27 +00001977
Chris Lattnerc8b7b532010-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)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001980 for (const auto &I : CXXRD->bases()) {
1981 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001982 "Unexpected base class!");
1983 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001984 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001985
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001986 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001987 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001988 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001989
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001990 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00001991 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001992 EndBit-BaseOffset, Context))
1993 return false;
1994 }
1995 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001996
Chris Lattnerc8b7b532010-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. Spencerb2f376b2010-08-25 18:17:27 +00002005
Chris Lattnerc8b7b532010-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. Spencerb2f376b2010-08-25 18:17:27 +00002014
Chris Lattnerc8b7b532010-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. Spencerb2f376b2010-08-25 18:17:27 +00002019
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002020 return false;
2021}
2022
Chris Lattnere556a712010-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 Lattner2192fe52011-07-18 04:24:23 +00002027static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002028 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002029 // Base case if we find a float.
2030 if (IROffset == 0 && IRType->isFloatTy())
2031 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002032
Chris Lattnere556a712010-07-29 18:39:32 +00002033 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002034 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-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. Spencerb2f376b2010-08-25 18:17:27 +00002040
Chris Lattnere556a712010-07-29 18:39:32 +00002041 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002042 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2043 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-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 Lattner7f4b81a2010-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 Lattnera5f58b02011-07-09 17:41:47 +00002055llvm::Type *X86_64ABIInfo::
2056GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002057 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002058 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-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. Spencerb2f376b2010-08-25 18:17:27 +00002064
Chris Lattnere556a712010-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 Villmowdd31ca12012-10-08 16:25:52 +00002068 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2069 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002070 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002071
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002072 return llvm::Type::getDoubleTy(getVMContext());
2073}
2074
2075
Chris Lattner1c56d9a2010-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 Lattnerb22f1c82010-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 Lattnera5f58b02011-07-09 17:41:47 +00002090llvm::Type *X86_64ABIInfo::
2091GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002092 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-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 Schuffc7dd7222012-10-11 15:52:22 +00002097 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2098 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002099 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002100
Chris Lattnerc8b7b532010-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 Schuffc7dd7222012-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. Spencerb2f376b2010-08-25 18:17:27 +00002112
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002113 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2114 SourceOffset*8+64, getContext()))
2115 return IRType;
2116 }
2117 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002118
Chris Lattner2192fe52011-07-18 04:24:23 +00002119 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002120 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002121 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002122 if (IROffset < SL->getSizeInBytes()) {
2123 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2124 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002125
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002126 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2127 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002128 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002129 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002130
Chris Lattner2192fe52011-07-18 04:24:23 +00002131 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002132 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002133 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002134 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002135 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2136 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002137 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002138
Chris Lattnerb22f1c82010-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 Lattner3f763422010-07-29 17:34:39 +00002141 unsigned TySizeInBytes =
2142 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002143
Chris Lattner3f763422010-07-29 17:34:39 +00002144 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002145
Chris Lattnerb22f1c82010-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 Lattner3f763422010-07-29 17:34:39 +00002148 return llvm::IntegerType::get(getVMContext(),
2149 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002150}
2151
Chris Lattnerd426c8e2010-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 Lattnera5f58b02011-07-09 17:41:47 +00002158static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002159GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002160 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-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 Villmowdd31ca12012-10-08 16:25:52 +00002167 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002168 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002169
Chris Lattnerd426c8e2010-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. Spencerf5a1fbc2010-10-19 06:39:39 +00002185
Chris Lattnera5f58b02011-07-09 17:41:47 +00002186 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002187
2188
Chris Lattnerd426c8e2010-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 Lattner31faff52010-07-28 23:06:14 +00002195ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002196classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-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 Friedman96fd2642013-06-12 00:13:45 +00002200 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002201
2202 // Check some invariants.
2203 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002204 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2205
Chris Lattnera5f58b02011-07-09 17:41:47 +00002206 llvm::Type *ResType = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002207 switch (Lo) {
2208 case NoClass:
Chris Lattner8a2f3c72010-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 Lattner31faff52010-07-28 23:06:14 +00002216
2217 case SSEUp:
2218 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002219 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-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 Lattnera5f58b02011-07-09 17:41:47 +00002229 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002230
Chris Lattner1f3a0632010-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. Spencerb2f376b2010-08-25 18:17:27 +00002237
Chris Lattner1f3a0632010-07-29 21:42:50 +00002238 if (RetTy->isIntegralOrEnumerationType() &&
2239 RetTy->isPromotableIntegerType())
2240 return ABIArgInfo::getExtend();
2241 }
Chris Lattner31faff52010-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 Lattnera5f58b02011-07-09 17:41:47 +00002247 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002248 break;
Chris Lattner31faff52010-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 Lattner2b037972010-07-29 02:01:43 +00002253 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002254 break;
Chris Lattner31faff52010-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 Lattner845511f2011-06-18 22:49:11 +00002261 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002262 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002263 NULL);
2264 break;
2265 }
2266
Chris Lattnera5f58b02011-07-09 17:41:47 +00002267 llvm::Type *HighPart = 0;
Chris Lattner31faff52010-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 Blaikie83d382b2011-09-23 05:06:16 +00002273 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002274
2275 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002276 case NoClass:
2277 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002278
Chris Lattner52b3c132010-09-01 00:20:33 +00002279 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002280 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002281 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2282 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002283 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002284 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002285 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002286 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2287 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-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 Lopes21a41bb2011-07-11 22:41:29 +00002291 // is passed in the next available eightbyte chunk if the last used
2292 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002293 //
Chris Lattner57540c52011-04-15 05:22:18 +00002294 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002295 case SSEUp:
2296 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002297 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-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 Lattner57540c52011-04-15 05:22:18 +00002303 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002304 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002305 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002306 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002307 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002308 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002309 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2310 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002311 }
Chris Lattner31faff52010-07-28 23:06:14 +00002312 break;
2313 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002314
Chris Lattner52b3c132010-09-01 00:20:33 +00002315 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-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 Lattnerd426c8e2010-09-01 00:50:20 +00002318 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002319 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002320
Chris Lattner1f3a0632010-07-29 21:42:50 +00002321 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002322}
2323
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002324ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002325 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2326 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002327 const
2328{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002329 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002330 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002331
Anton Korobeynikov244360d2009-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 Korobeynikov244360d2009-06-05 22:08:42 +00002335 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2336
2337 neededInt = 0;
2338 neededSSE = 0;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002339 llvm::Type *ResType = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002340 switch (Lo) {
2341 case NoClass:
Chris Lattner8a2f3c72010-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. Spencerb2f376b2010-08-25 18:17:27 +00002349
Anton Korobeynikov244360d2009-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 Lacey3825e832013-10-06 01:33:34 +00002358 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002359 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002360 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002361
2362 case SSEUp:
2363 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002364 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-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 Lattner22a931e2010-06-29 06:01:59 +00002370 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002371
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002372 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002373 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-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. Spencerb2f376b2010-08-25 18:17:27 +00002381
Chris Lattner1f3a0632010-07-29 21:42:50 +00002382 if (Ty->isIntegralOrEnumerationType() &&
2383 Ty->isPromotableIntegerType())
2384 return ABIArgInfo::getExtend();
2385 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002386
Anton Korobeynikov244360d2009-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 Wendling5cd41c42010-10-18 03:41:31 +00002392 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002393 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002394 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002395 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002396 break;
2397 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002398 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002399
Chris Lattnera5f58b02011-07-09 17:41:47 +00002400 llvm::Type *HighPart = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002401 switch (Hi) {
2402 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002403 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002404 // which is passed in memory.
2405 case Memory:
2406 case X87:
2407 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002408 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002409
2410 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002411
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002412 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002413 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002414 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002415 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002416
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002417 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2418 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-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 Lattnerbe5eb172010-09-01 00:24:35 +00002424 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002425 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002426
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002427 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2428 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002429
Anton Korobeynikov244360d2009-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. Spencerb2f376b2010-08-25 18:17:27 +00002435 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002436 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002437 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002438 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002439 break;
2440 }
2441
Chris Lattnerbe5eb172010-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 Villmowdd31ca12012-10-08 16:25:52 +00002446 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002447
Chris Lattner1f3a0632010-07-29 21:42:50 +00002448 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002449}
2450
Chris Lattner22326a12010-07-29 02:31:05 +00002451void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002452
Chris Lattner458b2aa2010-07-29 02:16:43 +00002453 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002454
2455 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002456 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-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 Friedman96fd2642013-06-12 00:13:45 +00002463 bool isVariadic = FI.isVariadic();
2464 unsigned numRequiredArgs = 0;
2465 if (isVariadic)
2466 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2467
Anton Korobeynikov244360d2009-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 Friedman96fd2642013-06-12 00:13:45 +00002472 bool isNamedArg = true;
2473 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002474 isNamedArg = (it - FI.arg_begin()) <
2475 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002476
Bill Wendling9987c0e2010-10-18 23:51:38 +00002477 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002478 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002479 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-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 Wendling9987c0e2010-10-18 23:51:38 +00002485 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002486 freeIntRegs -= neededInt;
2487 freeSSERegs -= neededSSE;
2488 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002489 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-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 Friedmana1748562011-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 Korobeynikov244360d2009-06-05 22:08:42 +00002506 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2507 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002508 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002509 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002510 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-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 Lattner5e016ae2010-06-27 07:15:29 +00002513 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002514 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-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 Lattner2192fe52011-07-18 04:24:23 +00002522 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002523 llvm::Value *Res =
2524 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002525 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-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 Anderson41a75022009-08-13 21:57:51 +00002533 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002534 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-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 Wendling9987c0e2010-10-18 23:51:38 +00002552 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002553
Chris Lattner9723d6c2010-03-11 18:19:55 +00002554 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002555 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2556 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-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 Lattnerd776fb12010-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 Korobeynikov244360d2009-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 Lattnerd776fb12010-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 Korobeynikov244360d2009-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 Lattner2192fe52011-07-18 04:24:23 +00002612 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-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 Lattnerfe34c1d2010-07-29 06:26:06 +00002618 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002619 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002620 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2621 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002622 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002623 llvm::Type *TyLo = ST->getElementType(0);
2624 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002625 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002626 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002627 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2628 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-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 Sands998f9d92010-02-15 16:14:01 +00002631 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2632 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-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 Anderson170229f2009-07-14 23:10:40 +00002639 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002640 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002641 } else if (neededInt) {
2642 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2643 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002644 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-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 Friedmanc11c1692013-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 Lattner0cf24192010-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 Korobeynikov244360d2009-06-05 22:08:42 +00002660 } else {
Chris Lattner0cf24192010-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 Lattnerd776fb12010-06-28 21:43:59 +00002665 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002666 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002667 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002668 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-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 Lattner0cf24192010-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 Korobeynikov244360d2009-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 Lattner5e016ae2010-06-27 07:15:29 +00002686 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002687 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2688 gp_offset_p);
2689 }
2690 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002691 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-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 Foad20c0f022011-03-30 11:28:58 +00002705 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002706 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707 ResAddr->addIncoming(RegAddr, InRegBlock);
2708 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002709 return ResAddr;
2710}
2711
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002712ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-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 Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002723 if (IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002724 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002725 return ABIArgInfo::getIndirect(0, false);
2726 } else {
Mark Lacey3825e832013-10-06 01:33:34 +00002727 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002728 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2729 }
2730
2731 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002732 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2733
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002734 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCallc8e01702013-04-16 22:48:15 +00002735 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumif8a6e802011-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 Takumie03c6032011-01-19 00:11:33 +00002742 (Size & (Size - 1)) == 0)
NAKAMURA Takumibd91f502011-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 Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002758 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002759
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002760 for (auto &I : FI.arguments())
2761 I.info = classify(I.type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002762}
2763
Chris Lattner04dc9572010-08-31 16:44:54 +00002764llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2765 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002766 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002767
Chris Lattner04dc9572010-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 Lattner0cf24192010-06-28 20:05:43 +00002785
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002786namespace {
2787
Derek Schuffa2020962012-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) {}
Craig Topper4f12f102014-03-12 06:41:41 +00002792 void computeInfo(CGFunctionInfo &FI) const override;
2793 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2794 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-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 Kramer1cdb23d2012-10-20 13:02:06 +00002806}
2807
Derek Schuffa2020962012-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 McCallea8d8bb2010-03-11 00:10:12 +00002823// PowerPC-32
2824
2825namespace {
2826class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2827public:
Chris Lattner2b037972010-07-29 02:01:43 +00002828 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002829
Craig Topper4f12f102014-03-12 06:41:41 +00002830 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-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,
Craig Topper4f12f102014-03-12 06:41:41 +00002836 llvm::Value *Address) const override;
John McCallea8d8bb2010-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 McCallea8d8bb2010-03-11 00:10:12 +00002848
Chris Lattnerece04092012-02-07 00:39:47 +00002849 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-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 McCall943fae92010-05-27 06:19:26 +00002855 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002856
2857 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002858 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-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 McCall943fae92010-05-27 06:19:26 +00002867 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002868
2869 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002870 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002871
2872 // 109: vrsave
2873 // 110: vscr
2874 // 111: spe_acc
2875 // 112: spefscr
2876 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002877 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002878
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002879 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002880}
2881
Roman Divackyd966e722012-05-09 18:22:46 +00002882// PowerPC-64
2883
2884namespace {
Bill Schmidt25cb3492012-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 Weigand77ed89d2012-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 Schmidt84d37792012-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.
Craig Topper4f12f102014-03-12 06:41:41 +00002902 void computeInfo(CGFunctionInfo &FI) const override {
Bill Schmidt84d37792012-10-12 19:26:17 +00002903 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002904 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-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 Schmidt179afae2013-07-23 22:15:57 +00002907 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002908 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00002909 if (T) {
2910 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidt179afae2013-07-23 22:15:57 +00002911 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002912 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002913 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00002914 continue;
2915 }
2916 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002917 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00002918 }
2919 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002920
Craig Topper4f12f102014-03-12 06:41:41 +00002921 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2922 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-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
Craig Topper4f12f102014-03-12 06:41:41 +00002930 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-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,
Craig Topper4f12f102014-03-12 06:41:41 +00002936 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002937};
2938
Roman Divackyd966e722012-05-09 18:22:46 +00002939class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2940public:
2941 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2942
Craig Topper4f12f102014-03-12 06:41:41 +00002943 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-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,
Craig Topper4f12f102014-03-12 06:41:41 +00002949 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00002950};
2951
2952}
2953
Ulrich Weigand77ed89d2012-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 Schmidt90b22c92012-11-27 02:46:43 +00002982 if (Ty->isAnyComplexType())
2983 return ABIArgInfo::getDirect();
2984
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002985 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00002986 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002987 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-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 Schmidta3d121c2012-12-17 04:20:17 +00003001 if (RetTy->isAnyComplexType())
3002 return ABIArgInfo::getDirect();
3003
Ulrich Weigand77ed89d2012-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 Schmidt25cb3492012-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 Schmidt924c4782013-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 Schmidt25cb3492012-10-03 19:18:57 +00003026 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-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 Schmidt25cb3492012-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 Schmidt924c4782013-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 Schmidt25cb3492012-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 Divackyd966e722012-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 McCallea8d8bb2010-03-11 00:10:12 +00003121
Bill Schmidt25cb3492012-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 Lattner0cf24192010-06-28 20:05:43 +00003137//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003138// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00003139//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003140
3141namespace {
3142
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003143class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003144public:
3145 enum ABIKind {
3146 APCS = 0,
3147 AAPCS = 1,
3148 AAPCS_VFP
3149 };
3150
3151private:
3152 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00003153 mutable int VFPRegs[16];
3154 const unsigned NumVFPs;
3155 const unsigned NumGPRs;
3156 mutable unsigned AllocatedGPRs;
3157 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003158
3159public:
Oliver Stannard405bded2014-02-11 09:25:50 +00003160 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
3161 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00003162 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003163 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00003164 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003165
John McCall3480ef22011-08-30 01:42:09 +00003166 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003167 switch (getTarget().getTriple().getEnvironment()) {
3168 case llvm::Triple::Android:
3169 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003170 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003171 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00003172 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003173 return true;
3174 default:
3175 return false;
3176 }
John McCall3480ef22011-08-30 01:42:09 +00003177 }
3178
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003179 bool isEABIHF() const {
3180 switch (getTarget().getTriple().getEnvironment()) {
3181 case llvm::Triple::EABIHF:
3182 case llvm::Triple::GNUEABIHF:
3183 return true;
3184 default:
3185 return false;
3186 }
3187 }
3188
Daniel Dunbar020daa92009-09-12 01:00:39 +00003189 ABIKind getABIKind() const { return Kind; }
3190
Tim Northovera484bc02013-10-01 14:34:25 +00003191private:
Amara Emerson9dc78782014-01-28 10:56:36 +00003192 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Oliver Stannard405bded2014-02-11 09:25:50 +00003193 ABIArgInfo classifyArgumentType(QualType RetTy, bool &IsHA, bool isVariadic,
3194 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00003195 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003196
Craig Topper4f12f102014-03-12 06:41:41 +00003197 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003198
Craig Topper4f12f102014-03-12 06:41:41 +00003199 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3200 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00003201
3202 llvm::CallingConv::ID getLLVMDefaultCC() const;
3203 llvm::CallingConv::ID getABIDefaultCC() const;
3204 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003205
3206 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
3207 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
3208 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003209};
3210
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003211class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3212public:
Chris Lattner2b037972010-07-29 02:01:43 +00003213 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3214 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00003215
John McCall3480ef22011-08-30 01:42:09 +00003216 const ARMABIInfo &getABIInfo() const {
3217 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3218 }
3219
Craig Topper4f12f102014-03-12 06:41:41 +00003220 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00003221 return 13;
3222 }
Roman Divackyc1617352011-05-18 19:36:54 +00003223
Craig Topper4f12f102014-03-12 06:41:41 +00003224 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00003225 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3226 }
3227
Roman Divackyc1617352011-05-18 19:36:54 +00003228 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003229 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00003230 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00003231
3232 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00003233 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00003234 return false;
3235 }
John McCall3480ef22011-08-30 01:42:09 +00003236
Craig Topper4f12f102014-03-12 06:41:41 +00003237 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00003238 if (getABIInfo().isEABI()) return 88;
3239 return TargetCodeGenInfo::getSizeOfUnwindException();
3240 }
Tim Northovera484bc02013-10-01 14:34:25 +00003241
3242 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00003243 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00003244 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3245 if (!FD)
3246 return;
3247
3248 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3249 if (!Attr)
3250 return;
3251
3252 const char *Kind;
3253 switch (Attr->getInterrupt()) {
3254 case ARMInterruptAttr::Generic: Kind = ""; break;
3255 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3256 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3257 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3258 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3259 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3260 }
3261
3262 llvm::Function *Fn = cast<llvm::Function>(GV);
3263
3264 Fn->addFnAttr("interrupt", Kind);
3265
3266 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3267 return;
3268
3269 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3270 // however this is not necessarily true on taking any interrupt. Instruct
3271 // the backend to perform a realignment as part of the function prologue.
3272 llvm::AttrBuilder B;
3273 B.addStackAlignmentAttr(8);
3274 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3275 llvm::AttributeSet::get(CGM.getLLVMContext(),
3276 llvm::AttributeSet::FunctionIndex,
3277 B));
3278 }
3279
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003280};
3281
Daniel Dunbard59655c2009-09-12 00:59:49 +00003282}
3283
Chris Lattner22326a12010-07-29 02:31:05 +00003284void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003285 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00003286 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00003287 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3288 // VFP registers of the appropriate type unallocated then the argument is
3289 // allocated to the lowest-numbered sequence of such registers.
3290 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3291 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00003292 resetAllocatedRegs();
3293
Amara Emerson9dc78782014-01-28 10:56:36 +00003294 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003295 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00003296 unsigned PreAllocationVFPs = AllocatedVFPs;
3297 unsigned PreAllocationGPRs = AllocatedGPRs;
Manman Ren2a523d82012-10-30 23:21:41 +00003298 bool IsHA = false;
Oliver Stannard405bded2014-02-11 09:25:50 +00003299 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00003300 // 6.1.2.3 There is one VFP co-processor register class using registers
3301 // s0-s15 (d0-d7) for passing arguments.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003302 I.info = classifyArgumentType(I.type, IsHA, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00003303 assert((IsCPRC || !IsHA) && "Homogeneous aggregates must be CPRCs");
Manman Ren2a523d82012-10-30 23:21:41 +00003304 // If we do not have enough VFP registers for the HA, any VFP registers
3305 // that are unallocated are marked as unavailable. To achieve this, we add
Oliver Stannard405bded2014-02-11 09:25:50 +00003306 // padding of (NumVFPs - PreAllocationVFP) floats.
Amara Emerson9dc78782014-01-28 10:56:36 +00003307 // Note that IsHA will only be set when using the AAPCS-VFP calling convention,
3308 // and the callee is not variadic.
Oliver Stannard405bded2014-02-11 09:25:50 +00003309 if (IsHA && AllocatedVFPs > NumVFPs && PreAllocationVFPs < NumVFPs) {
Manman Ren2a523d82012-10-30 23:21:41 +00003310 llvm::Type *PaddingTy = llvm::ArrayType::get(
Oliver Stannard405bded2014-02-11 09:25:50 +00003311 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocationVFPs);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003312 I.info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00003313 }
3314
3315 // If we have allocated some arguments onto the stack (due to running
3316 // out of VFP registers), we cannot split an argument between GPRs and
3317 // the stack. If this situation occurs, we add padding to prevent the
3318 // GPRs from being used. In this situiation, the current argument could
3319 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
3320 // unusable anyway.
3321 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
3322 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs && StackUsed) {
3323 llvm::Type *PaddingTy = llvm::ArrayType::get(
3324 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003325 I.info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
Manman Ren2a523d82012-10-30 23:21:41 +00003326 }
3327 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003328
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003329 // Always honor user-specified calling convention.
3330 if (FI.getCallingConvention() != llvm::CallingConv::C)
3331 return;
3332
John McCall882987f2013-02-28 19:01:20 +00003333 llvm::CallingConv::ID cc = getRuntimeCC();
3334 if (cc != llvm::CallingConv::C)
3335 FI.setEffectiveCallingConvention(cc);
3336}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003337
John McCall882987f2013-02-28 19:01:20 +00003338/// Return the default calling convention that LLVM will use.
3339llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3340 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003341 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00003342 return llvm::CallingConv::ARM_AAPCS_VFP;
3343 else if (isEABI())
3344 return llvm::CallingConv::ARM_AAPCS;
3345 else
3346 return llvm::CallingConv::ARM_APCS;
3347}
3348
3349/// Return the calling convention that our ABI would like us to use
3350/// as the C calling convention.
3351llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003352 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003353 case APCS: return llvm::CallingConv::ARM_APCS;
3354 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3355 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003356 }
John McCall882987f2013-02-28 19:01:20 +00003357 llvm_unreachable("bad ABI kind");
3358}
3359
3360void ARMABIInfo::setRuntimeCC() {
3361 assert(getRuntimeCC() == llvm::CallingConv::C);
3362
3363 // Don't muddy up the IR with a ton of explicit annotations if
3364 // they'd just match what LLVM will infer from the triple.
3365 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3366 if (abiCC != getLLVMDefaultCC())
3367 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003368}
3369
Bob Wilsone826a2a2011-08-03 05:58:22 +00003370/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3371/// aggregate. If HAMembers is non-null, the number of base elements
3372/// contained in the type is returned through it; this is used for the
3373/// recursive calls that check aggregate component types.
3374static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3375 ASTContext &Context,
3376 uint64_t *HAMembers = 0) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003377 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003378 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3379 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3380 return false;
3381 Members *= AT->getSize().getZExtValue();
3382 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3383 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003384 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003385 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003386
Bob Wilsone826a2a2011-08-03 05:58:22 +00003387 Members = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003388 for (const auto *FD : RD->fields()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00003389 uint64_t FldMembers;
3390 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3391 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003392
3393 Members = (RD->isUnion() ?
3394 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003395 }
3396 } else {
3397 Members = 1;
3398 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3399 Members = 2;
3400 Ty = CT->getElementType();
3401 }
3402
3403 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3404 // double, or 64-bit or 128-bit vectors.
3405 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3406 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00003407 BT->getKind() != BuiltinType::Double &&
3408 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00003409 return false;
3410 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3411 unsigned VecSize = Context.getTypeSize(VT);
3412 if (VecSize != 64 && VecSize != 128)
3413 return false;
3414 } else {
3415 return false;
3416 }
3417
3418 // The base type must be the same for all members. Vector types of the
3419 // same total size are treated as being equivalent here.
3420 const Type *TyPtr = Ty.getTypePtr();
3421 if (!Base)
3422 Base = TyPtr;
Oliver Stannard5e8558f2014-02-07 11:25:57 +00003423
3424 if (Base != TyPtr) {
3425 // Homogeneous aggregates are defined as containing members with the
3426 // same machine type. There are two cases in which two members have
3427 // different TypePtrs but the same machine type:
3428
3429 // 1) Vectors of the same length, regardless of the type and number
3430 // of their members.
3431 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
3432 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
3433
3434 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
3435 // machine type. This is not the case for the 64-bit AAPCS.
3436 const bool SameSizeDoubles =
3437 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
3438 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
3439 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
3440 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
3441 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
3442
3443 if (!SameLengthVectors && !SameSizeDoubles)
3444 return false;
3445 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003446 }
3447
3448 // Homogeneous Aggregates can have at most 4 members of the base type.
3449 if (HAMembers)
3450 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003451
3452 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003453}
3454
Manman Renb505d332012-10-31 19:02:26 +00003455/// markAllocatedVFPs - update VFPRegs according to the alignment and
3456/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00003457void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
3458 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00003459 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00003460 if (AllocatedVFPs >= 16) {
3461 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
3462 // the stack.
3463 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00003464 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00003465 }
Manman Renb505d332012-10-31 19:02:26 +00003466 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3467 // VFP registers of the appropriate type unallocated then the argument is
3468 // allocated to the lowest-numbered sequence of such registers.
3469 for (unsigned I = 0; I < 16; I += Alignment) {
3470 bool FoundSlot = true;
3471 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3472 if (J >= 16 || VFPRegs[J]) {
3473 FoundSlot = false;
3474 break;
3475 }
3476 if (FoundSlot) {
3477 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3478 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00003479 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00003480 return;
3481 }
3482 }
3483 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3484 // unallocated are marked as unavailable.
3485 for (unsigned I = 0; I < 16; I++)
3486 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00003487 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00003488}
3489
Oliver Stannard405bded2014-02-11 09:25:50 +00003490/// Update AllocatedGPRs to record the number of general purpose registers
3491/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
3492/// this represents arguments being stored on the stack.
3493void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
3494 unsigned NumRequired) const {
3495 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
3496
3497 if (Alignment == 2 && AllocatedGPRs & 0x1)
3498 AllocatedGPRs += 1;
3499
3500 AllocatedGPRs += NumRequired;
3501}
3502
3503void ARMABIInfo::resetAllocatedRegs(void) const {
3504 AllocatedGPRs = 0;
3505 AllocatedVFPs = 0;
3506 for (unsigned i = 0; i < NumVFPs; ++i)
3507 VFPRegs[i] = 0;
3508}
3509
3510ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool &IsHA,
3511 bool isVariadic,
3512 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003513 // We update number of allocated VFPs according to
3514 // 6.1.2.1 The following argument types are VFP CPRCs:
3515 // A single-precision floating-point type (including promoted
3516 // half-precision types); A double-precision floating-point type;
3517 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3518 // with a Base Type of a single- or double-precision floating-point type,
3519 // 64-bit containerized vectors or 128-bit containerized vectors with one
3520 // to four Elements.
3521
Manman Renfef9e312012-10-16 19:18:39 +00003522 // Handle illegal vector types here.
3523 if (isIllegalVectorType(Ty)) {
3524 uint64_t Size = getContext().getTypeSize(Ty);
3525 if (Size <= 32) {
3526 llvm::Type *ResType =
3527 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00003528 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00003529 return ABIArgInfo::getDirect(ResType);
3530 }
3531 if (Size == 64) {
3532 llvm::Type *ResType = llvm::VectorType::get(
3533 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00003534 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
3535 markAllocatedGPRs(2, 2);
3536 } else {
3537 markAllocatedVFPs(2, 2);
3538 IsCPRC = true;
3539 }
Manman Renfef9e312012-10-16 19:18:39 +00003540 return ABIArgInfo::getDirect(ResType);
3541 }
3542 if (Size == 128) {
3543 llvm::Type *ResType = llvm::VectorType::get(
3544 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00003545 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
3546 markAllocatedGPRs(2, 4);
3547 } else {
3548 markAllocatedVFPs(4, 4);
3549 IsCPRC = true;
3550 }
Manman Renfef9e312012-10-16 19:18:39 +00003551 return ABIArgInfo::getDirect(ResType);
3552 }
Oliver Stannard405bded2014-02-11 09:25:50 +00003553 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00003554 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3555 }
Manman Renb505d332012-10-31 19:02:26 +00003556 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00003557 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
3558 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3559 uint64_t Size = getContext().getTypeSize(VT);
3560 // Size of a legal vector should be power of 2 and above 64.
3561 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
3562 IsCPRC = true;
3563 }
Manman Ren2a523d82012-10-30 23:21:41 +00003564 }
Manman Renb505d332012-10-31 19:02:26 +00003565 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00003566 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
3567 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3568 if (BT->getKind() == BuiltinType::Half ||
3569 BT->getKind() == BuiltinType::Float) {
3570 markAllocatedVFPs(1, 1);
3571 IsCPRC = true;
3572 }
3573 if (BT->getKind() == BuiltinType::Double ||
3574 BT->getKind() == BuiltinType::LongDouble) {
3575 markAllocatedVFPs(2, 2);
3576 IsCPRC = true;
3577 }
3578 }
Manman Ren2a523d82012-10-30 23:21:41 +00003579 }
Manman Renfef9e312012-10-16 19:18:39 +00003580
John McCalla1dee5302010-08-22 10:59:02 +00003581 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003582 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00003583 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003584 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00003585 }
Douglas Gregora71cc152010-02-02 20:10:50 +00003586
Oliver Stannard405bded2014-02-11 09:25:50 +00003587 unsigned Size = getContext().getTypeSize(Ty);
3588 if (!IsCPRC)
3589 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003590 return (Ty->isPromotableIntegerType() ?
3591 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003592 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003593
Oliver Stannard405bded2014-02-11 09:25:50 +00003594 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
3595 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00003596 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00003597 }
Tim Northover1060eae2013-06-21 22:49:34 +00003598
Daniel Dunbar09d33622009-09-14 21:54:03 +00003599 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003600 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00003601 return ABIArgInfo::getIgnore();
3602
Amara Emerson9dc78782014-01-28 10:56:36 +00003603 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
Manman Ren2a523d82012-10-30 23:21:41 +00003604 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3605 // into VFP registers.
Bob Wilsone826a2a2011-08-03 05:58:22 +00003606 const Type *Base = 0;
Manman Ren2a523d82012-10-30 23:21:41 +00003607 uint64_t Members = 0;
3608 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003609 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00003610 // Base can be a floating-point or a vector.
3611 if (Base->isVectorType()) {
3612 // ElementSize is in number of floats.
3613 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00003614 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00003615 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00003616 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00003617 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00003618 else {
3619 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3620 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00003621 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003622 }
3623 IsHA = true;
Oliver Stannard405bded2014-02-11 09:25:50 +00003624 IsCPRC = true;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003625 return ABIArgInfo::getExpand();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003626 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003627 }
3628
Manman Ren6c30e132012-08-13 21:23:55 +00003629 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00003630 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3631 // most 8-byte. We realign the indirect argument if type alignment is bigger
3632 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00003633 uint64_t ABIAlign = 4;
3634 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3635 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3636 getABIKind() == ARMABIInfo::AAPCS)
3637 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00003638 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard405bded2014-02-11 09:25:50 +00003639 // Update Allocated GPRs
3640 markAllocatedGPRs(1, 1);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00003641 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00003642 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00003643 }
3644
Daniel Dunbarb34b0802010-09-23 01:54:28 +00003645 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00003646 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003647 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00003648 // FIXME: Try to match the types of the arguments more accurately where
3649 // we can.
3650 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00003651 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3652 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00003653 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00003654 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00003655 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3656 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00003657 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00003658 }
Stuart Hastings4b214952011-04-28 18:16:06 +00003659
Chris Lattnera5f58b02011-07-09 17:41:47 +00003660 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00003661 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00003662 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003663}
3664
Chris Lattner458b2aa2010-07-29 02:16:43 +00003665static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003666 llvm::LLVMContext &VMContext) {
3667 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3668 // is called integer-like if its size is less than or equal to one word, and
3669 // the offset of each of its addressable sub-fields is zero.
3670
3671 uint64_t Size = Context.getTypeSize(Ty);
3672
3673 // Check that the type fits in a word.
3674 if (Size > 32)
3675 return false;
3676
3677 // FIXME: Handle vector types!
3678 if (Ty->isVectorType())
3679 return false;
3680
Daniel Dunbard53bac72009-09-14 02:20:34 +00003681 // Float types are never treated as "integer like".
3682 if (Ty->isRealFloatingType())
3683 return false;
3684
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003685 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00003686 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003687 return true;
3688
Daniel Dunbar96ebba52010-02-01 23:31:26 +00003689 // Small complex integer types are "integer like".
3690 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3691 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003692
3693 // Single element and zero sized arrays should be allowed, by the definition
3694 // above, but they are not.
3695
3696 // Otherwise, it must be a record type.
3697 const RecordType *RT = Ty->getAs<RecordType>();
3698 if (!RT) return false;
3699
3700 // Ignore records with flexible arrays.
3701 const RecordDecl *RD = RT->getDecl();
3702 if (RD->hasFlexibleArrayMember())
3703 return false;
3704
3705 // Check that all sub-fields are at offset 0, and are themselves "integer
3706 // like".
3707 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3708
3709 bool HadField = false;
3710 unsigned idx = 0;
3711 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3712 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00003713 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003714
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003715 // Bit-fields are not addressable, we only need to verify they are "integer
3716 // like". We still have to disallow a subsequent non-bitfield, for example:
3717 // struct { int : 0; int x }
3718 // is non-integer like according to gcc.
3719 if (FD->isBitField()) {
3720 if (!RD->isUnion())
3721 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003722
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003723 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3724 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003725
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003726 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003727 }
3728
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003729 // Check if this field is at offset 0.
3730 if (Layout.getFieldOffset(idx) != 0)
3731 return false;
3732
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003733 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3734 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003735
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003736 // Only allow at most one field in a structure. This doesn't match the
3737 // wording above, but follows gcc in situations with a field following an
3738 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003739 if (!RD->isUnion()) {
3740 if (HadField)
3741 return false;
3742
3743 HadField = true;
3744 }
3745 }
3746
3747 return true;
3748}
3749
Oliver Stannard405bded2014-02-11 09:25:50 +00003750ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
3751 bool isVariadic) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003752 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003753 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003754
Daniel Dunbar19964db2010-09-23 01:54:32 +00003755 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00003756 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
3757 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00003758 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00003759 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00003760
John McCalla1dee5302010-08-22 10:59:02 +00003761 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003762 // Treat an enum type as its underlying type.
3763 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3764 RetTy = EnumTy->getDecl()->getIntegerType();
3765
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003766 return (RetTy->isPromotableIntegerType() ?
3767 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003768 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003769
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003770 // Structures with either a non-trivial destructor or a non-trivial
3771 // copy constructor are always indirect.
Oliver Stannard405bded2014-02-11 09:25:50 +00003772 if (isRecordReturnIndirect(RetTy, getCXXABI())) {
3773 markAllocatedGPRs(1, 1);
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003774 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Oliver Stannard405bded2014-02-11 09:25:50 +00003775 }
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003776
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003777 // Are we following APCS?
3778 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00003779 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003780 return ABIArgInfo::getIgnore();
3781
Daniel Dunbareedf1512010-02-01 23:31:19 +00003782 // Complex types are all returned as packed integers.
3783 //
3784 // FIXME: Consider using 2 x vector types if the back end handles them
3785 // correctly.
3786 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003787 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00003788 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00003789
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003790 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003791 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003792 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003793 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003794 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003795 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003796 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003797 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3798 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003799 }
3800
3801 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00003802 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003803 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003804 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003805
3806 // Otherwise this is an AAPCS variant.
3807
Chris Lattner458b2aa2010-07-29 02:16:43 +00003808 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003809 return ABIArgInfo::getIgnore();
3810
Bob Wilson1d9269a2011-11-02 04:51:36 +00003811 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00003812 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Bob Wilson1d9269a2011-11-02 04:51:36 +00003813 const Type *Base = 0;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003814 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3815 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00003816 // Homogeneous Aggregates are returned directly.
3817 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003818 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00003819 }
3820
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003821 // Aggregates <= 4 bytes are returned in r0; other aggregates
3822 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003823 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003824 if (Size <= 32) {
3825 // Return in the smallest viable integer type.
3826 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003827 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003828 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003829 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3830 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003831 }
3832
Oliver Stannard405bded2014-02-11 09:25:50 +00003833 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003834 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003835}
3836
Manman Renfef9e312012-10-16 19:18:39 +00003837/// isIllegalVector - check whether Ty is an illegal vector type.
3838bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3839 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3840 // Check whether VT is legal.
3841 unsigned NumElements = VT->getNumElements();
3842 uint64_t Size = getContext().getTypeSize(VT);
3843 // NumElements should be power of 2.
3844 if ((NumElements & (NumElements - 1)) != 0)
3845 return true;
3846 // Size should be greater than 32 bits.
3847 return Size <= 32;
3848 }
3849 return false;
3850}
3851
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003852llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003853 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003854 llvm::Type *BP = CGF.Int8PtrTy;
3855 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003856
3857 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00003858 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003859 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00003860
Tim Northover1711cc92013-06-21 23:05:33 +00003861 if (isEmptyRecord(getContext(), Ty, true)) {
3862 // These are ignored for parameter passing purposes.
3863 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3864 return Builder.CreateBitCast(Addr, PTy);
3865 }
3866
Manman Rencca54d02012-10-16 19:01:37 +00003867 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00003868 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00003869 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00003870
3871 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3872 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00003873 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3874 getABIKind() == ARMABIInfo::AAPCS)
3875 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3876 else
3877 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00003878 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3879 if (isIllegalVectorType(Ty) && Size > 16) {
3880 IsIndirect = true;
3881 Size = 4;
3882 TyAlign = 4;
3883 }
Manman Rencca54d02012-10-16 19:01:37 +00003884
3885 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00003886 if (TyAlign > 4) {
3887 assert((TyAlign & (TyAlign - 1)) == 0 &&
3888 "Alignment is not power of 2!");
3889 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3890 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3891 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00003892 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00003893 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003894
3895 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00003896 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003897 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003898 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003899 "ap.next");
3900 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3901
Manman Renfef9e312012-10-16 19:18:39 +00003902 if (IsIndirect)
3903 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00003904 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00003905 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3906 // may not be correctly aligned for the vector type. We create an aligned
3907 // temporary space and copy the content over from ap.cur to the temporary
3908 // space. This is necessary if the natural alignment of the type is greater
3909 // than the ABI alignment.
3910 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3911 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3912 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3913 "var.align");
3914 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3915 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3916 Builder.CreateMemCpy(Dst, Src,
3917 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3918 TyAlign, false);
3919 Addr = AlignedTemp; //The content is in aligned location.
3920 }
3921 llvm::Type *PTy =
3922 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3923 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3924
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003925 return AddrTyped;
3926}
3927
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003928namespace {
3929
Derek Schuffa2020962012-10-16 22:30:41 +00003930class NaClARMABIInfo : public ABIInfo {
3931 public:
3932 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3933 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00003934 void computeInfo(CGFunctionInfo &FI) const override;
3935 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3936 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00003937 private:
3938 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3939 ARMABIInfo NInfo; // Used for everything else.
3940};
3941
3942class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3943 public:
3944 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3945 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3946};
3947
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003948}
3949
Derek Schuffa2020962012-10-16 22:30:41 +00003950void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3951 if (FI.getASTCallingConvention() == CC_PnaclCall)
3952 PInfo.computeInfo(FI);
3953 else
3954 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3955}
3956
3957llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3958 CodeGenFunction &CGF) const {
3959 // Always use the native convention; calling pnacl-style varargs functions
3960 // is unsupported.
3961 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3962}
3963
Chris Lattner0cf24192010-06-28 20:05:43 +00003964//===----------------------------------------------------------------------===//
Tim Northover9bb857a2013-01-31 12:13:10 +00003965// AArch64 ABI Implementation
3966//===----------------------------------------------------------------------===//
3967
3968namespace {
3969
3970class AArch64ABIInfo : public ABIInfo {
3971public:
3972 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3973
3974private:
3975 // The AArch64 PCS is explicit about return types and argument types being
3976 // handled identically, so we don't need to draw a distinction between
3977 // Argument and Return classification.
3978 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3979 int &FreeVFPRegs) const;
3980
3981 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3982 llvm::Type *DirectTy = 0) const;
3983
Craig Topper4f12f102014-03-12 06:41:41 +00003984 void computeInfo(CGFunctionInfo &FI) const override;
Tim Northover9bb857a2013-01-31 12:13:10 +00003985
Craig Topper4f12f102014-03-12 06:41:41 +00003986 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3987 CodeGenFunction &CGF) const override;
Tim Northover9bb857a2013-01-31 12:13:10 +00003988};
3989
3990class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3991public:
3992 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3993 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3994
3995 const AArch64ABIInfo &getABIInfo() const {
3996 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3997 }
3998
Craig Topper4f12f102014-03-12 06:41:41 +00003999 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tim Northover9bb857a2013-01-31 12:13:10 +00004000 return 31;
4001 }
4002
4003 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004004 llvm::Value *Address) const override {
Tim Northover9bb857a2013-01-31 12:13:10 +00004005 // 0-31 are x0-x30 and sp: 8 bytes each
4006 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
4007 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
4008
4009 // 64-95 are v0-v31: 16 bytes each
4010 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
4011 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
4012
4013 return false;
4014 }
4015
4016};
4017
4018}
4019
4020void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4021 int FreeIntRegs = 8, FreeVFPRegs = 8;
4022
4023 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
4024 FreeIntRegs, FreeVFPRegs);
4025
4026 FreeIntRegs = FreeVFPRegs = 8;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004027 for (auto &I : FI.arguments()) {
4028 I.info = classifyGenericType(I.type, FreeIntRegs, FreeVFPRegs);
Tim Northover9bb857a2013-01-31 12:13:10 +00004029
4030 }
4031}
4032
4033ABIArgInfo
4034AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
4035 bool IsInt, llvm::Type *DirectTy) const {
4036 if (FreeRegs >= RegsNeeded) {
4037 FreeRegs -= RegsNeeded;
4038 return ABIArgInfo::getDirect(DirectTy);
4039 }
4040
4041 llvm::Type *Padding = 0;
4042
4043 // We need padding so that later arguments don't get filled in anyway. That
4044 // wouldn't happen if only ByVal arguments followed in the same category, but
4045 // a large structure will simply seem to be a pointer as far as LLVM is
4046 // concerned.
4047 if (FreeRegs > 0) {
4048 if (IsInt)
4049 Padding = llvm::Type::getInt64Ty(getVMContext());
4050 else
4051 Padding = llvm::Type::getFloatTy(getVMContext());
4052
4053 // Either [N x i64] or [N x float].
4054 Padding = llvm::ArrayType::get(Padding, FreeRegs);
4055 FreeRegs = 0;
4056 }
4057
4058 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
4059 /*IsByVal=*/ true, /*Realign=*/ false,
4060 Padding);
4061}
4062
4063
4064ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
4065 int &FreeIntRegs,
4066 int &FreeVFPRegs) const {
4067 // Can only occurs for return, but harmless otherwise.
4068 if (Ty->isVoidType())
4069 return ABIArgInfo::getIgnore();
4070
4071 // Large vector types should be returned via memory. There's no such concept
4072 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
4073 // classified they'd go into memory (see B.3).
4074 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
4075 if (FreeIntRegs > 0)
4076 --FreeIntRegs;
4077 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4078 }
4079
4080 // All non-aggregate LLVM types have a concrete ABI representation so they can
4081 // be passed directly. After this block we're guaranteed to be in a
4082 // complicated case.
4083 if (!isAggregateTypeForABI(Ty)) {
4084 // Treat an enum type as its underlying type.
4085 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4086 Ty = EnumTy->getDecl()->getIntegerType();
4087
4088 if (Ty->isFloatingType() || Ty->isVectorType())
4089 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
4090
4091 assert(getContext().getTypeSize(Ty) <= 128 &&
4092 "unexpectedly large scalar type");
4093
4094 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
4095
4096 // If the type may need padding registers to ensure "alignment", we must be
4097 // careful when this is accounted for. Increasing the effective size covers
4098 // all cases.
4099 if (getContext().getTypeAlign(Ty) == 128)
4100 RegsNeeded += FreeIntRegs % 2 != 0;
4101
4102 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
4103 }
4104
Mark Lacey3825e832013-10-06 01:33:34 +00004105 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004106 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northover9bb857a2013-01-31 12:13:10 +00004107 --FreeIntRegs;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004108 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northover9bb857a2013-01-31 12:13:10 +00004109 }
4110
4111 if (isEmptyRecord(getContext(), Ty, true)) {
4112 if (!getContext().getLangOpts().CPlusPlus) {
4113 // Empty structs outside C++ mode are a GNU extension, so no ABI can
4114 // possibly tell us what to do. It turns out (I believe) that GCC ignores
4115 // the object for parameter-passsing purposes.
4116 return ABIArgInfo::getIgnore();
4117 }
4118
4119 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
4120 // description of va_arg in the PCS require that an empty struct does
4121 // actually occupy space for parameter-passing. I'm hoping for a
4122 // clarification giving an explicit paragraph to point to in future.
4123 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
4124 llvm::Type::getInt8Ty(getVMContext()));
4125 }
4126
4127 // Homogeneous vector aggregates get passed in registers or on the stack.
4128 const Type *Base = 0;
4129 uint64_t NumMembers = 0;
4130 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
4131 assert(Base && "Base class should be set for homogeneous aggregate");
4132 // Homogeneous aggregates are passed and returned directly.
4133 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
4134 /*IsInt=*/ false);
4135 }
4136
4137 uint64_t Size = getContext().getTypeSize(Ty);
4138 if (Size <= 128) {
4139 // Small structs can use the same direct type whether they're in registers
4140 // or on the stack.
4141 llvm::Type *BaseTy;
4142 unsigned NumBases;
4143 int SizeInRegs = (Size + 63) / 64;
4144
4145 if (getContext().getTypeAlign(Ty) == 128) {
4146 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
4147 NumBases = 1;
4148
4149 // If the type may need padding registers to ensure "alignment", we must
4150 // be careful when this is accounted for. Increasing the effective size
4151 // covers all cases.
4152 SizeInRegs += FreeIntRegs % 2 != 0;
4153 } else {
4154 BaseTy = llvm::Type::getInt64Ty(getVMContext());
4155 NumBases = SizeInRegs;
4156 }
4157 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
4158
4159 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
4160 /*IsInt=*/ true, DirectTy);
4161 }
4162
4163 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
4164 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
4165 --FreeIntRegs;
4166 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
4167}
4168
4169llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4170 CodeGenFunction &CGF) const {
4171 // The AArch64 va_list type and handling is specified in the Procedure Call
4172 // Standard, section B.4:
4173 //
4174 // struct {
4175 // void *__stack;
4176 // void *__gr_top;
4177 // void *__vr_top;
4178 // int __gr_offs;
4179 // int __vr_offs;
4180 // };
4181
Tim Northover9bb857a2013-01-31 12:13:10 +00004182 int FreeIntRegs = 8, FreeVFPRegs = 8;
4183 Ty = CGF.getContext().getCanonicalType(Ty);
4184 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
4185
4186 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4187 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4188 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4189 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4190
4191 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
4192 int reg_top_index;
4193 int RegSize;
4194 if (FreeIntRegs < 8) {
4195 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
4196 // 3 is the field number of __gr_offs
4197 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4198 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4199 reg_top_index = 1; // field number for __gr_top
4200 RegSize = 8 * (8 - FreeIntRegs);
4201 } else {
4202 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4203 // 4 is the field number of __vr_offs.
4204 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4205 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4206 reg_top_index = 2; // field number for __vr_top
4207 RegSize = 16 * (8 - FreeVFPRegs);
4208 }
4209
4210 //=======================================
4211 // Find out where argument was passed
4212 //=======================================
4213
4214 // If reg_offs >= 0 we're already using the stack for this type of
4215 // argument. We don't want to keep updating reg_offs (in case it overflows,
4216 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4217 // whatever they get).
4218 llvm::Value *UsingStack = 0;
4219 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4220 llvm::ConstantInt::get(CGF.Int32Ty, 0));
4221
4222 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4223
4224 // Otherwise, at least some kind of argument could go in these registers, the
4225 // quesiton is whether this particular type is too big.
4226 CGF.EmitBlock(MaybeRegBlock);
4227
4228 // Integer arguments may need to correct register alignment (for example a
4229 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4230 // align __gr_offs to calculate the potential address.
4231 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4232 int Align = getContext().getTypeAlign(Ty) / 8;
4233
4234 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4235 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4236 "align_regoffs");
4237 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4238 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4239 "aligned_regoffs");
4240 }
4241
4242 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4243 llvm::Value *NewOffset = 0;
4244 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4245 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4246 "new_reg_offs");
4247 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4248
4249 // Now we're in a position to decide whether this argument really was in
4250 // registers or not.
4251 llvm::Value *InRegs = 0;
4252 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4253 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4254 "inreg");
4255
4256 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4257
4258 //=======================================
4259 // Argument was in registers
4260 //=======================================
4261
4262 // Now we emit the code for if the argument was originally passed in
4263 // registers. First start the appropriate block:
4264 CGF.EmitBlock(InRegBlock);
4265
4266 llvm::Value *reg_top_p = 0, *reg_top = 0;
4267 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4268 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4269 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4270 llvm::Value *RegAddr = 0;
4271 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4272
4273 if (!AI.isDirect()) {
4274 // If it's been passed indirectly (actually a struct), whatever we find from
4275 // stored registers or on the stack will actually be a struct **.
4276 MemTy = llvm::PointerType::getUnqual(MemTy);
4277 }
4278
4279 const Type *Base = 0;
4280 uint64_t NumMembers;
4281 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4282 && NumMembers > 1) {
4283 // Homogeneous aggregates passed in registers will have their elements split
4284 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4285 // qN+1, ...). We reload and store into a temporary local variable
4286 // contiguously.
4287 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4288 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4289 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4290 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
Christian Pirkerf5164222014-03-14 11:51:06 +00004291 int Offset = 0;
Tim Northover9bb857a2013-01-31 12:13:10 +00004292
Christian Pirkerf5164222014-03-14 11:51:06 +00004293 if (CGF.CGM.getDataLayout().isBigEndian() &&
4294 getContext().getTypeSize(Base) < 128)
4295 Offset = 16 - getContext().getTypeSize(Base)/8;
Tim Northover9bb857a2013-01-31 12:13:10 +00004296 for (unsigned i = 0; i < NumMembers; ++i) {
Christian Pirkerf5164222014-03-14 11:51:06 +00004297 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty,
4298 16 * i + Offset);
Tim Northover9bb857a2013-01-31 12:13:10 +00004299 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4300 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4301 llvm::PointerType::getUnqual(BaseTy));
4302 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4303
4304 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4305 CGF.Builder.CreateStore(Elem, StoreAddr);
4306 }
4307
4308 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4309 } else {
4310 // Otherwise the object is contiguous in memory
Christian Pirkerf5164222014-03-14 11:51:06 +00004311 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
4312 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4313 getContext().getTypeSize(Ty) < (BeAlign * 8)) {
4314 int Offset = BeAlign - getContext().getTypeSize(Ty)/8;
4315 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4316
4317 BaseAddr = CGF.Builder.CreateAdd(BaseAddr,
4318 llvm::ConstantInt::get(CGF.Int64Ty,
4319 Offset),
4320 "align_be");
4321
4322 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4323 }
4324
Tim Northover9bb857a2013-01-31 12:13:10 +00004325 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4326 }
4327
4328 CGF.EmitBranch(ContBlock);
4329
4330 //=======================================
4331 // Argument was on the stack
4332 //=======================================
4333 CGF.EmitBlock(OnStackBlock);
4334
4335 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4336 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4337 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4338
4339 // Again, stack arguments may need realigmnent. In this case both integer and
4340 // floating-point ones might be affected.
4341 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4342 int Align = getContext().getTypeAlign(Ty) / 8;
4343
4344 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4345
4346 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4347 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4348 "align_stack");
4349 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4350 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4351 "align_stack");
4352
4353 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4354 }
4355
4356 uint64_t StackSize;
4357 if (AI.isDirect())
4358 StackSize = getContext().getTypeSize(Ty) / 8;
4359 else
4360 StackSize = 8;
4361
4362 // All stack slots are 8 bytes
4363 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4364
4365 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4366 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4367 "new_stack");
4368
4369 // Write the new value of __stack for the next call to va_arg
4370 CGF.Builder.CreateStore(NewStack, stack_p);
4371
Christian Pirkerf5164222014-03-14 11:51:06 +00004372 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4373 getContext().getTypeSize(Ty) < 64 ) {
4374 int Offset = 8 - getContext().getTypeSize(Ty)/8;
4375 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4376
4377 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4378 llvm::ConstantInt::get(CGF.Int64Ty,
4379 Offset),
4380 "align_be");
4381
4382 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4383 }
4384
Tim Northover9bb857a2013-01-31 12:13:10 +00004385 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4386
4387 CGF.EmitBranch(ContBlock);
4388
4389 //=======================================
4390 // Tidy up
4391 //=======================================
4392 CGF.EmitBlock(ContBlock);
4393
4394 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4395 ResAddr->addIncoming(RegAddr, InRegBlock);
4396 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4397
4398 if (AI.isDirect())
4399 return ResAddr;
4400
4401 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4402}
4403
4404//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004405// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004406//===----------------------------------------------------------------------===//
4407
4408namespace {
4409
Justin Holewinski83e96682012-05-24 17:43:12 +00004410class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004411public:
Justin Holewinski36837432013-03-30 14:38:24 +00004412 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004413
4414 ABIArgInfo classifyReturnType(QualType RetTy) const;
4415 ABIArgInfo classifyArgumentType(QualType Ty) const;
4416
Craig Topper4f12f102014-03-12 06:41:41 +00004417 void computeInfo(CGFunctionInfo &FI) const override;
4418 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4419 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004420};
4421
Justin Holewinski83e96682012-05-24 17:43:12 +00004422class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004423public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004424 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4425 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004426
4427 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4428 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00004429private:
4430 static void addKernelMetadata(llvm::Function *F);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004431};
4432
Justin Holewinski83e96682012-05-24 17:43:12 +00004433ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004434 if (RetTy->isVoidType())
4435 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004436
4437 // note: this is different from default ABI
4438 if (!RetTy->isScalarType())
4439 return ABIArgInfo::getDirect();
4440
4441 // Treat an enum type as its underlying type.
4442 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4443 RetTy = EnumTy->getDecl()->getIntegerType();
4444
4445 return (RetTy->isPromotableIntegerType() ?
4446 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004447}
4448
Justin Holewinski83e96682012-05-24 17:43:12 +00004449ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004450 // Treat an enum type as its underlying type.
4451 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4452 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004453
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004454 return (Ty->isPromotableIntegerType() ?
4455 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004456}
4457
Justin Holewinski83e96682012-05-24 17:43:12 +00004458void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004459 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004460 for (auto &I : FI.arguments())
4461 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004462
4463 // Always honor user-specified calling convention.
4464 if (FI.getCallingConvention() != llvm::CallingConv::C)
4465 return;
4466
John McCall882987f2013-02-28 19:01:20 +00004467 FI.setEffectiveCallingConvention(getRuntimeCC());
4468}
4469
Justin Holewinski83e96682012-05-24 17:43:12 +00004470llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4471 CodeGenFunction &CFG) const {
4472 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004473}
4474
Justin Holewinski83e96682012-05-24 17:43:12 +00004475void NVPTXTargetCodeGenInfo::
4476SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4477 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004478 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4479 if (!FD) return;
4480
4481 llvm::Function *F = cast<llvm::Function>(GV);
4482
4483 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004484 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004485 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004486 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004487 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004488 // OpenCL __kernel functions get kernel metadata
4489 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004490 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004491 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004492 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004493 }
Justin Holewinski38031972011-10-05 17:58:44 +00004494
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004495 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004496 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004497 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004498 // __global__ functions cannot be called from the device, we do not
4499 // need to set the noinline attribute.
Aaron Ballman9ead1242013-12-19 02:39:40 +00004500 if (FD->hasAttr<CUDAGlobalAttr>())
Justin Holewinski36837432013-03-30 14:38:24 +00004501 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004502 }
4503}
4504
Justin Holewinski36837432013-03-30 14:38:24 +00004505void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4506 llvm::Module *M = F->getParent();
4507 llvm::LLVMContext &Ctx = M->getContext();
4508
4509 // Get "nvvm.annotations" metadata node
4510 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4511
4512 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4513 llvm::SmallVector<llvm::Value *, 3> MDVals;
4514 MDVals.push_back(F);
4515 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4516 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4517
4518 // Append metadata to nvvm.annotations
4519 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4520}
4521
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004522}
4523
4524//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004525// SystemZ ABI Implementation
4526//===----------------------------------------------------------------------===//
4527
4528namespace {
4529
4530class SystemZABIInfo : public ABIInfo {
4531public:
4532 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4533
4534 bool isPromotableIntegerType(QualType Ty) const;
4535 bool isCompoundType(QualType Ty) const;
4536 bool isFPArgumentType(QualType Ty) const;
4537
4538 ABIArgInfo classifyReturnType(QualType RetTy) const;
4539 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4540
Craig Topper4f12f102014-03-12 06:41:41 +00004541 void computeInfo(CGFunctionInfo &FI) const override {
Ulrich Weigand47445072013-05-06 16:26:41 +00004542 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004543 for (auto &I : FI.arguments())
4544 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00004545 }
4546
Craig Topper4f12f102014-03-12 06:41:41 +00004547 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4548 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00004549};
4550
4551class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4552public:
4553 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4554 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4555};
4556
4557}
4558
4559bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4560 // Treat an enum type as its underlying type.
4561 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4562 Ty = EnumTy->getDecl()->getIntegerType();
4563
4564 // Promotable integer types are required to be promoted by the ABI.
4565 if (Ty->isPromotableIntegerType())
4566 return true;
4567
4568 // 32-bit values must also be promoted.
4569 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4570 switch (BT->getKind()) {
4571 case BuiltinType::Int:
4572 case BuiltinType::UInt:
4573 return true;
4574 default:
4575 return false;
4576 }
4577 return false;
4578}
4579
4580bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4581 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4582}
4583
4584bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4585 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4586 switch (BT->getKind()) {
4587 case BuiltinType::Float:
4588 case BuiltinType::Double:
4589 return true;
4590 default:
4591 return false;
4592 }
4593
4594 if (const RecordType *RT = Ty->getAsStructureType()) {
4595 const RecordDecl *RD = RT->getDecl();
4596 bool Found = false;
4597
4598 // If this is a C++ record, check the bases first.
4599 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00004600 for (const auto &I : CXXRD->bases()) {
4601 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00004602
4603 // Empty bases don't affect things either way.
4604 if (isEmptyRecord(getContext(), Base, true))
4605 continue;
4606
4607 if (Found)
4608 return false;
4609 Found = isFPArgumentType(Base);
4610 if (!Found)
4611 return false;
4612 }
4613
4614 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004615 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00004616 // Empty bitfields don't affect things either way.
4617 // Unlike isSingleElementStruct(), empty structure and array fields
4618 // do count. So do anonymous bitfields that aren't zero-sized.
4619 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4620 return true;
4621
4622 // Unlike isSingleElementStruct(), arrays do not count.
4623 // Nested isFPArgumentType structures still do though.
4624 if (Found)
4625 return false;
4626 Found = isFPArgumentType(FD->getType());
4627 if (!Found)
4628 return false;
4629 }
4630
4631 // Unlike isSingleElementStruct(), trailing padding is allowed.
4632 // An 8-byte aligned struct s { float f; } is passed as a double.
4633 return Found;
4634 }
4635
4636 return false;
4637}
4638
4639llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4640 CodeGenFunction &CGF) const {
4641 // Assume that va_list type is correct; should be pointer to LLVM type:
4642 // struct {
4643 // i64 __gpr;
4644 // i64 __fpr;
4645 // i8 *__overflow_arg_area;
4646 // i8 *__reg_save_area;
4647 // };
4648
4649 // Every argument occupies 8 bytes and is passed by preference in either
4650 // GPRs or FPRs.
4651 Ty = CGF.getContext().getCanonicalType(Ty);
4652 ABIArgInfo AI = classifyArgumentType(Ty);
4653 bool InFPRs = isFPArgumentType(Ty);
4654
4655 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4656 bool IsIndirect = AI.isIndirect();
4657 unsigned UnpaddedBitSize;
4658 if (IsIndirect) {
4659 APTy = llvm::PointerType::getUnqual(APTy);
4660 UnpaddedBitSize = 64;
4661 } else
4662 UnpaddedBitSize = getContext().getTypeSize(Ty);
4663 unsigned PaddedBitSize = 64;
4664 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4665
4666 unsigned PaddedSize = PaddedBitSize / 8;
4667 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4668
4669 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4670 if (InFPRs) {
4671 MaxRegs = 4; // Maximum of 4 FPR arguments
4672 RegCountField = 1; // __fpr
4673 RegSaveIndex = 16; // save offset for f0
4674 RegPadding = 0; // floats are passed in the high bits of an FPR
4675 } else {
4676 MaxRegs = 5; // Maximum of 5 GPR arguments
4677 RegCountField = 0; // __gpr
4678 RegSaveIndex = 2; // save offset for r2
4679 RegPadding = Padding; // values are passed in the low bits of a GPR
4680 }
4681
4682 llvm::Value *RegCountPtr =
4683 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4684 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4685 llvm::Type *IndexTy = RegCount->getType();
4686 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4687 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00004688 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00004689
4690 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4691 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4692 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4693 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4694
4695 // Emit code to load the value if it was passed in registers.
4696 CGF.EmitBlock(InRegBlock);
4697
4698 // Work out the address of an argument register.
4699 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4700 llvm::Value *ScaledRegCount =
4701 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4702 llvm::Value *RegBase =
4703 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4704 llvm::Value *RegOffset =
4705 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4706 llvm::Value *RegSaveAreaPtr =
4707 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4708 llvm::Value *RegSaveArea =
4709 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4710 llvm::Value *RawRegAddr =
4711 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4712 llvm::Value *RegAddr =
4713 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4714
4715 // Update the register count
4716 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4717 llvm::Value *NewRegCount =
4718 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4719 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4720 CGF.EmitBranch(ContBlock);
4721
4722 // Emit code to load the value if it was passed in memory.
4723 CGF.EmitBlock(InMemBlock);
4724
4725 // Work out the address of a stack argument.
4726 llvm::Value *OverflowArgAreaPtr =
4727 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4728 llvm::Value *OverflowArgArea =
4729 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4730 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4731 llvm::Value *RawMemAddr =
4732 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4733 llvm::Value *MemAddr =
4734 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4735
4736 // Update overflow_arg_area_ptr pointer
4737 llvm::Value *NewOverflowArgArea =
4738 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4739 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4740 CGF.EmitBranch(ContBlock);
4741
4742 // Return the appropriate result.
4743 CGF.EmitBlock(ContBlock);
4744 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4745 ResAddr->addIncoming(RegAddr, InRegBlock);
4746 ResAddr->addIncoming(MemAddr, InMemBlock);
4747
4748 if (IsIndirect)
4749 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4750
4751 return ResAddr;
4752}
4753
John McCall1fe2a8c2013-06-18 02:46:29 +00004754bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4755 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4756 assert(Triple.getArch() == llvm::Triple::x86);
4757
4758 switch (Opts.getStructReturnConvention()) {
4759 case CodeGenOptions::SRCK_Default:
4760 break;
4761 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4762 return false;
4763 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4764 return true;
4765 }
4766
4767 if (Triple.isOSDarwin())
4768 return true;
4769
4770 switch (Triple.getOS()) {
4771 case llvm::Triple::Cygwin:
4772 case llvm::Triple::MinGW32:
4773 case llvm::Triple::AuroraUX:
4774 case llvm::Triple::DragonFly:
4775 case llvm::Triple::FreeBSD:
4776 case llvm::Triple::OpenBSD:
4777 case llvm::Triple::Bitrig:
4778 case llvm::Triple::Win32:
4779 return true;
4780 default:
4781 return false;
4782 }
4783}
Ulrich Weigand47445072013-05-06 16:26:41 +00004784
4785ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4786 if (RetTy->isVoidType())
4787 return ABIArgInfo::getIgnore();
4788 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4789 return ABIArgInfo::getIndirect(0);
4790 return (isPromotableIntegerType(RetTy) ?
4791 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4792}
4793
4794ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4795 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00004796 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00004797 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4798
4799 // Integers and enums are extended to full register width.
4800 if (isPromotableIntegerType(Ty))
4801 return ABIArgInfo::getExtend();
4802
4803 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4804 uint64_t Size = getContext().getTypeSize(Ty);
4805 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00004806 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004807
4808 // Handle small structures.
4809 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4810 // Structures with flexible arrays have variable length, so really
4811 // fail the size test above.
4812 const RecordDecl *RD = RT->getDecl();
4813 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00004814 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004815
4816 // The structure is passed as an unextended integer, a float, or a double.
4817 llvm::Type *PassTy;
4818 if (isFPArgumentType(Ty)) {
4819 assert(Size == 32 || Size == 64);
4820 if (Size == 32)
4821 PassTy = llvm::Type::getFloatTy(getVMContext());
4822 else
4823 PassTy = llvm::Type::getDoubleTy(getVMContext());
4824 } else
4825 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4826 return ABIArgInfo::getDirect(PassTy);
4827 }
4828
4829 // Non-structure compounds are passed indirectly.
4830 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00004831 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004832
4833 return ABIArgInfo::getDirect(0);
4834}
4835
4836//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004837// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004838//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004839
4840namespace {
4841
4842class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4843public:
Chris Lattner2b037972010-07-29 02:01:43 +00004844 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4845 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004846 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004847 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004848};
4849
4850}
4851
4852void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4853 llvm::GlobalValue *GV,
4854 CodeGen::CodeGenModule &M) const {
4855 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4856 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4857 // Handle 'interrupt' attribute:
4858 llvm::Function *F = cast<llvm::Function>(GV);
4859
4860 // Step 1: Set ISR calling convention.
4861 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4862
4863 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00004864 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004865
4866 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004867 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004868 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004869 "__isr_" + Twine(Num),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004870 GV, &M.getModule());
4871 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004872 }
4873}
4874
Chris Lattner0cf24192010-06-28 20:05:43 +00004875//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00004876// MIPS ABI Implementation. This works for both little-endian and
4877// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00004878//===----------------------------------------------------------------------===//
4879
John McCall943fae92010-05-27 06:19:26 +00004880namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004881class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00004882 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004883 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4884 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004885 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004886 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004887 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004888 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004889public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004890 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004891 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004892 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00004893
4894 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004895 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00004896 void computeInfo(CGFunctionInfo &FI) const override;
4897 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4898 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004899};
4900
John McCall943fae92010-05-27 06:19:26 +00004901class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004902 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00004903public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004904 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4905 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00004906 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00004907
Craig Topper4f12f102014-03-12 06:41:41 +00004908 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00004909 return 29;
4910 }
4911
Reed Kotler373feca2013-01-16 17:10:28 +00004912 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004913 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00004914 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4915 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00004916 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00004917 if (FD->hasAttr<Mips16Attr>()) {
4918 Fn->addFnAttr("mips16");
4919 }
4920 else if (FD->hasAttr<NoMips16Attr>()) {
4921 Fn->addFnAttr("nomips16");
4922 }
Reed Kotler373feca2013-01-16 17:10:28 +00004923 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00004924
John McCall943fae92010-05-27 06:19:26 +00004925 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004926 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00004927
Craig Topper4f12f102014-03-12 06:41:41 +00004928 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004929 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00004930 }
John McCall943fae92010-05-27 06:19:26 +00004931};
4932}
4933
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004934void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004935 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004936 llvm::IntegerType *IntTy =
4937 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004938
4939 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4940 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4941 ArgList.push_back(IntTy);
4942
4943 // If necessary, add one more integer type to ArgList.
4944 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4945
4946 if (R)
4947 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004948}
4949
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004950// In N32/64, an aligned double precision floating point field is passed in
4951// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004952llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004953 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4954
4955 if (IsO32) {
4956 CoerceToIntArgs(TySize, ArgList);
4957 return llvm::StructType::get(getVMContext(), ArgList);
4958 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004959
Akira Hatanaka02e13e52012-01-12 00:52:17 +00004960 if (Ty->isComplexType())
4961 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00004962
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004963 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004964
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004965 // Unions/vectors are passed in integer registers.
4966 if (!RT || !RT->isStructureOrClassType()) {
4967 CoerceToIntArgs(TySize, ArgList);
4968 return llvm::StructType::get(getVMContext(), ArgList);
4969 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004970
4971 const RecordDecl *RD = RT->getDecl();
4972 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004973 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004974
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004975 uint64_t LastOffset = 0;
4976 unsigned idx = 0;
4977 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4978
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004979 // Iterate over fields in the struct/class and check if there are any aligned
4980 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004981 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4982 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004983 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004984 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4985
4986 if (!BT || BT->getKind() != BuiltinType::Double)
4987 continue;
4988
4989 uint64_t Offset = Layout.getFieldOffset(idx);
4990 if (Offset % 64) // Ignore doubles that are not aligned.
4991 continue;
4992
4993 // Add ((Offset - LastOffset) / 64) args of type i64.
4994 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4995 ArgList.push_back(I64);
4996
4997 // Add double type.
4998 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4999 LastOffset = Offset + 64;
5000 }
5001
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005002 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5003 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005004
5005 return llvm::StructType::get(getVMContext(), ArgList);
5006}
5007
Akira Hatanakaddd66342013-10-29 18:41:15 +00005008llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5009 uint64_t Offset) const {
5010 if (OrigOffset + MinABIStackAlignInBytes > Offset)
5011 return 0;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005012
Akira Hatanakaddd66342013-10-29 18:41:15 +00005013 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005014}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005015
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005016ABIArgInfo
5017MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005018 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005019 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005020 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005021
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005022 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5023 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005024 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5025 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005026
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005027 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005028 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005029 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005030 return ABIArgInfo::getIgnore();
5031
Mark Lacey3825e832013-10-06 01:33:34 +00005032 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005033 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005034 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005035 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005036
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005037 // If we have reached here, aggregates are passed directly by coercing to
5038 // another structure type. Padding is inserted if the offset of the
5039 // aggregate is unaligned.
5040 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00005041 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005042 }
5043
5044 // Treat an enum type as its underlying type.
5045 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5046 Ty = EnumTy->getDecl()->getIntegerType();
5047
Akira Hatanaka1632af62012-01-09 19:31:25 +00005048 if (Ty->isPromotableIntegerType())
5049 return ABIArgInfo::getExtend();
5050
Akira Hatanakaddd66342013-10-29 18:41:15 +00005051 return ABIArgInfo::getDirect(
5052 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005053}
5054
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005055llvm::Type*
5056MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005057 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005058 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005059
Akira Hatanakab6f74432012-02-09 18:49:26 +00005060 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005061 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005062 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5063 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005064
Akira Hatanakab6f74432012-02-09 18:49:26 +00005065 // N32/64 returns struct/classes in floating point registers if the
5066 // following conditions are met:
5067 // 1. The size of the struct/class is no larger than 128-bit.
5068 // 2. The struct/class has one or two fields all of which are floating
5069 // point types.
5070 // 3. The offset of the first field is zero (this follows what gcc does).
5071 //
5072 // Any other composite results are returned in integer registers.
5073 //
5074 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5075 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5076 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005077 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005078
Akira Hatanakab6f74432012-02-09 18:49:26 +00005079 if (!BT || !BT->isFloatingPoint())
5080 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005081
David Blaikie2d7c57e2012-04-30 02:36:29 +00005082 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005083 }
5084
5085 if (b == e)
5086 return llvm::StructType::get(getVMContext(), RTList,
5087 RD->hasAttr<PackedAttr>());
5088
5089 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005090 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005091 }
5092
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005093 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005094 return llvm::StructType::get(getVMContext(), RTList);
5095}
5096
Akira Hatanakab579fe52011-06-02 00:09:17 +00005097ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005098 uint64_t Size = getContext().getTypeSize(RetTy);
5099
5100 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005101 return ABIArgInfo::getIgnore();
5102
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005103 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey3825e832013-10-06 01:33:34 +00005104 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005105 return ABIArgInfo::getIndirect(0);
5106
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005107 if (Size <= 128) {
5108 if (RetTy->isAnyComplexType())
5109 return ABIArgInfo::getDirect();
5110
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005111 // O32 returns integer vectors in registers.
5112 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
5113 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5114
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005115 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005116 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5117 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005118
5119 return ABIArgInfo::getIndirect(0);
5120 }
5121
5122 // Treat an enum type as its underlying type.
5123 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5124 RetTy = EnumTy->getDecl()->getIntegerType();
5125
5126 return (RetTy->isPromotableIntegerType() ?
5127 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5128}
5129
5130void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005131 ABIArgInfo &RetInfo = FI.getReturnInfo();
5132 RetInfo = classifyReturnType(FI.getReturnType());
5133
5134 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005135 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005136
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005137 for (auto &I : FI.arguments())
5138 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005139}
5140
5141llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5142 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00005143 llvm::Type *BP = CGF.Int8PtrTy;
5144 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005145
5146 CGBuilderTy &Builder = CGF.Builder;
5147 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5148 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00005149 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005150 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5151 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00005152 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00005153 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005154
5155 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00005156 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5157 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5158 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5159 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005160 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5161 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5162 }
5163 else
5164 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5165
5166 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00005167 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005168 uint64_t Offset =
5169 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5170 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00005171 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005172 "ap.next");
5173 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5174
5175 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005176}
5177
John McCall943fae92010-05-27 06:19:26 +00005178bool
5179MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5180 llvm::Value *Address) const {
5181 // This information comes from gcc's implementation, which seems to
5182 // as canonical as it gets.
5183
John McCall943fae92010-05-27 06:19:26 +00005184 // Everything on MIPS is 4 bytes. Double-precision FP registers
5185 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005186 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005187
5188 // 0-31 are the general purpose registers, $0 - $31.
5189 // 32-63 are the floating-point registers, $f0 - $f31.
5190 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5191 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005192 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005193
5194 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5195 // They are one bit wide and ignored here.
5196
5197 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5198 // (coprocessor 1 is the FP unit)
5199 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5200 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5201 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005202 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005203 return false;
5204}
5205
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005206//===----------------------------------------------------------------------===//
5207// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5208// Currently subclassed only to implement custom OpenCL C function attribute
5209// handling.
5210//===----------------------------------------------------------------------===//
5211
5212namespace {
5213
5214class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5215public:
5216 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5217 : DefaultTargetCodeGenInfo(CGT) {}
5218
Craig Topper4f12f102014-03-12 06:41:41 +00005219 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5220 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005221};
5222
5223void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5224 llvm::GlobalValue *GV,
5225 CodeGen::CodeGenModule &M) const {
5226 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5227 if (!FD) return;
5228
5229 llvm::Function *F = cast<llvm::Function>(GV);
5230
David Blaikiebbafb8a2012-03-11 07:00:24 +00005231 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005232 if (FD->hasAttr<OpenCLKernelAttr>()) {
5233 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005234 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005235 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5236 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005237 // Convert the reqd_work_group_size() attributes to metadata.
5238 llvm::LLVMContext &Context = F->getContext();
5239 llvm::NamedMDNode *OpenCLMetadata =
5240 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5241
5242 SmallVector<llvm::Value*, 5> Operands;
5243 Operands.push_back(F);
5244
Chris Lattnerece04092012-02-07 00:39:47 +00005245 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005246 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005247 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005248 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005249 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005250 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005251
5252 // Add a boolean constant operand for "required" (true) or "hint" (false)
5253 // for implementing the work_group_size_hint attr later. Currently
5254 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005255 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005256 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5257 }
5258 }
5259 }
5260}
5261
5262}
John McCall943fae92010-05-27 06:19:26 +00005263
Tony Linthicum76329bf2011-12-12 21:14:55 +00005264//===----------------------------------------------------------------------===//
5265// Hexagon ABI Implementation
5266//===----------------------------------------------------------------------===//
5267
5268namespace {
5269
5270class HexagonABIInfo : public ABIInfo {
5271
5272
5273public:
5274 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5275
5276private:
5277
5278 ABIArgInfo classifyReturnType(QualType RetTy) const;
5279 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5280
Craig Topper4f12f102014-03-12 06:41:41 +00005281 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005282
Craig Topper4f12f102014-03-12 06:41:41 +00005283 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5284 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005285};
5286
5287class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5288public:
5289 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5290 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5291
Craig Topper4f12f102014-03-12 06:41:41 +00005292 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005293 return 29;
5294 }
5295};
5296
5297}
5298
5299void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5300 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005301 for (auto &I : FI.arguments())
5302 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005303}
5304
5305ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5306 if (!isAggregateTypeForABI(Ty)) {
5307 // Treat an enum type as its underlying type.
5308 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5309 Ty = EnumTy->getDecl()->getIntegerType();
5310
5311 return (Ty->isPromotableIntegerType() ?
5312 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5313 }
5314
5315 // Ignore empty records.
5316 if (isEmptyRecord(getContext(), Ty, true))
5317 return ABIArgInfo::getIgnore();
5318
Mark Lacey3825e832013-10-06 01:33:34 +00005319 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005320 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005321
5322 uint64_t Size = getContext().getTypeSize(Ty);
5323 if (Size > 64)
5324 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5325 // Pass in the smallest viable integer type.
5326 else if (Size > 32)
5327 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5328 else if (Size > 16)
5329 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5330 else if (Size > 8)
5331 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5332 else
5333 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5334}
5335
5336ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5337 if (RetTy->isVoidType())
5338 return ABIArgInfo::getIgnore();
5339
5340 // Large vector types should be returned via memory.
5341 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5342 return ABIArgInfo::getIndirect(0);
5343
5344 if (!isAggregateTypeForABI(RetTy)) {
5345 // Treat an enum type as its underlying type.
5346 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5347 RetTy = EnumTy->getDecl()->getIntegerType();
5348
5349 return (RetTy->isPromotableIntegerType() ?
5350 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5351 }
5352
5353 // Structures with either a non-trivial destructor or a non-trivial
5354 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00005355 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum76329bf2011-12-12 21:14:55 +00005356 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5357
5358 if (isEmptyRecord(getContext(), RetTy, true))
5359 return ABIArgInfo::getIgnore();
5360
5361 // Aggregates <= 8 bytes are returned in r0; other aggregates
5362 // are returned indirectly.
5363 uint64_t Size = getContext().getTypeSize(RetTy);
5364 if (Size <= 64) {
5365 // Return in the smallest viable integer type.
5366 if (Size <= 8)
5367 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5368 if (Size <= 16)
5369 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5370 if (Size <= 32)
5371 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5372 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5373 }
5374
5375 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5376}
5377
5378llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005379 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005380 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005381 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005382
5383 CGBuilderTy &Builder = CGF.Builder;
5384 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5385 "ap");
5386 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5387 llvm::Type *PTy =
5388 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5389 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5390
5391 uint64_t Offset =
5392 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5393 llvm::Value *NextAddr =
5394 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5395 "ap.next");
5396 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5397
5398 return AddrTyped;
5399}
5400
5401
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005402//===----------------------------------------------------------------------===//
5403// SPARC v9 ABI Implementation.
5404// Based on the SPARC Compliance Definition version 2.4.1.
5405//
5406// Function arguments a mapped to a nominal "parameter array" and promoted to
5407// registers depending on their type. Each argument occupies 8 or 16 bytes in
5408// the array, structs larger than 16 bytes are passed indirectly.
5409//
5410// One case requires special care:
5411//
5412// struct mixed {
5413// int i;
5414// float f;
5415// };
5416//
5417// When a struct mixed is passed by value, it only occupies 8 bytes in the
5418// parameter array, but the int is passed in an integer register, and the float
5419// is passed in a floating point register. This is represented as two arguments
5420// with the LLVM IR inreg attribute:
5421//
5422// declare void f(i32 inreg %i, float inreg %f)
5423//
5424// The code generator will only allocate 4 bytes from the parameter array for
5425// the inreg arguments. All other arguments are allocated a multiple of 8
5426// bytes.
5427//
5428namespace {
5429class SparcV9ABIInfo : public ABIInfo {
5430public:
5431 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5432
5433private:
5434 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005435 void computeInfo(CGFunctionInfo &FI) const override;
5436 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5437 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005438
5439 // Coercion type builder for structs passed in registers. The coercion type
5440 // serves two purposes:
5441 //
5442 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5443 // in registers.
5444 // 2. Expose aligned floating point elements as first-level elements, so the
5445 // code generator knows to pass them in floating point registers.
5446 //
5447 // We also compute the InReg flag which indicates that the struct contains
5448 // aligned 32-bit floats.
5449 //
5450 struct CoerceBuilder {
5451 llvm::LLVMContext &Context;
5452 const llvm::DataLayout &DL;
5453 SmallVector<llvm::Type*, 8> Elems;
5454 uint64_t Size;
5455 bool InReg;
5456
5457 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5458 : Context(c), DL(dl), Size(0), InReg(false) {}
5459
5460 // Pad Elems with integers until Size is ToSize.
5461 void pad(uint64_t ToSize) {
5462 assert(ToSize >= Size && "Cannot remove elements");
5463 if (ToSize == Size)
5464 return;
5465
5466 // Finish the current 64-bit word.
5467 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5468 if (Aligned > Size && Aligned <= ToSize) {
5469 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5470 Size = Aligned;
5471 }
5472
5473 // Add whole 64-bit words.
5474 while (Size + 64 <= ToSize) {
5475 Elems.push_back(llvm::Type::getInt64Ty(Context));
5476 Size += 64;
5477 }
5478
5479 // Final in-word padding.
5480 if (Size < ToSize) {
5481 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5482 Size = ToSize;
5483 }
5484 }
5485
5486 // Add a floating point element at Offset.
5487 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5488 // Unaligned floats are treated as integers.
5489 if (Offset % Bits)
5490 return;
5491 // The InReg flag is only required if there are any floats < 64 bits.
5492 if (Bits < 64)
5493 InReg = true;
5494 pad(Offset);
5495 Elems.push_back(Ty);
5496 Size = Offset + Bits;
5497 }
5498
5499 // Add a struct type to the coercion type, starting at Offset (in bits).
5500 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5501 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5502 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5503 llvm::Type *ElemTy = StrTy->getElementType(i);
5504 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5505 switch (ElemTy->getTypeID()) {
5506 case llvm::Type::StructTyID:
5507 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5508 break;
5509 case llvm::Type::FloatTyID:
5510 addFloat(ElemOffset, ElemTy, 32);
5511 break;
5512 case llvm::Type::DoubleTyID:
5513 addFloat(ElemOffset, ElemTy, 64);
5514 break;
5515 case llvm::Type::FP128TyID:
5516 addFloat(ElemOffset, ElemTy, 128);
5517 break;
5518 case llvm::Type::PointerTyID:
5519 if (ElemOffset % 64 == 0) {
5520 pad(ElemOffset);
5521 Elems.push_back(ElemTy);
5522 Size += 64;
5523 }
5524 break;
5525 default:
5526 break;
5527 }
5528 }
5529 }
5530
5531 // Check if Ty is a usable substitute for the coercion type.
5532 bool isUsableType(llvm::StructType *Ty) const {
5533 if (Ty->getNumElements() != Elems.size())
5534 return false;
5535 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5536 if (Elems[i] != Ty->getElementType(i))
5537 return false;
5538 return true;
5539 }
5540
5541 // Get the coercion type as a literal struct type.
5542 llvm::Type *getType() const {
5543 if (Elems.size() == 1)
5544 return Elems.front();
5545 else
5546 return llvm::StructType::get(Context, Elems);
5547 }
5548 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005549};
5550} // end anonymous namespace
5551
5552ABIArgInfo
5553SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5554 if (Ty->isVoidType())
5555 return ABIArgInfo::getIgnore();
5556
5557 uint64_t Size = getContext().getTypeSize(Ty);
5558
5559 // Anything too big to fit in registers is passed with an explicit indirect
5560 // pointer / sret pointer.
5561 if (Size > SizeLimit)
5562 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5563
5564 // Treat an enum type as its underlying type.
5565 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5566 Ty = EnumTy->getDecl()->getIntegerType();
5567
5568 // Integer types smaller than a register are extended.
5569 if (Size < 64 && Ty->isIntegerType())
5570 return ABIArgInfo::getExtend();
5571
5572 // Other non-aggregates go in registers.
5573 if (!isAggregateTypeForABI(Ty))
5574 return ABIArgInfo::getDirect();
5575
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00005576 // If a C++ object has either a non-trivial copy constructor or a non-trivial
5577 // destructor, it is passed with an explicit indirect pointer / sret pointer.
5578 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5579 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5580
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005581 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005582 // Build a coercion type from the LLVM struct type.
5583 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5584 if (!StrTy)
5585 return ABIArgInfo::getDirect();
5586
5587 CoerceBuilder CB(getVMContext(), getDataLayout());
5588 CB.addStruct(0, StrTy);
5589 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5590
5591 // Try to use the original type for coercion.
5592 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5593
5594 if (CB.InReg)
5595 return ABIArgInfo::getDirectInReg(CoerceTy);
5596 else
5597 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005598}
5599
5600llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5601 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005602 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5603 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5604 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5605 AI.setCoerceToType(ArgTy);
5606
5607 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5608 CGBuilderTy &Builder = CGF.Builder;
5609 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5610 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5611 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5612 llvm::Value *ArgAddr;
5613 unsigned Stride;
5614
5615 switch (AI.getKind()) {
5616 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00005617 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005618 llvm_unreachable("Unsupported ABI kind for va_arg");
5619
5620 case ABIArgInfo::Extend:
5621 Stride = 8;
5622 ArgAddr = Builder
5623 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5624 "extend");
5625 break;
5626
5627 case ABIArgInfo::Direct:
5628 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5629 ArgAddr = Addr;
5630 break;
5631
5632 case ABIArgInfo::Indirect:
5633 Stride = 8;
5634 ArgAddr = Builder.CreateBitCast(Addr,
5635 llvm::PointerType::getUnqual(ArgPtrTy),
5636 "indirect");
5637 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5638 break;
5639
5640 case ABIArgInfo::Ignore:
5641 return llvm::UndefValue::get(ArgPtrTy);
5642 }
5643
5644 // Update VAList.
5645 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5646 Builder.CreateStore(Addr, VAListAddrAsBPP);
5647
5648 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005649}
5650
5651void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5652 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005653 for (auto &I : FI.arguments())
5654 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005655}
5656
5657namespace {
5658class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5659public:
5660 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5661 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00005662
Craig Topper4f12f102014-03-12 06:41:41 +00005663 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00005664 return 14;
5665 }
5666
5667 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005668 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005669};
5670} // end anonymous namespace
5671
Roman Divackyf02c9942014-02-24 18:46:27 +00005672bool
5673SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5674 llvm::Value *Address) const {
5675 // This is calculated from the LLVM and GCC tables and verified
5676 // against gcc output. AFAIK all ABIs use the same encoding.
5677
5678 CodeGen::CGBuilderTy &Builder = CGF.Builder;
5679
5680 llvm::IntegerType *i8 = CGF.Int8Ty;
5681 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
5682 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
5683
5684 // 0-31: the 8-byte general-purpose registers
5685 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
5686
5687 // 32-63: f0-31, the 4-byte floating-point registers
5688 AssignToArrayRange(Builder, Address, Four8, 32, 63);
5689
5690 // Y = 64
5691 // PSR = 65
5692 // WIM = 66
5693 // TBR = 67
5694 // PC = 68
5695 // NPC = 69
5696 // FSR = 70
5697 // CSR = 71
5698 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
5699
5700 // 72-87: d0-15, the 8-byte floating-point registers
5701 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
5702
5703 return false;
5704}
5705
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005706
Robert Lytton0e076492013-08-13 09:43:10 +00005707//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00005708// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00005709//===----------------------------------------------------------------------===//
5710namespace {
Robert Lytton7d1db152013-08-19 09:46:39 +00005711class XCoreABIInfo : public DefaultABIInfo {
5712public:
5713 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005714 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5715 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00005716};
5717
Robert Lyttond21e2d72014-03-03 13:45:29 +00005718class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton0e076492013-08-13 09:43:10 +00005719public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00005720 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00005721 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton0e076492013-08-13 09:43:10 +00005722};
Robert Lytton2d196952013-10-11 10:29:34 +00005723} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00005724
Robert Lytton7d1db152013-08-19 09:46:39 +00005725llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5726 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00005727 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00005728
Robert Lytton2d196952013-10-11 10:29:34 +00005729 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00005730 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5731 CGF.Int8PtrPtrTy);
5732 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00005733
Robert Lytton2d196952013-10-11 10:29:34 +00005734 // Handle the argument.
5735 ABIArgInfo AI = classifyArgumentType(Ty);
5736 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5737 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5738 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00005739 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00005740 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00005741 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00005742 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00005743 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00005744 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00005745 llvm_unreachable("Unsupported ABI kind for va_arg");
5746 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00005747 Val = llvm::UndefValue::get(ArgPtrTy);
5748 ArgSize = 0;
5749 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005750 case ABIArgInfo::Extend:
5751 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00005752 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5753 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5754 if (ArgSize < 4)
5755 ArgSize = 4;
5756 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005757 case ABIArgInfo::Indirect:
5758 llvm::Value *ArgAddr;
5759 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5760 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00005761 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5762 ArgSize = 4;
5763 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005764 }
Robert Lytton2d196952013-10-11 10:29:34 +00005765
5766 // Increment the VAList.
5767 if (ArgSize) {
5768 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5769 Builder.CreateStore(APN, VAListAddrAsBPP);
5770 }
5771 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00005772}
Robert Lytton0e076492013-08-13 09:43:10 +00005773
5774//===----------------------------------------------------------------------===//
5775// Driver code
5776//===----------------------------------------------------------------------===//
5777
Chris Lattner2b037972010-07-29 02:01:43 +00005778const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005779 if (TheTargetCodeGenInfo)
5780 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005781
John McCallc8e01702013-04-16 22:48:15 +00005782 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00005783 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00005784 default:
Chris Lattner2b037972010-07-29 02:01:43 +00005785 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00005786
Derek Schuff09338a22012-09-06 17:37:28 +00005787 case llvm::Triple::le32:
5788 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00005789 case llvm::Triple::mips:
5790 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005791 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
5792
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00005793 case llvm::Triple::mips64:
5794 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005795 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
5796
Tim Northover9bb857a2013-01-31 12:13:10 +00005797 case llvm::Triple::aarch64:
Christian Pirker9b019ae2014-02-25 13:51:00 +00005798 case llvm::Triple::aarch64_be:
Tim Northover9bb857a2013-01-31 12:13:10 +00005799 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5800
Daniel Dunbard59655c2009-09-12 00:59:49 +00005801 case llvm::Triple::arm:
5802 case llvm::Triple::thumb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005803 {
5804 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCallc8e01702013-04-16 22:48:15 +00005805 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005806 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00005807 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00005808 (CodeGenOpts.FloatABI != "soft" &&
5809 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005810 Kind = ARMABIInfo::AAPCS_VFP;
5811
Derek Schuffa2020962012-10-16 22:30:41 +00005812 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00005813 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00005814 return *(TheTargetCodeGenInfo =
5815 new NaClARMTargetCodeGenInfo(Types, Kind));
5816 default:
5817 return *(TheTargetCodeGenInfo =
5818 new ARMTargetCodeGenInfo(Types, Kind));
5819 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005820 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00005821
John McCallea8d8bb2010-03-11 00:10:12 +00005822 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00005823 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00005824 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00005825 if (Triple.isOSBinFormatELF())
5826 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5827 else
5828 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00005829 case llvm::Triple::ppc64le:
5830 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5831 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00005832
Peter Collingbournec947aae2012-05-20 23:28:41 +00005833 case llvm::Triple::nvptx:
5834 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00005835 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005836
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005837 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00005838 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00005839
Ulrich Weigand47445072013-05-06 16:26:41 +00005840 case llvm::Triple::systemz:
5841 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5842
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005843 case llvm::Triple::tce:
5844 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5845
Eli Friedman33465822011-07-08 23:31:17 +00005846 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00005847 bool IsDarwinVectorABI = Triple.isOSDarwin();
5848 bool IsSmallStructInRegABI =
5849 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5850 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005851
John McCall1fe2a8c2013-06-18 02:46:29 +00005852 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00005853 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005854 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00005855 IsDarwinVectorABI, IsSmallStructInRegABI,
5856 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005857 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00005858 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005859 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00005860 new X86_32TargetCodeGenInfo(Types,
5861 IsDarwinVectorABI, IsSmallStructInRegABI,
5862 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00005863 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005864 }
Eli Friedman33465822011-07-08 23:31:17 +00005865 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005866
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005867 case llvm::Triple::x86_64: {
John McCallc8e01702013-04-16 22:48:15 +00005868 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005869
Chris Lattner04dc9572010-08-31 16:44:54 +00005870 switch (Triple.getOS()) {
5871 case llvm::Triple::Win32:
NAKAMURA Takumi31ea2f12011-02-17 08:51:38 +00005872 case llvm::Triple::MinGW32:
Chris Lattner04dc9572010-08-31 16:44:54 +00005873 case llvm::Triple::Cygwin:
5874 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00005875 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00005876 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5877 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005878 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005879 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5880 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005881 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00005882 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00005883 case llvm::Triple::hexagon:
5884 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005885 case llvm::Triple::sparcv9:
5886 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005887 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00005888 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005889
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005890 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005891}