blob: c51a48646f43a7aa3fdf89b67fcb5bbd05e07fc4 [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"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000023#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000026#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000027
28#include <algorithm> // std::sort
29
Anton Korobeynikov244360d2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall943fae92010-05-27 06:19:26 +000033static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
34 llvm::Value *Array,
35 llvm::Value *Value,
36 unsigned FirstIndex,
37 unsigned LastIndex) {
38 // Alternatively, we could emit this as a loop in the source.
39 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
40 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
41 Builder.CreateStore(Value, Cell);
42 }
43}
44
John McCalla1dee5302010-08-22 10:59:02 +000045static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000046 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000047 T->isMemberFunctionPointerType();
48}
49
Anton Korobeynikov244360d2009-06-05 22:08:42 +000050ABIInfo::~ABIInfo() {}
51
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000052static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000053 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000054 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
55 if (!RD)
56 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000057 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000058}
59
60static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000061 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000062 const RecordType *RT = T->getAs<RecordType>();
63 if (!RT)
64 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000065 return getRecordArgABI(RT, CXXABI);
66}
67
68CGCXXABI &ABIInfo::getCXXABI() const {
69 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000070}
71
Chris Lattner2b037972010-07-29 02:01:43 +000072ASTContext &ABIInfo::getContext() const {
73 return CGT.getContext();
74}
75
76llvm::LLVMContext &ABIInfo::getVMContext() const {
77 return CGT.getLLVMContext();
78}
79
Micah Villmowdd31ca12012-10-08 16:25:52 +000080const llvm::DataLayout &ABIInfo::getDataLayout() const {
81 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000082}
83
John McCallc8e01702013-04-16 22:48:15 +000084const TargetInfo &ABIInfo::getTarget() const {
85 return CGT.getTarget();
86}
Chris Lattner2b037972010-07-29 02:01:43 +000087
Reid Klecknere9f6a712014-10-31 17:10:41 +000088bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
89 return false;
90}
91
92bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
93 uint64_t Members) const {
94 return false;
95}
96
Anton Korobeynikov244360d2009-06-05 22:08:42 +000097void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000098 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +000099 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000100 switch (TheKind) {
101 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000102 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000103 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000104 Ty->print(OS);
105 else
106 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000107 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000108 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000109 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000110 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000111 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000112 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000113 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000114 case InAlloca:
115 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
116 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000117 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000118 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000119 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000120 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000121 break;
122 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000123 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000124 break;
125 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127}
128
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000129TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
130
John McCall3480ef22011-08-30 01:42:09 +0000131// If someone can figure out a general rule for this, that would be great.
132// It's probably just doomed to be platform-dependent, though.
133unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
134 // Verified for:
135 // x86-64 FreeBSD, Linux, Darwin
136 // x86-32 FreeBSD, Linux, Darwin
137 // PowerPC Linux, Darwin
138 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000139 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000140 return 32;
141}
142
John McCalla729c622012-02-17 03:33:10 +0000143bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
144 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000145 // The following conventions are known to require this to be false:
146 // x86_stdcall
147 // MIPS
148 // For everything else, we just prefer false unless we opt out.
149 return false;
150}
151
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000152void
153TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
154 llvm::SmallString<24> &Opt) const {
155 // This assumes the user is passing a library name like "rt" instead of a
156 // filename like "librt.a/so", and that they don't care whether it's static or
157 // dynamic.
158 Opt = "-l";
159 Opt += Lib;
160}
161
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000162static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000163
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000164/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000165/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000166static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
167 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000168 if (FD->isUnnamedBitfield())
169 return true;
170
171 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000172
Eli Friedman0b3f2012011-11-18 03:47:20 +0000173 // Constant arrays of empty records count as empty, strip them off.
174 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000175 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000176 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
177 if (AT->getSize() == 0)
178 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000179 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000180 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000181
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000182 const RecordType *RT = FT->getAs<RecordType>();
183 if (!RT)
184 return false;
185
186 // C++ record fields are never empty, at least in the Itanium ABI.
187 //
188 // FIXME: We should use a predicate for whether this behavior is true in the
189 // current ABI.
190 if (isa<CXXRecordDecl>(RT->getDecl()))
191 return false;
192
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000194}
195
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000196/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000197/// fields. Note that a structure with a flexible array member is not
198/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000199static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000200 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000201 if (!RT)
202 return 0;
203 const RecordDecl *RD = RT->getDecl();
204 if (RD->hasFlexibleArrayMember())
205 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000206
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000207 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000208 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000209 for (const auto &I : CXXRD->bases())
210 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000211 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000212
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000213 for (const auto *I : RD->fields())
214 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215 return false;
216 return true;
217}
218
219/// isSingleElementStruct - Determine if a structure is a "single
220/// element struct", i.e. it has exactly one non-empty field or
221/// exactly one field which is itself a single element
222/// struct. Structures with flexible array members are never
223/// considered single element structs.
224///
225/// \return The field declaration for the single non-empty field, if
226/// it exists.
227static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
228 const RecordType *RT = T->getAsStructureType();
229 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000230 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000231
232 const RecordDecl *RD = RT->getDecl();
233 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000234 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000235
Craig Topper8a13c412014-05-21 05:09:00 +0000236 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000237
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000238 // If this is a C++ record, check the bases first.
239 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000240 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000241 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000242 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000243 continue;
244
245 // If we already found an element then this isn't a single-element struct.
246 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000247 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000248
249 // If this is non-empty and not a single element struct, the composite
250 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000251 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000252 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000253 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000254 }
255 }
256
257 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000258 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000259 QualType FT = FD->getType();
260
261 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000262 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000263 continue;
264
265 // If we already found an element then this isn't a single-element
266 // struct.
267 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000268 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000269
270 // Treat single element arrays as the element.
271 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
272 if (AT->getSize().getZExtValue() != 1)
273 break;
274 FT = AT->getElementType();
275 }
276
John McCalla1dee5302010-08-22 10:59:02 +0000277 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000278 Found = FT.getTypePtr();
279 } else {
280 Found = isSingleElementStruct(FT, Context);
281 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000282 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000283 }
284 }
285
Eli Friedmanee945342011-11-18 01:25:50 +0000286 // We don't consider a struct a single-element struct if it has
287 // padding beyond the element type.
288 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000289 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000290
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000291 return Found;
292}
293
294static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000295 // Treat complex types as the element type.
296 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
297 Ty = CTy->getElementType();
298
299 // Check for a type which we know has a simple scalar argument-passing
300 // convention without any padding. (We're specifically looking for 32
301 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000302 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000303 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000304 return false;
305
306 uint64_t Size = Context.getTypeSize(Ty);
307 return Size == 32 || Size == 64;
308}
309
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000310/// canExpandIndirectArgument - Test whether an argument type which is to be
311/// passed indirectly (on the stack) would have the equivalent layout if it was
312/// expanded into separate arguments. If so, we prefer to do the latter to avoid
313/// inhibiting optimizations.
314///
315// FIXME: This predicate is missing many cases, currently it just follows
316// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
317// should probably make this smarter, or better yet make the LLVM backend
318// capable of handling it.
319static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
320 // We can only expand structure types.
321 const RecordType *RT = Ty->getAs<RecordType>();
322 if (!RT)
323 return false;
324
325 // We can only expand (C) structures.
326 //
327 // FIXME: This needs to be generalized to handle classes as well.
328 const RecordDecl *RD = RT->getDecl();
329 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
330 return false;
331
Eli Friedmane5c85622011-11-18 01:32:26 +0000332 uint64_t Size = 0;
333
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000334 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000335 if (!is32Or64BitBasicType(FD->getType(), Context))
336 return false;
337
338 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
339 // how to expand them yet, and the predicate for telling if a bitfield still
340 // counts as "basic" is more complicated than what we were doing previously.
341 if (FD->isBitField())
342 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000343
344 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000345 }
346
Eli Friedmane5c85622011-11-18 01:32:26 +0000347 // Make sure there are not any holes in the struct.
348 if (Size != Context.getTypeSize(Ty))
349 return false;
350
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000351 return true;
352}
353
354namespace {
355/// DefaultABIInfo - The default implementation for ABI specific
356/// details. This implementation provides information which results in
357/// self-consistent and sensible LLVM IR generation, but does not
358/// conform to any particular ABI.
359class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000360public:
361 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000362
Chris Lattner458b2aa2010-07-29 02:16:43 +0000363 ABIArgInfo classifyReturnType(QualType RetTy) const;
364 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000365
Craig Topper4f12f102014-03-12 06:41:41 +0000366 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000367 if (!getCXXABI().classifyReturnType(FI))
368 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000369 for (auto &I : FI.arguments())
370 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000371 }
372
Craig Topper4f12f102014-03-12 06:41:41 +0000373 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
374 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000375};
376
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000377class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
378public:
Chris Lattner2b037972010-07-29 02:01:43 +0000379 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
380 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000381};
382
383llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
384 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000385 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000386}
387
Chris Lattner458b2aa2010-07-29 02:16:43 +0000388ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000389 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000390 return ABIArgInfo::getIndirect(0);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000391
Chris Lattner9723d6c2010-03-11 18:19:55 +0000392 // Treat an enum type as its underlying type.
393 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
394 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000395
Chris Lattner9723d6c2010-03-11 18:19:55 +0000396 return (Ty->isPromotableIntegerType() ?
397 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000398}
399
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000400ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
401 if (RetTy->isVoidType())
402 return ABIArgInfo::getIgnore();
403
404 if (isAggregateTypeForABI(RetTy))
405 return ABIArgInfo::getIndirect(0);
406
407 // Treat an enum type as its underlying type.
408 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
409 RetTy = EnumTy->getDecl()->getIntegerType();
410
411 return (RetTy->isPromotableIntegerType() ?
412 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
413}
414
Derek Schuff09338a22012-09-06 17:37:28 +0000415//===----------------------------------------------------------------------===//
416// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000417//
418// This is a simplified version of the x86_32 ABI. Arguments and return values
419// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000420//===----------------------------------------------------------------------===//
421
422class PNaClABIInfo : public ABIInfo {
423 public:
424 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
425
426 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000427 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000428
Craig Topper4f12f102014-03-12 06:41:41 +0000429 void computeInfo(CGFunctionInfo &FI) const override;
430 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
431 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000432};
433
434class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
435 public:
436 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
437 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
438};
439
440void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000441 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000442 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
443
Reid Kleckner40ca9132014-05-13 22:05:45 +0000444 for (auto &I : FI.arguments())
445 I.info = classifyArgumentType(I.type);
446}
Derek Schuff09338a22012-09-06 17:37:28 +0000447
448llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
449 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000450 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000451}
452
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000453/// \brief Classify argument of given type \p Ty.
454ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000455 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000456 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000457 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000458 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000459 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
460 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000461 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000462 } else if (Ty->isFloatingType()) {
463 // Floating-point types don't go inreg.
464 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000465 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000466
467 return (Ty->isPromotableIntegerType() ?
468 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000469}
470
471ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
472 if (RetTy->isVoidType())
473 return ABIArgInfo::getIgnore();
474
Eli Benderskye20dad62013-04-04 22:49:35 +0000475 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000476 if (isAggregateTypeForABI(RetTy))
477 return ABIArgInfo::getIndirect(0);
478
479 // Treat an enum type as its underlying type.
480 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
481 RetTy = EnumTy->getDecl()->getIntegerType();
482
483 return (RetTy->isPromotableIntegerType() ?
484 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
485}
486
Chad Rosier651c1832013-03-25 21:00:27 +0000487/// IsX86_MMXType - Return true if this is an MMX type.
488bool IsX86_MMXType(llvm::Type *IRType) {
489 // 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 +0000490 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
491 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
492 IRType->getScalarSizeInBits() != 64;
493}
494
Jay Foad7c57be32011-07-11 09:56:20 +0000495static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000496 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000497 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000498 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
499 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
500 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000501 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000502 }
503
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000504 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000505 }
506
507 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000508 return Ty;
509}
510
Reid Kleckner80944df2014-10-31 22:00:51 +0000511/// Returns true if this type can be passed in SSE registers with the
512/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
513static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
514 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
515 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
516 return true;
517 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
518 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
519 // registers specially.
520 unsigned VecSize = Context.getTypeSize(VT);
521 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
522 return true;
523 }
524 return false;
525}
526
527/// Returns true if this aggregate is small enough to be passed in SSE registers
528/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
529static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
530 return NumMembers <= 4;
531}
532
Chris Lattner0cf24192010-06-28 20:05:43 +0000533//===----------------------------------------------------------------------===//
534// X86-32 ABI Implementation
535//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000536
Reid Kleckner661f35b2014-01-18 01:12:41 +0000537/// \brief Similar to llvm::CCState, but for Clang.
538struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000539 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000540
541 unsigned CC;
542 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000543 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000544};
545
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000546/// X86_32ABIInfo - The X86-32 ABI information.
547class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000548 enum Class {
549 Integer,
550 Float
551 };
552
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000553 static const unsigned MinABIStackAlignInBytes = 4;
554
David Chisnallde3a0692009-08-17 23:08:21 +0000555 bool IsDarwinVectorABI;
556 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000557 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000558 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000559
560 static bool isRegisterSize(unsigned Size) {
561 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
562 }
563
Reid Kleckner80944df2014-10-31 22:00:51 +0000564 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
565 // FIXME: Assumes vectorcall is in use.
566 return isX86VectorTypeForVectorCall(getContext(), Ty);
567 }
568
569 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
570 uint64_t NumMembers) const override {
571 // FIXME: Assumes vectorcall is in use.
572 return isX86VectorCallAggregateSmallEnough(NumMembers);
573 }
574
Reid Kleckner40ca9132014-05-13 22:05:45 +0000575 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000576
Daniel Dunbar557893d2010-04-21 19:10:51 +0000577 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
578 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000579 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
580
581 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000582
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000583 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000584 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000585
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000586 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000587 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000588 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
589 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000590
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000591 /// \brief Rewrite the function info so that all memory arguments use
592 /// inalloca.
593 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
594
595 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
596 unsigned &StackOffset, ABIArgInfo &Info,
597 QualType Type) const;
598
Rafael Espindola75419dc2012-07-23 23:30:29 +0000599public:
600
Craig Topper4f12f102014-03-12 06:41:41 +0000601 void computeInfo(CGFunctionInfo &FI) const override;
602 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
603 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000604
Chad Rosier651c1832013-03-25 21:00:27 +0000605 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000606 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000607 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000608 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000609};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000610
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000611class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
612public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000613 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000614 bool d, bool p, bool w, unsigned r)
615 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000616
John McCall1fe2a8c2013-06-18 02:46:29 +0000617 static bool isStructReturnInRegABI(
618 const llvm::Triple &Triple, const CodeGenOptions &Opts);
619
Charles Davis4ea31ab2010-02-13 15:54:06 +0000620 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000621 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000622
Craig Topper4f12f102014-03-12 06:41:41 +0000623 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000624 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000625 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000626 return 4;
627 }
628
629 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000630 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000631
Jay Foad7c57be32011-07-11 09:56:20 +0000632 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000633 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000634 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000635 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
636 }
637
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000638 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
639 std::string &Constraints,
640 std::vector<llvm::Type *> &ResultRegTypes,
641 std::vector<llvm::Type *> &ResultTruncRegTypes,
642 std::vector<LValue> &ResultRegDests,
643 std::string &AsmString,
644 unsigned NumOutputs) const override;
645
Craig Topper4f12f102014-03-12 06:41:41 +0000646 llvm::Constant *
647 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000648 unsigned Sig = (0xeb << 0) | // jmp rel8
649 (0x06 << 8) | // .+0x08
650 ('F' << 16) |
651 ('T' << 24);
652 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
653 }
654
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000655};
656
657}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000658
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000659/// Rewrite input constraint references after adding some output constraints.
660/// In the case where there is one output and one input and we add one output,
661/// we need to replace all operand references greater than or equal to 1:
662/// mov $0, $1
663/// mov eax, $1
664/// The result will be:
665/// mov $0, $2
666/// mov eax, $2
667static void rewriteInputConstraintReferences(unsigned FirstIn,
668 unsigned NumNewOuts,
669 std::string &AsmString) {
670 std::string Buf;
671 llvm::raw_string_ostream OS(Buf);
672 size_t Pos = 0;
673 while (Pos < AsmString.size()) {
674 size_t DollarStart = AsmString.find('$', Pos);
675 if (DollarStart == std::string::npos)
676 DollarStart = AsmString.size();
677 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
678 if (DollarEnd == std::string::npos)
679 DollarEnd = AsmString.size();
680 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
681 Pos = DollarEnd;
682 size_t NumDollars = DollarEnd - DollarStart;
683 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
684 // We have an operand reference.
685 size_t DigitStart = Pos;
686 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
687 if (DigitEnd == std::string::npos)
688 DigitEnd = AsmString.size();
689 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
690 unsigned OperandIndex;
691 if (!OperandStr.getAsInteger(10, OperandIndex)) {
692 if (OperandIndex >= FirstIn)
693 OperandIndex += NumNewOuts;
694 OS << OperandIndex;
695 } else {
696 OS << OperandStr;
697 }
698 Pos = DigitEnd;
699 }
700 }
701 AsmString = std::move(OS.str());
702}
703
704/// Add output constraints for EAX:EDX because they are return registers.
705void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
706 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
707 std::vector<llvm::Type *> &ResultRegTypes,
708 std::vector<llvm::Type *> &ResultTruncRegTypes,
709 std::vector<LValue> &ResultRegDests, std::string &AsmString,
710 unsigned NumOutputs) const {
711 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
712
713 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
714 // larger.
715 if (!Constraints.empty())
716 Constraints += ',';
717 if (RetWidth <= 32) {
718 Constraints += "={eax}";
719 ResultRegTypes.push_back(CGF.Int32Ty);
720 } else {
721 // Use the 'A' constraint for EAX:EDX.
722 Constraints += "=A";
723 ResultRegTypes.push_back(CGF.Int64Ty);
724 }
725
726 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
727 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
728 ResultTruncRegTypes.push_back(CoerceTy);
729
730 // Coerce the integer by bitcasting the return slot pointer.
731 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
732 CoerceTy->getPointerTo()));
733 ResultRegDests.push_back(ReturnSlot);
734
735 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
736}
737
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000738/// shouldReturnTypeInRegister - Determine if the given type should be
739/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000740bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
741 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000742 uint64_t Size = Context.getTypeSize(Ty);
743
744 // Type must be register sized.
745 if (!isRegisterSize(Size))
746 return false;
747
748 if (Ty->isVectorType()) {
749 // 64- and 128- bit vectors inside structures are not returned in
750 // registers.
751 if (Size == 64 || Size == 128)
752 return false;
753
754 return true;
755 }
756
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000757 // If this is a builtin, pointer, enum, complex type, member pointer, or
758 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000759 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000760 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000761 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000762 return true;
763
764 // Arrays are treated like records.
765 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000766 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000767
768 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000769 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000770 if (!RT) return false;
771
Anders Carlsson40446e82010-01-27 03:25:19 +0000772 // FIXME: Traverse bases here too.
773
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000774 // Structure types are passed in register if all fields would be
775 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000776 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000777 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000778 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000779 continue;
780
781 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000782 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000783 return false;
784 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000785 return true;
786}
787
Reid Kleckner661f35b2014-01-18 01:12:41 +0000788ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
789 // If the return value is indirect, then the hidden argument is consuming one
790 // integer register.
791 if (State.FreeRegs) {
792 --State.FreeRegs;
793 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
794 }
795 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
796}
797
Reid Kleckner40ca9132014-05-13 22:05:45 +0000798ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000799 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000800 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000801
Reid Kleckner80944df2014-10-31 22:00:51 +0000802 const Type *Base = nullptr;
803 uint64_t NumElts = 0;
804 if (State.CC == llvm::CallingConv::X86_VectorCall &&
805 isHomogeneousAggregate(RetTy, Base, NumElts)) {
806 // The LLVM struct type for such an aggregate should lower properly.
807 return ABIArgInfo::getDirect();
808 }
809
Chris Lattner458b2aa2010-07-29 02:16:43 +0000810 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000811 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000812 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000813 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000814
815 // 128-bit vectors are a special case; they are returned in
816 // registers and we need to make sure to pick a type the LLVM
817 // backend will like.
818 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000819 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000820 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000821
822 // Always return in register if it fits in a general purpose
823 // register, or if it is 64 bits and has a single element.
824 if ((Size == 8 || Size == 16 || Size == 32) ||
825 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000826 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000827 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000828
Reid Kleckner661f35b2014-01-18 01:12:41 +0000829 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000830 }
831
832 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000833 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000834
John McCalla1dee5302010-08-22 10:59:02 +0000835 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000836 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000837 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000838 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000839 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000840 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000841
David Chisnallde3a0692009-08-17 23:08:21 +0000842 // If specified, structs and unions are always indirect.
843 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000844 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000845
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000846 // Small structures which are register sized are generally returned
847 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000848 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000849 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000850
851 // As a special-case, if the struct is a "single-element" struct, and
852 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000853 // floating-point register. (MSVC does not apply this special case.)
854 // We apply a similar transformation for pointer types to improve the
855 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000856 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000857 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000858 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000859 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
860
861 // FIXME: We should be able to narrow this integer in cases with dead
862 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000863 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000864 }
865
Reid Kleckner661f35b2014-01-18 01:12:41 +0000866 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000867 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000868
Chris Lattner458b2aa2010-07-29 02:16:43 +0000869 // Treat an enum type as its underlying type.
870 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
871 RetTy = EnumTy->getDecl()->getIntegerType();
872
873 return (RetTy->isPromotableIntegerType() ?
874 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000875}
876
Eli Friedman7919bea2012-06-05 19:40:46 +0000877static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
878 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
879}
880
Daniel Dunbared23de32010-09-16 20:42:00 +0000881static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
882 const RecordType *RT = Ty->getAs<RecordType>();
883 if (!RT)
884 return 0;
885 const RecordDecl *RD = RT->getDecl();
886
887 // If this is a C++ record, check the bases first.
888 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000889 for (const auto &I : CXXRD->bases())
890 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000891 return false;
892
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000893 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000894 QualType FT = i->getType();
895
Eli Friedman7919bea2012-06-05 19:40:46 +0000896 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000897 return true;
898
899 if (isRecordWithSSEVectorType(Context, FT))
900 return true;
901 }
902
903 return false;
904}
905
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000906unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
907 unsigned Align) const {
908 // Otherwise, if the alignment is less than or equal to the minimum ABI
909 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000910 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000911 return 0; // Use default alignment.
912
913 // On non-Darwin, the stack type alignment is always 4.
914 if (!IsDarwinVectorABI) {
915 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000916 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000917 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000918
Daniel Dunbared23de32010-09-16 20:42:00 +0000919 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000920 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
921 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000922 return 16;
923
924 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000925}
926
Rafael Espindola703c47f2012-10-19 05:04:37 +0000927ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000928 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000929 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000930 if (State.FreeRegs) {
931 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000932 return ABIArgInfo::getIndirectInReg(0, false);
933 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000934 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000935 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000936
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000937 // Compute the byval alignment.
938 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
939 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
940 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000941 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000942
943 // If the stack alignment is less than the type alignment, realign the
944 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000945 bool Realign = TypeAlign > StackAlign;
946 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000947}
948
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000949X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
950 const Type *T = isSingleElementStruct(Ty, getContext());
951 if (!T)
952 T = Ty.getTypePtr();
953
954 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
955 BuiltinType::Kind K = BT->getKind();
956 if (K == BuiltinType::Float || K == BuiltinType::Double)
957 return Float;
958 }
959 return Integer;
960}
961
Reid Kleckner661f35b2014-01-18 01:12:41 +0000962bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
963 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000964 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000965 Class C = classify(Ty);
966 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000967 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000968
Rafael Espindola077dd592012-10-24 01:58:58 +0000969 unsigned Size = getContext().getTypeSize(Ty);
970 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000971
972 if (SizeInRegs == 0)
973 return false;
974
Reid Kleckner661f35b2014-01-18 01:12:41 +0000975 if (SizeInRegs > State.FreeRegs) {
976 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000977 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000978 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000979
Reid Kleckner661f35b2014-01-18 01:12:41 +0000980 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000981
Reid Kleckner80944df2014-10-31 22:00:51 +0000982 if (State.CC == llvm::CallingConv::X86_FastCall ||
983 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000984 if (Size > 32)
985 return false;
986
987 if (Ty->isIntegralOrEnumerationType())
988 return true;
989
990 if (Ty->isPointerType())
991 return true;
992
993 if (Ty->isReferenceType())
994 return true;
995
Reid Kleckner661f35b2014-01-18 01:12:41 +0000996 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000997 NeedsPadding = true;
998
Rafael Espindola077dd592012-10-24 01:58:58 +0000999 return false;
1000 }
1001
Rafael Espindola703c47f2012-10-19 05:04:37 +00001002 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001003}
1004
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001005ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1006 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001007 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001008
Reid Kleckner80944df2014-10-31 22:00:51 +00001009 // Check with the C++ ABI first.
1010 const RecordType *RT = Ty->getAs<RecordType>();
1011 if (RT) {
1012 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1013 if (RAA == CGCXXABI::RAA_Indirect) {
1014 return getIndirectResult(Ty, false, State);
1015 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1016 // The field index doesn't matter, we'll fix it up later.
1017 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1018 }
1019 }
1020
1021 // vectorcall adds the concept of a homogenous vector aggregate, similar
1022 // to other targets.
1023 const Type *Base = nullptr;
1024 uint64_t NumElts = 0;
1025 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1026 isHomogeneousAggregate(Ty, Base, NumElts)) {
1027 if (State.FreeSSERegs >= NumElts) {
1028 State.FreeSSERegs -= NumElts;
1029 if (Ty->isBuiltinType() || Ty->isVectorType())
1030 return ABIArgInfo::getDirect();
1031 return ABIArgInfo::getExpand();
1032 }
1033 return getIndirectResult(Ty, /*ByVal=*/false, State);
1034 }
1035
1036 if (isAggregateTypeForABI(Ty)) {
1037 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001038 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001039 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001040 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001041
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001042 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001043 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001044 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001045 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001046
Eli Friedman9f061a32011-11-18 00:28:11 +00001047 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001048 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001049 return ABIArgInfo::getIgnore();
1050
Rafael Espindolafad28de2012-10-24 01:59:00 +00001051 llvm::LLVMContext &LLVMContext = getVMContext();
1052 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1053 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001054 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001055 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001056 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001057 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1058 return ABIArgInfo::getDirectInReg(Result);
1059 }
Craig Topper8a13c412014-05-21 05:09:00 +00001060 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001061
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001062 // Expand small (<= 128-bit) record types when we know that the stack layout
1063 // of those arguments will match the struct. This is important because the
1064 // LLVM backend isn't smart enough to remove byval, which inhibits many
1065 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001066 if (getContext().getTypeSize(Ty) <= 4*32 &&
1067 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001068 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001069 State.CC == llvm::CallingConv::X86_FastCall ||
1070 State.CC == llvm::CallingConv::X86_VectorCall,
1071 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001072
Reid Kleckner661f35b2014-01-18 01:12:41 +00001073 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001074 }
1075
Chris Lattnerd774ae92010-08-26 20:05:13 +00001076 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001077 // On Darwin, some vectors are passed in memory, we handle this by passing
1078 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001079 if (IsDarwinVectorABI) {
1080 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001081 if ((Size == 8 || Size == 16 || Size == 32) ||
1082 (Size == 64 && VT->getNumElements() == 1))
1083 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1084 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001085 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001086
Chad Rosier651c1832013-03-25 21:00:27 +00001087 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1088 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001089
Chris Lattnerd774ae92010-08-26 20:05:13 +00001090 return ABIArgInfo::getDirect();
1091 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001092
1093
Chris Lattner458b2aa2010-07-29 02:16:43 +00001094 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1095 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001096
Rafael Espindolafad28de2012-10-24 01:59:00 +00001097 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001098 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001099
1100 if (Ty->isPromotableIntegerType()) {
1101 if (InReg)
1102 return ABIArgInfo::getExtendInReg();
1103 return ABIArgInfo::getExtend();
1104 }
1105 if (InReg)
1106 return ABIArgInfo::getDirectInReg();
1107 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001108}
1109
Rafael Espindolaa6472962012-07-24 00:01:07 +00001110void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001111 CCState State(FI.getCallingConvention());
1112 if (State.CC == llvm::CallingConv::X86_FastCall)
1113 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001114 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1115 State.FreeRegs = 2;
1116 State.FreeSSERegs = 6;
1117 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001118 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001119 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001120 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001121
Reid Kleckner677539d2014-07-10 01:58:55 +00001122 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001123 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001124 } else if (FI.getReturnInfo().isIndirect()) {
1125 // The C++ ABI is not aware of register usage, so we have to check if the
1126 // return value was sret and put it in a register ourselves if appropriate.
1127 if (State.FreeRegs) {
1128 --State.FreeRegs; // The sret parameter consumes a register.
1129 FI.getReturnInfo().setInReg(true);
1130 }
1131 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001132
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001133 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001134 for (auto &I : FI.arguments()) {
1135 I.info = classifyArgumentType(I.type, State);
1136 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001137 }
1138
1139 // If we needed to use inalloca for any argument, do a second pass and rewrite
1140 // all the memory arguments to use inalloca.
1141 if (UsedInAlloca)
1142 rewriteWithInAlloca(FI);
1143}
1144
1145void
1146X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1147 unsigned &StackOffset,
1148 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001149 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1150 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1151 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1152 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1153
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001154 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1155 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001156 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001157 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001158 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001159 unsigned NumBytes = StackOffset - OldOffset;
1160 assert(NumBytes);
1161 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1162 Ty = llvm::ArrayType::get(Ty, NumBytes);
1163 FrameFields.push_back(Ty);
1164 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001165}
1166
Reid Kleckner852361d2014-07-26 00:12:26 +00001167static bool isArgInAlloca(const ABIArgInfo &Info) {
1168 // Leave ignored and inreg arguments alone.
1169 switch (Info.getKind()) {
1170 case ABIArgInfo::InAlloca:
1171 return true;
1172 case ABIArgInfo::Indirect:
1173 assert(Info.getIndirectByVal());
1174 return true;
1175 case ABIArgInfo::Ignore:
1176 return false;
1177 case ABIArgInfo::Direct:
1178 case ABIArgInfo::Extend:
1179 case ABIArgInfo::Expand:
1180 if (Info.getInReg())
1181 return false;
1182 return true;
1183 }
1184 llvm_unreachable("invalid enum");
1185}
1186
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001187void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1188 assert(IsWin32StructABI && "inalloca only supported on win32");
1189
1190 // Build a packed struct type for all of the arguments in memory.
1191 SmallVector<llvm::Type *, 6> FrameFields;
1192
1193 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001194 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1195
1196 // Put 'this' into the struct before 'sret', if necessary.
1197 bool IsThisCall =
1198 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1199 ABIArgInfo &Ret = FI.getReturnInfo();
1200 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1201 isArgInAlloca(I->info)) {
1202 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1203 ++I;
1204 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001205
1206 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001207 if (Ret.isIndirect() && !Ret.getInReg()) {
1208 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1209 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001210 // On Windows, the hidden sret parameter is always returned in eax.
1211 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001212 }
1213
1214 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001215 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001216 ++I;
1217
1218 // Put arguments passed in memory into the struct.
1219 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001220 if (isArgInAlloca(I->info))
1221 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001222 }
1223
1224 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1225 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001226}
1227
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001228llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1229 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001230 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001231
1232 CGBuilderTy &Builder = CGF.Builder;
1233 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1234 "ap");
1235 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001236
1237 // Compute if the address needs to be aligned
1238 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1239 Align = getTypeStackAlignInBytes(Ty, Align);
1240 Align = std::max(Align, 4U);
1241 if (Align > 4) {
1242 // addr = (addr + align - 1) & -align;
1243 llvm::Value *Offset =
1244 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1245 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1246 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1247 CGF.Int32Ty);
1248 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1249 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1250 Addr->getType(),
1251 "ap.cur.aligned");
1252 }
1253
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001254 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001255 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001256 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1257
1258 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001259 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001260 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001261 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001262 "ap.next");
1263 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1264
1265 return AddrTyped;
1266}
1267
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001268bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1269 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1270 assert(Triple.getArch() == llvm::Triple::x86);
1271
1272 switch (Opts.getStructReturnConvention()) {
1273 case CodeGenOptions::SRCK_Default:
1274 break;
1275 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1276 return false;
1277 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1278 return true;
1279 }
1280
1281 if (Triple.isOSDarwin())
1282 return true;
1283
1284 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001285 case llvm::Triple::DragonFly:
1286 case llvm::Triple::FreeBSD:
1287 case llvm::Triple::OpenBSD:
1288 case llvm::Triple::Bitrig:
1289 return true;
1290 case llvm::Triple::Win32:
1291 switch (Triple.getEnvironment()) {
1292 case llvm::Triple::UnknownEnvironment:
1293 case llvm::Triple::Cygnus:
1294 case llvm::Triple::GNU:
1295 case llvm::Triple::MSVC:
1296 return true;
1297 default:
1298 return false;
1299 }
1300 default:
1301 return false;
1302 }
1303}
1304
Charles Davis4ea31ab2010-02-13 15:54:06 +00001305void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1306 llvm::GlobalValue *GV,
1307 CodeGen::CodeGenModule &CGM) const {
1308 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1309 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1310 // Get the LLVM function.
1311 llvm::Function *Fn = cast<llvm::Function>(GV);
1312
1313 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001314 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001315 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001316 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1317 llvm::AttributeSet::get(CGM.getLLVMContext(),
1318 llvm::AttributeSet::FunctionIndex,
1319 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001320 }
1321 }
1322}
1323
John McCallbeec5a02010-03-06 00:35:14 +00001324bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1325 CodeGen::CodeGenFunction &CGF,
1326 llvm::Value *Address) const {
1327 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001328
Chris Lattnerece04092012-02-07 00:39:47 +00001329 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001330
John McCallbeec5a02010-03-06 00:35:14 +00001331 // 0-7 are the eight integer registers; the order is different
1332 // on Darwin (for EH), but the range is the same.
1333 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001334 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001335
John McCallc8e01702013-04-16 22:48:15 +00001336 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001337 // 12-16 are st(0..4). Not sure why we stop at 4.
1338 // These have size 16, which is sizeof(long double) on
1339 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001340 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001341 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001342
John McCallbeec5a02010-03-06 00:35:14 +00001343 } else {
1344 // 9 is %eflags, which doesn't get a size on Darwin for some
1345 // reason.
1346 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1347
1348 // 11-16 are st(0..5). Not sure why we stop at 5.
1349 // These have size 12, which is sizeof(long double) on
1350 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001351 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001352 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1353 }
John McCallbeec5a02010-03-06 00:35:14 +00001354
1355 return false;
1356}
1357
Chris Lattner0cf24192010-06-28 20:05:43 +00001358//===----------------------------------------------------------------------===//
1359// X86-64 ABI Implementation
1360//===----------------------------------------------------------------------===//
1361
1362
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001363namespace {
1364/// X86_64ABIInfo - The X86_64 ABI information.
1365class X86_64ABIInfo : public ABIInfo {
1366 enum Class {
1367 Integer = 0,
1368 SSE,
1369 SSEUp,
1370 X87,
1371 X87Up,
1372 ComplexX87,
1373 NoClass,
1374 Memory
1375 };
1376
1377 /// merge - Implement the X86_64 ABI merging algorithm.
1378 ///
1379 /// Merge an accumulating classification \arg Accum with a field
1380 /// classification \arg Field.
1381 ///
1382 /// \param Accum - The accumulating classification. This should
1383 /// always be either NoClass or the result of a previous merge
1384 /// call. In addition, this should never be Memory (the caller
1385 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001386 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001387
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001388 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1389 ///
1390 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1391 /// final MEMORY or SSE classes when necessary.
1392 ///
1393 /// \param AggregateSize - The size of the current aggregate in
1394 /// the classification process.
1395 ///
1396 /// \param Lo - The classification for the parts of the type
1397 /// residing in the low word of the containing object.
1398 ///
1399 /// \param Hi - The classification for the parts of the type
1400 /// residing in the higher words of the containing object.
1401 ///
1402 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1403
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001404 /// classify - Determine the x86_64 register classes in which the
1405 /// given type T should be passed.
1406 ///
1407 /// \param Lo - The classification for the parts of the type
1408 /// residing in the low word of the containing object.
1409 ///
1410 /// \param Hi - The classification for the parts of the type
1411 /// residing in the high word of the containing object.
1412 ///
1413 /// \param OffsetBase - The bit offset of this type in the
1414 /// containing object. Some parameters are classified different
1415 /// depending on whether they straddle an eightbyte boundary.
1416 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001417 /// \param isNamedArg - Whether the argument in question is a "named"
1418 /// argument, as used in AMD64-ABI 3.5.7.
1419 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001420 /// If a word is unused its result will be NoClass; if a type should
1421 /// be passed in Memory then at least the classification of \arg Lo
1422 /// will be Memory.
1423 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001424 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001425 ///
1426 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1427 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001428 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1429 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001430
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001431 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001432 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1433 unsigned IROffset, QualType SourceTy,
1434 unsigned SourceOffset) const;
1435 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1436 unsigned IROffset, QualType SourceTy,
1437 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001438
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001439 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001440 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001441 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001442
1443 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001444 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001445 ///
1446 /// \param freeIntRegs - The number of free integer registers remaining
1447 /// available.
1448 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001449
Chris Lattner458b2aa2010-07-29 02:16:43 +00001450 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001451
Bill Wendling5cd41c42010-10-18 03:41:31 +00001452 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001453 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001454 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001455 unsigned &neededSSE,
1456 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001457
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001458 bool IsIllegalVectorType(QualType Ty) const;
1459
John McCalle0fda732011-04-21 01:20:55 +00001460 /// The 0.98 ABI revision clarified a lot of ambiguities,
1461 /// unfortunately in ways that were not always consistent with
1462 /// certain previous compilers. In particular, platforms which
1463 /// required strict binary compatibility with older versions of GCC
1464 /// may need to exempt themselves.
1465 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001466 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001467 }
1468
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001469 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001470 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1471 // 64-bit hardware.
1472 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001473
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001474public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001475 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001476 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001477 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001478 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001479
John McCalla729c622012-02-17 03:33:10 +00001480 bool isPassedUsingAVXType(QualType type) const {
1481 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001482 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001483 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1484 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001485 if (info.isDirect()) {
1486 llvm::Type *ty = info.getCoerceToType();
1487 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1488 return (vectorTy->getBitWidth() > 128);
1489 }
1490 return false;
1491 }
1492
Craig Topper4f12f102014-03-12 06:41:41 +00001493 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001494
Craig Topper4f12f102014-03-12 06:41:41 +00001495 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1496 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001497};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001498
Chris Lattner04dc9572010-08-31 16:44:54 +00001499/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001500class WinX86_64ABIInfo : public ABIInfo {
1501
Reid Kleckner80944df2014-10-31 22:00:51 +00001502 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1503 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001504
Chris Lattner04dc9572010-08-31 16:44:54 +00001505public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001506 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1507
Craig Topper4f12f102014-03-12 06:41:41 +00001508 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001509
Craig Topper4f12f102014-03-12 06:41:41 +00001510 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1511 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001512
1513 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1514 // FIXME: Assumes vectorcall is in use.
1515 return isX86VectorTypeForVectorCall(getContext(), Ty);
1516 }
1517
1518 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1519 uint64_t NumMembers) const override {
1520 // FIXME: Assumes vectorcall is in use.
1521 return isX86VectorCallAggregateSmallEnough(NumMembers);
1522 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001523};
1524
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001525class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001526 bool HasAVX;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001527public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001528 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Alexander Musman09184fe2014-09-30 05:29:28 +00001529 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCallbeec5a02010-03-06 00:35:14 +00001530
John McCalla729c622012-02-17 03:33:10 +00001531 const X86_64ABIInfo &getABIInfo() const {
1532 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1533 }
1534
Craig Topper4f12f102014-03-12 06:41:41 +00001535 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001536 return 7;
1537 }
1538
1539 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001540 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001541 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001542
John McCall943fae92010-05-27 06:19:26 +00001543 // 0-15 are the 16 integer registers.
1544 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001545 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001546 return false;
1547 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001548
Jay Foad7c57be32011-07-11 09:56:20 +00001549 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001550 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001551 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001552 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1553 }
1554
John McCalla729c622012-02-17 03:33:10 +00001555 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001556 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001557 // The default CC on x86-64 sets %al to the number of SSA
1558 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001559 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001560 // that when AVX types are involved: the ABI explicitly states it is
1561 // undefined, and it doesn't work in practice because of how the ABI
1562 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001563 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001564 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001565 for (CallArgList::const_iterator
1566 it = args.begin(), ie = args.end(); it != ie; ++it) {
1567 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1568 HasAVXType = true;
1569 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001570 }
1571 }
John McCalla729c622012-02-17 03:33:10 +00001572
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001573 if (!HasAVXType)
1574 return true;
1575 }
John McCallcbc038a2011-09-21 08:08:30 +00001576
John McCalla729c622012-02-17 03:33:10 +00001577 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001578 }
1579
Craig Topper4f12f102014-03-12 06:41:41 +00001580 llvm::Constant *
1581 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001582 unsigned Sig = (0xeb << 0) | // jmp rel8
1583 (0x0a << 8) | // .+0x0c
1584 ('F' << 16) |
1585 ('T' << 24);
1586 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1587 }
1588
Alexander Musman09184fe2014-09-30 05:29:28 +00001589 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1590 return HasAVX ? 32 : 16;
1591 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001592};
1593
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001594static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1595 // If the argument does not end in .lib, automatically add the suffix. This
1596 // matches the behavior of MSVC.
1597 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001598 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001599 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001600 return ArgStr;
1601}
1602
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001603class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1604public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001605 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1606 bool d, bool p, bool w, unsigned RegParms)
1607 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001608
1609 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001610 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001611 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001612 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001613 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001614
1615 void getDetectMismatchOption(llvm::StringRef Name,
1616 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001617 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001618 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001619 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001620};
1621
Chris Lattner04dc9572010-08-31 16:44:54 +00001622class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001623 bool HasAVX;
Chris Lattner04dc9572010-08-31 16:44:54 +00001624public:
Alexander Musman09184fe2014-09-30 05:29:28 +00001625 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1626 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001627
Craig Topper4f12f102014-03-12 06:41:41 +00001628 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001629 return 7;
1630 }
1631
1632 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001633 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001634 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001635
Chris Lattner04dc9572010-08-31 16:44:54 +00001636 // 0-15 are the 16 integer registers.
1637 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001638 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001639 return false;
1640 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001641
1642 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001643 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001644 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001645 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001646 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001647
1648 void getDetectMismatchOption(llvm::StringRef Name,
1649 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001650 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001651 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001652 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001653
1654 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1655 return HasAVX ? 32 : 16;
1656 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001657};
1658
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001659}
1660
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001661void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1662 Class &Hi) const {
1663 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1664 //
1665 // (a) If one of the classes is Memory, the whole argument is passed in
1666 // memory.
1667 //
1668 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1669 // memory.
1670 //
1671 // (c) If the size of the aggregate exceeds two eightbytes and the first
1672 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1673 // argument is passed in memory. NOTE: This is necessary to keep the
1674 // ABI working for processors that don't support the __m256 type.
1675 //
1676 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1677 //
1678 // Some of these are enforced by the merging logic. Others can arise
1679 // only with unions; for example:
1680 // union { _Complex double; unsigned; }
1681 //
1682 // Note that clauses (b) and (c) were added in 0.98.
1683 //
1684 if (Hi == Memory)
1685 Lo = Memory;
1686 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1687 Lo = Memory;
1688 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1689 Lo = Memory;
1690 if (Hi == SSEUp && Lo != SSE)
1691 Hi = SSE;
1692}
1693
Chris Lattnerd776fb12010-06-28 21:43:59 +00001694X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001695 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1696 // classified recursively so that always two fields are
1697 // considered. The resulting class is calculated according to
1698 // the classes of the fields in the eightbyte:
1699 //
1700 // (a) If both classes are equal, this is the resulting class.
1701 //
1702 // (b) If one of the classes is NO_CLASS, the resulting class is
1703 // the other class.
1704 //
1705 // (c) If one of the classes is MEMORY, the result is the MEMORY
1706 // class.
1707 //
1708 // (d) If one of the classes is INTEGER, the result is the
1709 // INTEGER.
1710 //
1711 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1712 // MEMORY is used as class.
1713 //
1714 // (f) Otherwise class SSE is used.
1715
1716 // Accum should never be memory (we should have returned) or
1717 // ComplexX87 (because this cannot be passed in a structure).
1718 assert((Accum != Memory && Accum != ComplexX87) &&
1719 "Invalid accumulated classification during merge.");
1720 if (Accum == Field || Field == NoClass)
1721 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001722 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001723 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001724 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001725 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001726 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001727 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001728 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1729 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001730 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001731 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001732}
1733
Chris Lattner5c740f12010-06-30 19:14:05 +00001734void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001735 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001736 // FIXME: This code can be simplified by introducing a simple value class for
1737 // Class pairs with appropriate constructor methods for the various
1738 // situations.
1739
1740 // FIXME: Some of the split computations are wrong; unaligned vectors
1741 // shouldn't be passed in registers for example, so there is no chance they
1742 // can straddle an eightbyte. Verify & simplify.
1743
1744 Lo = Hi = NoClass;
1745
1746 Class &Current = OffsetBase < 64 ? Lo : Hi;
1747 Current = Memory;
1748
John McCall9dd450b2009-09-21 23:43:11 +00001749 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001750 BuiltinType::Kind k = BT->getKind();
1751
1752 if (k == BuiltinType::Void) {
1753 Current = NoClass;
1754 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1755 Lo = Integer;
1756 Hi = Integer;
1757 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1758 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001759 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1760 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001761 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001762 Current = SSE;
1763 } else if (k == BuiltinType::LongDouble) {
1764 Lo = X87;
1765 Hi = X87Up;
1766 }
1767 // FIXME: _Decimal32 and _Decimal64 are SSE.
1768 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001769 return;
1770 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001771
Chris Lattnerd776fb12010-06-28 21:43:59 +00001772 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001773 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001774 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001775 return;
1776 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001777
Chris Lattnerd776fb12010-06-28 21:43:59 +00001778 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001779 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001780 return;
1781 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001782
Chris Lattnerd776fb12010-06-28 21:43:59 +00001783 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001784 if (Ty->isMemberFunctionPointerType()) {
1785 if (Has64BitPointers) {
1786 // If Has64BitPointers, this is an {i64, i64}, so classify both
1787 // Lo and Hi now.
1788 Lo = Hi = Integer;
1789 } else {
1790 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1791 // straddles an eightbyte boundary, Hi should be classified as well.
1792 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1793 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1794 if (EB_FuncPtr != EB_ThisAdj) {
1795 Lo = Hi = Integer;
1796 } else {
1797 Current = Integer;
1798 }
1799 }
1800 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001801 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001802 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001803 return;
1804 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001805
Chris Lattnerd776fb12010-06-28 21:43:59 +00001806 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001807 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001808 if (Size == 32) {
1809 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1810 // float> as integer.
1811 Current = Integer;
1812
1813 // If this type crosses an eightbyte boundary, it should be
1814 // split.
1815 uint64_t EB_Real = (OffsetBase) / 64;
1816 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1817 if (EB_Real != EB_Imag)
1818 Hi = Lo;
1819 } else if (Size == 64) {
1820 // gcc passes <1 x double> in memory. :(
1821 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1822 return;
1823
1824 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001825 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001826 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1827 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1828 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001829 Current = Integer;
1830 else
1831 Current = SSE;
1832
1833 // If this type crosses an eightbyte boundary, it should be
1834 // split.
1835 if (OffsetBase && OffsetBase != 64)
1836 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001837 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001838 // Arguments of 256-bits are split into four eightbyte chunks. The
1839 // least significant one belongs to class SSE and all the others to class
1840 // SSEUP. The original Lo and Hi design considers that types can't be
1841 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1842 // This design isn't correct for 256-bits, but since there're no cases
1843 // where the upper parts would need to be inspected, avoid adding
1844 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001845 //
1846 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1847 // registers if they are "named", i.e. not part of the "..." of a
1848 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001849 Lo = SSE;
1850 Hi = SSEUp;
1851 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001852 return;
1853 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001854
Chris Lattnerd776fb12010-06-28 21:43:59 +00001855 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001856 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001857
Chris Lattner2b037972010-07-29 02:01:43 +00001858 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001859 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001860 if (Size <= 64)
1861 Current = Integer;
1862 else if (Size <= 128)
1863 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001864 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001865 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001866 else if (ET == getContext().DoubleTy ||
1867 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001868 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001869 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001870 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001871 Current = ComplexX87;
1872
1873 // If this complex type crosses an eightbyte boundary then it
1874 // should be split.
1875 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001876 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001877 if (Hi == NoClass && EB_Real != EB_Imag)
1878 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001879
Chris Lattnerd776fb12010-06-28 21:43:59 +00001880 return;
1881 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001882
Chris Lattner2b037972010-07-29 02:01:43 +00001883 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001884 // Arrays are treated like structures.
1885
Chris Lattner2b037972010-07-29 02:01:43 +00001886 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001887
1888 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001889 // than four eightbytes, ..., it has class MEMORY.
1890 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001891 return;
1892
1893 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1894 // fields, it has class MEMORY.
1895 //
1896 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001897 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001898 return;
1899
1900 // Otherwise implement simplified merge. We could be smarter about
1901 // this, but it isn't worth it and would be harder to verify.
1902 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001903 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001904 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001905
1906 // The only case a 256-bit wide vector could be used is when the array
1907 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1908 // to work for sizes wider than 128, early check and fallback to memory.
1909 if (Size > 128 && EltSize != 256)
1910 return;
1911
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001912 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1913 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001914 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001915 Lo = merge(Lo, FieldLo);
1916 Hi = merge(Hi, FieldHi);
1917 if (Lo == Memory || Hi == Memory)
1918 break;
1919 }
1920
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001921 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001922 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001923 return;
1924 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001925
Chris Lattnerd776fb12010-06-28 21:43:59 +00001926 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001927 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001928
1929 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001930 // than four eightbytes, ..., it has class MEMORY.
1931 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001932 return;
1933
Anders Carlsson20759ad2009-09-16 15:53:40 +00001934 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1935 // copy constructor or a non-trivial destructor, it is passed by invisible
1936 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001937 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001938 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001939
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001940 const RecordDecl *RD = RT->getDecl();
1941
1942 // Assume variable sized types are passed in memory.
1943 if (RD->hasFlexibleArrayMember())
1944 return;
1945
Chris Lattner2b037972010-07-29 02:01:43 +00001946 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001947
1948 // Reset Lo class, this will be recomputed.
1949 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001950
1951 // If this is a C++ record, classify the bases first.
1952 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001953 for (const auto &I : CXXRD->bases()) {
1954 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001955 "Unexpected base class!");
1956 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001957 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001958
1959 // Classify this field.
1960 //
1961 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1962 // single eightbyte, each is classified separately. Each eightbyte gets
1963 // initialized to class NO_CLASS.
1964 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001965 uint64_t Offset =
1966 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001967 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001968 Lo = merge(Lo, FieldLo);
1969 Hi = merge(Hi, FieldHi);
1970 if (Lo == Memory || Hi == Memory)
1971 break;
1972 }
1973 }
1974
1975 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001976 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001977 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001978 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001979 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1980 bool BitField = i->isBitField();
1981
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001982 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1983 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001984 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001985 // The only case a 256-bit wide vector could be used is when the struct
1986 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1987 // to work for sizes wider than 128, early check and fallback to memory.
1988 //
1989 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1990 Lo = Memory;
1991 return;
1992 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001993 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001994 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001995 Lo = Memory;
1996 return;
1997 }
1998
1999 // Classify this field.
2000 //
2001 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2002 // exceeds a single eightbyte, each is classified
2003 // separately. Each eightbyte gets initialized to class
2004 // NO_CLASS.
2005 Class FieldLo, FieldHi;
2006
2007 // Bit-fields require special handling, they do not force the
2008 // structure to be passed in memory even if unaligned, and
2009 // therefore they can straddle an eightbyte.
2010 if (BitField) {
2011 // Ignore padding bit-fields.
2012 if (i->isUnnamedBitfield())
2013 continue;
2014
2015 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002016 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002017
2018 uint64_t EB_Lo = Offset / 64;
2019 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002020
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002021 if (EB_Lo) {
2022 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2023 FieldLo = NoClass;
2024 FieldHi = Integer;
2025 } else {
2026 FieldLo = Integer;
2027 FieldHi = EB_Hi ? Integer : NoClass;
2028 }
2029 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002030 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002031 Lo = merge(Lo, FieldLo);
2032 Hi = merge(Hi, FieldHi);
2033 if (Lo == Memory || Hi == Memory)
2034 break;
2035 }
2036
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002037 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002038 }
2039}
2040
Chris Lattner22a931e2010-06-29 06:01:59 +00002041ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002042 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2043 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002044 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002045 // Treat an enum type as its underlying type.
2046 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2047 Ty = EnumTy->getDecl()->getIntegerType();
2048
2049 return (Ty->isPromotableIntegerType() ?
2050 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2051 }
2052
2053 return ABIArgInfo::getIndirect(0);
2054}
2055
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002056bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2057 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2058 uint64_t Size = getContext().getTypeSize(VecTy);
2059 unsigned LargestVector = HasAVX ? 256 : 128;
2060 if (Size <= 64 || Size > LargestVector)
2061 return true;
2062 }
2063
2064 return false;
2065}
2066
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002067ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2068 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002069 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2070 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002071 //
2072 // This assumption is optimistic, as there could be free registers available
2073 // when we need to pass this argument in memory, and LLVM could try to pass
2074 // the argument in the free register. This does not seem to happen currently,
2075 // but this code would be much safer if we could mark the argument with
2076 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002077 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002078 // Treat an enum type as its underlying type.
2079 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2080 Ty = EnumTy->getDecl()->getIntegerType();
2081
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002082 return (Ty->isPromotableIntegerType() ?
2083 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002084 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002085
Mark Lacey3825e832013-10-06 01:33:34 +00002086 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002087 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002088
Chris Lattner44c2b902011-05-22 23:21:23 +00002089 // Compute the byval alignment. We specify the alignment of the byval in all
2090 // cases so that the mid-level optimizer knows the alignment of the byval.
2091 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002092
2093 // Attempt to avoid passing indirect results using byval when possible. This
2094 // is important for good codegen.
2095 //
2096 // We do this by coercing the value into a scalar type which the backend can
2097 // handle naturally (i.e., without using byval).
2098 //
2099 // For simplicity, we currently only do this when we have exhausted all of the
2100 // free integer registers. Doing this when there are free integer registers
2101 // would require more care, as we would have to ensure that the coerced value
2102 // did not claim the unused register. That would require either reording the
2103 // arguments to the function (so that any subsequent inreg values came first),
2104 // or only doing this optimization when there were no following arguments that
2105 // might be inreg.
2106 //
2107 // We currently expect it to be rare (particularly in well written code) for
2108 // arguments to be passed on the stack when there are still free integer
2109 // registers available (this would typically imply large structs being passed
2110 // by value), so this seems like a fair tradeoff for now.
2111 //
2112 // We can revisit this if the backend grows support for 'onstack' parameter
2113 // attributes. See PR12193.
2114 if (freeIntRegs == 0) {
2115 uint64_t Size = getContext().getTypeSize(Ty);
2116
2117 // If this type fits in an eightbyte, coerce it into the matching integral
2118 // type, which will end up on the stack (with alignment 8).
2119 if (Align == 8 && Size <= 64)
2120 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2121 Size));
2122 }
2123
Chris Lattner44c2b902011-05-22 23:21:23 +00002124 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002125}
2126
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002127/// GetByteVectorType - The ABI specifies that a value should be passed in an
2128/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00002129/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002130llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002131 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002132
Chris Lattner9fa15c32010-07-29 05:02:29 +00002133 // Wrapper structs that just contain vectors are passed just like vectors,
2134 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002135 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00002136 while (STy && STy->getNumElements() == 1) {
2137 IRType = STy->getElementType(0);
2138 STy = dyn_cast<llvm::StructType>(IRType);
2139 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002140
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00002141 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002142 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
2143 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002144 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00002145 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00002146 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
2147 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
2148 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
2149 EltTy->isIntegerTy(128)))
2150 return VT;
2151 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002152
Chris Lattner4200fe42010-07-29 04:56:46 +00002153 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
2154}
2155
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002156/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2157/// is known to either be off the end of the specified type or being in
2158/// alignment padding. The user type specified is known to be at most 128 bits
2159/// in size, and have passed through X86_64ABIInfo::classify with a successful
2160/// classification that put one of the two halves in the INTEGER class.
2161///
2162/// It is conservatively correct to return false.
2163static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2164 unsigned EndBit, ASTContext &Context) {
2165 // If the bytes being queried are off the end of the type, there is no user
2166 // data hiding here. This handles analysis of builtins, vectors and other
2167 // types that don't contain interesting padding.
2168 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2169 if (TySize <= StartBit)
2170 return true;
2171
Chris Lattner98076a22010-07-29 07:43:55 +00002172 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2173 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2174 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2175
2176 // Check each element to see if the element overlaps with the queried range.
2177 for (unsigned i = 0; i != NumElts; ++i) {
2178 // If the element is after the span we care about, then we're done..
2179 unsigned EltOffset = i*EltSize;
2180 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002181
Chris Lattner98076a22010-07-29 07:43:55 +00002182 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2183 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2184 EndBit-EltOffset, Context))
2185 return false;
2186 }
2187 // If it overlaps no elements, then it is safe to process as padding.
2188 return true;
2189 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002190
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002191 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2192 const RecordDecl *RD = RT->getDecl();
2193 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002194
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002195 // If this is a C++ record, check the bases first.
2196 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002197 for (const auto &I : CXXRD->bases()) {
2198 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002199 "Unexpected base class!");
2200 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002201 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002202
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002203 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002204 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002205 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002206
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002207 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002208 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002209 EndBit-BaseOffset, Context))
2210 return false;
2211 }
2212 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002213
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002214 // Verify that no field has data that overlaps the region of interest. Yes
2215 // this could be sped up a lot by being smarter about queried fields,
2216 // however we're only looking at structs up to 16 bytes, so we don't care
2217 // much.
2218 unsigned idx = 0;
2219 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2220 i != e; ++i, ++idx) {
2221 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002222
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002223 // If we found a field after the region we care about, then we're done.
2224 if (FieldOffset >= EndBit) break;
2225
2226 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2227 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2228 Context))
2229 return false;
2230 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002231
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002232 // If nothing in this record overlapped the area of interest, then we're
2233 // clean.
2234 return true;
2235 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002236
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002237 return false;
2238}
2239
Chris Lattnere556a712010-07-29 18:39:32 +00002240/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2241/// float member at the specified offset. For example, {int,{float}} has a
2242/// float at offset 4. It is conservatively correct for this routine to return
2243/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002244static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002245 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002246 // Base case if we find a float.
2247 if (IROffset == 0 && IRType->isFloatTy())
2248 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002249
Chris Lattnere556a712010-07-29 18:39:32 +00002250 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002251 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002252 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2253 unsigned Elt = SL->getElementContainingOffset(IROffset);
2254 IROffset -= SL->getElementOffset(Elt);
2255 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2256 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002257
Chris Lattnere556a712010-07-29 18:39:32 +00002258 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002259 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2260 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002261 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2262 IROffset -= IROffset/EltSize*EltSize;
2263 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2264 }
2265
2266 return false;
2267}
2268
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002269
2270/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2271/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002272llvm::Type *X86_64ABIInfo::
2273GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002274 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002275 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002276 // pass as float if the last 4 bytes is just padding. This happens for
2277 // structs that contain 3 floats.
2278 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2279 SourceOffset*8+64, getContext()))
2280 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002281
Chris Lattnere556a712010-07-29 18:39:32 +00002282 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2283 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2284 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002285 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2286 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002287 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002288
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002289 return llvm::Type::getDoubleTy(getVMContext());
2290}
2291
2292
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002293/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2294/// an 8-byte GPR. This means that we either have a scalar or we are talking
2295/// about the high or low part of an up-to-16-byte struct. This routine picks
2296/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002297/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2298/// etc).
2299///
2300/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2301/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2302/// the 8-byte value references. PrefType may be null.
2303///
Alp Toker9907f082014-07-09 14:06:35 +00002304/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002305/// an offset into this that we're processing (which is always either 0 or 8).
2306///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002307llvm::Type *X86_64ABIInfo::
2308GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002309 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002310 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2311 // returning an 8-byte unit starting with it. See if we can safely use it.
2312 if (IROffset == 0) {
2313 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002314 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2315 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002316 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002317
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002318 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2319 // goodness in the source type is just tail padding. This is allowed to
2320 // kick in for struct {double,int} on the int, but not on
2321 // struct{double,int,int} because we wouldn't return the second int. We
2322 // have to do this analysis on the source type because we can't depend on
2323 // unions being lowered a specific way etc.
2324 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002325 IRType->isIntegerTy(32) ||
2326 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2327 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2328 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002329
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002330 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2331 SourceOffset*8+64, getContext()))
2332 return IRType;
2333 }
2334 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002335
Chris Lattner2192fe52011-07-18 04:24:23 +00002336 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002337 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002338 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002339 if (IROffset < SL->getSizeInBytes()) {
2340 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2341 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002342
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002343 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2344 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002345 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002346 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002347
Chris Lattner2192fe52011-07-18 04:24:23 +00002348 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002349 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002350 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002351 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002352 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2353 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002354 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002355
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002356 // Okay, we don't have any better idea of what to pass, so we pass this in an
2357 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002358 unsigned TySizeInBytes =
2359 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002360
Chris Lattner3f763422010-07-29 17:34:39 +00002361 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002362
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002363 // It is always safe to classify this as an integer type up to i64 that
2364 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002365 return llvm::IntegerType::get(getVMContext(),
2366 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002367}
2368
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002369
2370/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2371/// be used as elements of a two register pair to pass or return, return a
2372/// first class aggregate to represent them. For example, if the low part of
2373/// a by-value argument should be passed as i32* and the high part as float,
2374/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002375static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002376GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002377 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002378 // In order to correctly satisfy the ABI, we need to the high part to start
2379 // at offset 8. If the high and low parts we inferred are both 4-byte types
2380 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2381 // the second element at offset 8. Check for this:
2382 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2383 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002384 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002385 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002386
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002387 // To handle this, we have to increase the size of the low part so that the
2388 // second element will start at an 8 byte offset. We can't increase the size
2389 // of the second element because it might make us access off the end of the
2390 // struct.
2391 if (HiStart != 8) {
2392 // There are only two sorts of types the ABI generation code can produce for
2393 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2394 // Promote these to a larger type.
2395 if (Lo->isFloatTy())
2396 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2397 else {
2398 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2399 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2400 }
2401 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002402
Chris Lattnera5f58b02011-07-09 17:41:47 +00002403 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002404
2405
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002406 // Verify that the second element is at an 8-byte offset.
2407 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2408 "Invalid x86-64 argument pair!");
2409 return Result;
2410}
2411
Chris Lattner31faff52010-07-28 23:06:14 +00002412ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002413classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002414 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2415 // classification algorithm.
2416 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002417 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002418
2419 // Check some invariants.
2420 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002421 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2422
Craig Topper8a13c412014-05-21 05:09:00 +00002423 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002424 switch (Lo) {
2425 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002426 if (Hi == NoClass)
2427 return ABIArgInfo::getIgnore();
2428 // If the low part is just padding, it takes no register, leave ResType
2429 // null.
2430 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2431 "Unknown missing lo part");
2432 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002433
2434 case SSEUp:
2435 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002436 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002437
2438 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2439 // hidden argument.
2440 case Memory:
2441 return getIndirectReturnResult(RetTy);
2442
2443 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2444 // available register of the sequence %rax, %rdx is used.
2445 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002446 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002447
Chris Lattner1f3a0632010-07-29 21:42:50 +00002448 // If we have a sign or zero extended integer, make sure to return Extend
2449 // so that the parameter gets the right LLVM IR attributes.
2450 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2451 // Treat an enum type as its underlying type.
2452 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2453 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002454
Chris Lattner1f3a0632010-07-29 21:42:50 +00002455 if (RetTy->isIntegralOrEnumerationType() &&
2456 RetTy->isPromotableIntegerType())
2457 return ABIArgInfo::getExtend();
2458 }
Chris Lattner31faff52010-07-28 23:06:14 +00002459 break;
2460
2461 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2462 // available SSE register of the sequence %xmm0, %xmm1 is used.
2463 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002464 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002465 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002466
2467 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2468 // returned on the X87 stack in %st0 as 80-bit x87 number.
2469 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002470 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002471 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002472
2473 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2474 // part of the value is returned in %st0 and the imaginary part in
2475 // %st1.
2476 case ComplexX87:
2477 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002478 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002479 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002480 NULL);
2481 break;
2482 }
2483
Craig Topper8a13c412014-05-21 05:09:00 +00002484 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002485 switch (Hi) {
2486 // Memory was handled previously and X87 should
2487 // never occur as a hi class.
2488 case Memory:
2489 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002490 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002491
2492 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002493 case NoClass:
2494 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002495
Chris Lattner52b3c132010-09-01 00:20:33 +00002496 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002497 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002498 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2499 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002500 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002501 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002502 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002503 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2504 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002505 break;
2506
2507 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002508 // is passed in the next available eightbyte chunk if the last used
2509 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002510 //
Chris Lattner57540c52011-04-15 05:22:18 +00002511 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002512 case SSEUp:
2513 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002514 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002515 break;
2516
2517 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2518 // returned together with the previous X87 value in %st0.
2519 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002520 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002521 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002522 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002523 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002524 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002525 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002526 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2527 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002528 }
Chris Lattner31faff52010-07-28 23:06:14 +00002529 break;
2530 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002531
Chris Lattner52b3c132010-09-01 00:20:33 +00002532 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002533 // known to pass in the high eightbyte of the result. We do this by forming a
2534 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002535 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002536 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002537
Chris Lattner1f3a0632010-07-29 21:42:50 +00002538 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002539}
2540
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002541ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002542 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2543 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002544 const
2545{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002546 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002547 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002548
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002549 // Check some invariants.
2550 // FIXME: Enforce these by construction.
2551 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002552 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2553
2554 neededInt = 0;
2555 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002556 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002557 switch (Lo) {
2558 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002559 if (Hi == NoClass)
2560 return ABIArgInfo::getIgnore();
2561 // If the low part is just padding, it takes no register, leave ResType
2562 // null.
2563 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2564 "Unknown missing lo part");
2565 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002566
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002567 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2568 // on the stack.
2569 case Memory:
2570
2571 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2572 // COMPLEX_X87, it is passed in memory.
2573 case X87:
2574 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002575 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002576 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002577 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002578
2579 case SSEUp:
2580 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002581 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002582
2583 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2584 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2585 // and %r9 is used.
2586 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002587 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002588
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002589 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002590 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002591
2592 // If we have a sign or zero extended integer, make sure to return Extend
2593 // so that the parameter gets the right LLVM IR attributes.
2594 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2595 // Treat an enum type as its underlying type.
2596 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2597 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002598
Chris Lattner1f3a0632010-07-29 21:42:50 +00002599 if (Ty->isIntegralOrEnumerationType() &&
2600 Ty->isPromotableIntegerType())
2601 return ABIArgInfo::getExtend();
2602 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002603
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002604 break;
2605
2606 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2607 // available SSE register is used, the registers are taken in the
2608 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002609 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002610 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002611 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002612 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002613 break;
2614 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002615 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616
Craig Topper8a13c412014-05-21 05:09:00 +00002617 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002618 switch (Hi) {
2619 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002620 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002621 // which is passed in memory.
2622 case Memory:
2623 case X87:
2624 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002625 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002626
2627 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002628
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002629 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002630 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002631 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002632 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002633
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002634 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2635 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002636 break;
2637
2638 // X87Up generally doesn't occur here (long double is passed in
2639 // memory), except in situations involving unions.
2640 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002641 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002642 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002643
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002644 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2645 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002646
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002647 ++neededSSE;
2648 break;
2649
2650 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2651 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002652 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002653 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002654 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002655 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002656 break;
2657 }
2658
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002659 // If a high part was specified, merge it together with the low part. It is
2660 // known to pass in the high eightbyte of the result. We do this by forming a
2661 // first class struct aggregate with the high and low part: {low, high}
2662 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002663 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002664
Chris Lattner1f3a0632010-07-29 21:42:50 +00002665 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002666}
2667
Chris Lattner22326a12010-07-29 02:31:05 +00002668void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002669
Reid Kleckner40ca9132014-05-13 22:05:45 +00002670 if (!getCXXABI().classifyReturnType(FI))
2671 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002672
2673 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002674 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002675
2676 // If the return value is indirect, then the hidden argument is consuming one
2677 // integer register.
2678 if (FI.getReturnInfo().isIndirect())
2679 --freeIntRegs;
2680
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002681 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002682 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2683 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002684 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002686 it != ie; ++it, ++ArgNo) {
2687 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002688
Bill Wendling9987c0e2010-10-18 23:51:38 +00002689 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002690 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002691 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002692
2693 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2694 // eightbyte of an argument, the whole argument is passed on the
2695 // stack. If registers have already been assigned for some
2696 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002697 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002698 freeIntRegs -= neededInt;
2699 freeSSERegs -= neededSSE;
2700 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002701 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002702 }
2703 }
2704}
2705
2706static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2707 QualType Ty,
2708 CodeGenFunction &CGF) {
2709 llvm::Value *overflow_arg_area_p =
2710 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2711 llvm::Value *overflow_arg_area =
2712 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2713
2714 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2715 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002716 // It isn't stated explicitly in the standard, but in practice we use
2717 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002718 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2719 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002720 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002721 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002722 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002723 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2724 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002725 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002726 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002727 overflow_arg_area =
2728 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2729 overflow_arg_area->getType(),
2730 "overflow_arg_area.align");
2731 }
2732
2733 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002734 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002735 llvm::Value *Res =
2736 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002737 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002738
2739 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2740 // l->overflow_arg_area + sizeof(type).
2741 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2742 // an 8 byte boundary.
2743
2744 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002745 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002746 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002747 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2748 "overflow_arg_area.next");
2749 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2750
2751 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2752 return Res;
2753}
2754
2755llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2756 CodeGenFunction &CGF) const {
2757 // Assume that va_list type is correct; should be pointer to LLVM type:
2758 // struct {
2759 // i32 gp_offset;
2760 // i32 fp_offset;
2761 // i8* overflow_arg_area;
2762 // i8* reg_save_area;
2763 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002764 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002765
Chris Lattner9723d6c2010-03-11 18:19:55 +00002766 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002767 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2768 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002769
2770 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2771 // in the registers. If not go to step 7.
2772 if (!neededInt && !neededSSE)
2773 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2774
2775 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2776 // general purpose registers needed to pass type and num_fp to hold
2777 // the number of floating point registers needed.
2778
2779 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2780 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2781 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2782 //
2783 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2784 // register save space).
2785
Craig Topper8a13c412014-05-21 05:09:00 +00002786 llvm::Value *InRegs = nullptr;
2787 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2788 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002789 if (neededInt) {
2790 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2791 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002792 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2793 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002794 }
2795
2796 if (neededSSE) {
2797 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2798 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2799 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002800 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2801 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002802 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2803 }
2804
2805 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2806 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2807 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2808 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2809
2810 // Emit code to load the value if it was passed in registers.
2811
2812 CGF.EmitBlock(InRegBlock);
2813
2814 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2815 // an offset of l->gp_offset and/or l->fp_offset. This may require
2816 // copying to a temporary location in case the parameter is passed
2817 // in different register classes or requires an alignment greater
2818 // than 8 for general purpose registers and 16 for XMM registers.
2819 //
2820 // FIXME: This really results in shameful code when we end up needing to
2821 // collect arguments from different places; often what should result in a
2822 // simple assembling of a structure from scattered addresses has many more
2823 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002824 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002825 llvm::Value *RegAddr =
2826 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2827 "reg_save_area");
2828 if (neededInt && neededSSE) {
2829 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002830 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002831 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002832 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2833 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002834 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002835 llvm::Type *TyLo = ST->getElementType(0);
2836 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002837 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002838 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002839 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2840 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002841 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2842 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002843 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2844 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002845 llvm::Value *V =
2846 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2847 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2848 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2849 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2850
Owen Anderson170229f2009-07-14 23:10:40 +00002851 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002852 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002853 } else if (neededInt) {
2854 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2855 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002856 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002857
2858 // Copy to a temporary if necessary to ensure the appropriate alignment.
2859 std::pair<CharUnits, CharUnits> SizeAlign =
2860 CGF.getContext().getTypeInfoInChars(Ty);
2861 uint64_t TySize = SizeAlign.first.getQuantity();
2862 unsigned TyAlign = SizeAlign.second.getQuantity();
2863 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002864 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2865 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2866 RegAddr = Tmp;
2867 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002868 } else if (neededSSE == 1) {
2869 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2870 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2871 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002872 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002873 assert(neededSSE == 2 && "Invalid number of needed registers!");
2874 // SSE registers are spaced 16 bytes apart in the register save
2875 // area, we need to collect the two eightbytes together.
2876 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002877 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002878 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002879 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002880 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002881 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2882 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2883 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002884 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2885 DblPtrTy));
2886 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2887 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2888 DblPtrTy));
2889 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2890 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2891 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002892 }
2893
2894 // AMD64-ABI 3.5.7p5: Step 5. Set:
2895 // l->gp_offset = l->gp_offset + num_gp * 8
2896 // l->fp_offset = l->fp_offset + num_fp * 16.
2897 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002898 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002899 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2900 gp_offset_p);
2901 }
2902 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002903 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002904 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2905 fp_offset_p);
2906 }
2907 CGF.EmitBranch(ContBlock);
2908
2909 // Emit code to load the value if it was passed in memory.
2910
2911 CGF.EmitBlock(InMemBlock);
2912 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2913
2914 // Return the appropriate result.
2915
2916 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002917 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002918 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002919 ResAddr->addIncoming(RegAddr, InRegBlock);
2920 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002921 return ResAddr;
2922}
2923
Reid Kleckner80944df2014-10-31 22:00:51 +00002924ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
2925 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002926
2927 if (Ty->isVoidType())
2928 return ABIArgInfo::getIgnore();
2929
2930 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2931 Ty = EnumTy->getDecl()->getIntegerType();
2932
Reid Kleckner80944df2014-10-31 22:00:51 +00002933 TypeInfo Info = getContext().getTypeInfo(Ty);
2934 uint64_t Width = Info.Width;
2935 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002936
Reid Kleckner9005f412014-05-02 00:51:20 +00002937 const RecordType *RT = Ty->getAs<RecordType>();
2938 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002939 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002940 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002941 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2942 }
2943
2944 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002945 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2946
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002947 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00002948 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002949 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00002950 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00002951 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002952
Reid Kleckner80944df2014-10-31 22:00:51 +00002953 // vectorcall adds the concept of a homogenous vector aggregate, similar to
2954 // other targets.
2955 const Type *Base = nullptr;
2956 uint64_t NumElts = 0;
2957 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
2958 if (FreeSSERegs >= NumElts) {
2959 FreeSSERegs -= NumElts;
2960 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
2961 return ABIArgInfo::getDirect();
2962 return ABIArgInfo::getExpand();
2963 }
2964 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
2965 }
2966
2967
Reid Klecknerec87fec2014-05-02 01:17:12 +00002968 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00002969 // If the member pointer is represented by an LLVM int or ptr, pass it
2970 // directly.
2971 llvm::Type *LLTy = CGT.ConvertType(Ty);
2972 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2973 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00002974 }
2975
2976 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002977 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2978 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00002979 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00002980 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002981
Reid Kleckner9005f412014-05-02 00:51:20 +00002982 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00002983 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002984 }
2985
Julien Lerouge10dcff82014-08-27 00:36:55 +00002986 // Bool type is always extended to the ABI, other builtin types are not
2987 // extended.
2988 const BuiltinType *BT = Ty->getAs<BuiltinType>();
2989 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00002990 return ABIArgInfo::getExtend();
2991
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002992 return ABIArgInfo::getDirect();
2993}
2994
2995void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00002996 bool IsVectorCall =
2997 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002998
Reid Kleckner80944df2014-10-31 22:00:51 +00002999 // We can use up to 4 SSE return registers with vectorcall.
3000 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3001 if (!getCXXABI().classifyReturnType(FI))
3002 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3003
3004 // We can use up to 6 SSE register parameters with vectorcall.
3005 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003006 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003007 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003008}
3009
Chris Lattner04dc9572010-08-31 16:44:54 +00003010llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3011 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003012 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003013
Chris Lattner04dc9572010-08-31 16:44:54 +00003014 CGBuilderTy &Builder = CGF.Builder;
3015 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3016 "ap");
3017 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3018 llvm::Type *PTy =
3019 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3020 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3021
3022 uint64_t Offset =
3023 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3024 llvm::Value *NextAddr =
3025 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3026 "ap.next");
3027 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3028
3029 return AddrTyped;
3030}
Chris Lattner0cf24192010-06-28 20:05:43 +00003031
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003032namespace {
3033
Derek Schuffa2020962012-10-16 22:30:41 +00003034class NaClX86_64ABIInfo : public ABIInfo {
3035 public:
3036 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
3037 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00003038 void computeInfo(CGFunctionInfo &FI) const override;
3039 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3040 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00003041 private:
3042 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3043 X86_64ABIInfo NInfo; // Used for everything else.
3044};
3045
3046class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00003047 bool HasAVX;
Derek Schuffa2020962012-10-16 22:30:41 +00003048 public:
Alexander Musman09184fe2014-09-30 05:29:28 +00003049 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
3050 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {
3051 }
3052 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3053 return HasAVX ? 32 : 16;
3054 }
Derek Schuffa2020962012-10-16 22:30:41 +00003055};
3056
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003057}
3058
Derek Schuffa2020962012-10-16 22:30:41 +00003059void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3060 if (FI.getASTCallingConvention() == CC_PnaclCall)
3061 PInfo.computeInfo(FI);
3062 else
3063 NInfo.computeInfo(FI);
3064}
3065
3066llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3067 CodeGenFunction &CGF) const {
3068 // Always use the native convention; calling pnacl-style varargs functions
3069 // is unuspported.
3070 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
3071}
3072
3073
John McCallea8d8bb2010-03-11 00:10:12 +00003074// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003075namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003076/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3077class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003078public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003079 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3080
3081 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3082 CodeGenFunction &CGF) const override;
3083};
3084
3085class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3086public:
3087 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003088
Craig Topper4f12f102014-03-12 06:41:41 +00003089 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003090 // This is recovered from gcc output.
3091 return 1; // r1 is the dedicated stack pointer
3092 }
3093
3094 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003095 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003096
3097 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3098 return 16; // Natural alignment for Altivec vectors.
3099 }
John McCallea8d8bb2010-03-11 00:10:12 +00003100};
3101
3102}
3103
Roman Divacky8a12d842014-11-03 18:32:54 +00003104llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3105 QualType Ty,
3106 CodeGenFunction &CGF) const {
3107 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3108 // TODO: Implement this. For now ignore.
3109 (void)CTy;
3110 return nullptr;
3111 }
3112
3113 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3114 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3115 llvm::Type *CharPtr = CGF.Int8PtrTy;
3116 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3117
3118 CGBuilderTy &Builder = CGF.Builder;
3119 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3120 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3121 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3122 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3123 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3124 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3125 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3126 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3127 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3128 // Align GPR when TY is i64.
3129 if (isI64) {
3130 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3131 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3132 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3133 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3134 }
3135 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3136 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3137 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3138 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3139 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3140
3141 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3142 Builder.getInt8(8), "cond");
3143
3144 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3145 Builder.getInt8(isInt ? 4 : 8));
3146
3147 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3148
3149 if (Ty->isFloatingType())
3150 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3151
3152 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3153 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3154 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3155
3156 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3157
3158 CGF.EmitBlock(UsingRegs);
3159
3160 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3161 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3162 // Increase the GPR/FPR indexes.
3163 if (isInt) {
3164 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3165 Builder.CreateStore(GPR, GPRPtr);
3166 } else {
3167 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3168 Builder.CreateStore(FPR, FPRPtr);
3169 }
3170 CGF.EmitBranch(Cont);
3171
3172 CGF.EmitBlock(UsingOverflow);
3173
3174 // Increase the overflow area.
3175 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3176 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3177 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3178 CGF.EmitBranch(Cont);
3179
3180 CGF.EmitBlock(Cont);
3181
3182 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3183 Result->addIncoming(Result1, UsingRegs);
3184 Result->addIncoming(Result2, UsingOverflow);
3185
3186 if (Ty->isAggregateType()) {
3187 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3188 return Builder.CreateLoad(AGGPtr, false, "aggr");
3189 }
3190
3191 return Result;
3192}
3193
John McCallea8d8bb2010-03-11 00:10:12 +00003194bool
3195PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3196 llvm::Value *Address) const {
3197 // This is calculated from the LLVM and GCC tables and verified
3198 // against gcc output. AFAIK all ABIs use the same encoding.
3199
3200 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003201
Chris Lattnerece04092012-02-07 00:39:47 +00003202 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003203 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3204 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3205 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3206
3207 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003208 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003209
3210 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003211 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003212
3213 // 64-76 are various 4-byte special-purpose registers:
3214 // 64: mq
3215 // 65: lr
3216 // 66: ctr
3217 // 67: ap
3218 // 68-75 cr0-7
3219 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003220 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003221
3222 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003223 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003224
3225 // 109: vrsave
3226 // 110: vscr
3227 // 111: spe_acc
3228 // 112: spefscr
3229 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003230 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003231
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003232 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003233}
3234
Roman Divackyd966e722012-05-09 18:22:46 +00003235// PowerPC-64
3236
3237namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003238/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3239class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003240public:
3241 enum ABIKind {
3242 ELFv1 = 0,
3243 ELFv2
3244 };
3245
3246private:
3247 static const unsigned GPRBits = 64;
3248 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003249
3250public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003251 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3252 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003253
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003254 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003255 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003256
3257 ABIArgInfo classifyReturnType(QualType RetTy) const;
3258 ABIArgInfo classifyArgumentType(QualType Ty) const;
3259
Reid Klecknere9f6a712014-10-31 17:10:41 +00003260 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3261 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3262 uint64_t Members) const override;
3263
Bill Schmidt84d37792012-10-12 19:26:17 +00003264 // TODO: We can add more logic to computeInfo to improve performance.
3265 // Example: For aggregate arguments that fit in a register, we could
3266 // use getDirectInReg (as is done below for structs containing a single
3267 // floating-point value) to avoid pushing them to memory on function
3268 // entry. This would require changing the logic in PPCISelLowering
3269 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003270 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003271 if (!getCXXABI().classifyReturnType(FI))
3272 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003273 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003274 // We rely on the default argument classification for the most part.
3275 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003276 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003277 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003278 if (T) {
3279 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003280 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3281 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003282 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003283 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003284 continue;
3285 }
3286 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003287 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003288 }
3289 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003290
Craig Topper4f12f102014-03-12 06:41:41 +00003291 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3292 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003293};
3294
3295class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3296public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003297 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3298 PPC64_SVR4_ABIInfo::ABIKind Kind)
3299 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003300
Craig Topper4f12f102014-03-12 06:41:41 +00003301 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003302 // This is recovered from gcc output.
3303 return 1; // r1 is the dedicated stack pointer
3304 }
3305
3306 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003307 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003308
3309 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3310 return 16; // Natural alignment for Altivec and VSX vectors.
3311 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003312};
3313
Roman Divackyd966e722012-05-09 18:22:46 +00003314class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3315public:
3316 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3317
Craig Topper4f12f102014-03-12 06:41:41 +00003318 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003319 // This is recovered from gcc output.
3320 return 1; // r1 is the dedicated stack pointer
3321 }
3322
3323 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003324 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003325
3326 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3327 return 16; // Natural alignment for Altivec vectors.
3328 }
Roman Divackyd966e722012-05-09 18:22:46 +00003329};
3330
3331}
3332
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003333// Return true if the ABI requires Ty to be passed sign- or zero-
3334// extended to 64 bits.
3335bool
3336PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3337 // Treat an enum type as its underlying type.
3338 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3339 Ty = EnumTy->getDecl()->getIntegerType();
3340
3341 // Promotable integer types are required to be promoted by the ABI.
3342 if (Ty->isPromotableIntegerType())
3343 return true;
3344
3345 // In addition to the usual promotable integer types, we also need to
3346 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3347 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3348 switch (BT->getKind()) {
3349 case BuiltinType::Int:
3350 case BuiltinType::UInt:
3351 return true;
3352 default:
3353 break;
3354 }
3355
3356 return false;
3357}
3358
Ulrich Weigand581badc2014-07-10 17:20:07 +00003359/// isAlignedParamType - Determine whether a type requires 16-byte
3360/// alignment in the parameter area.
3361bool
3362PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3363 // Complex types are passed just like their elements.
3364 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3365 Ty = CTy->getElementType();
3366
3367 // Only vector types of size 16 bytes need alignment (larger types are
3368 // passed via reference, smaller types are not aligned).
3369 if (Ty->isVectorType())
3370 return getContext().getTypeSize(Ty) == 128;
3371
3372 // For single-element float/vector structs, we consider the whole type
3373 // to have the same alignment requirements as its single element.
3374 const Type *AlignAsType = nullptr;
3375 const Type *EltType = isSingleElementStruct(Ty, getContext());
3376 if (EltType) {
3377 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3378 if ((EltType->isVectorType() &&
3379 getContext().getTypeSize(EltType) == 128) ||
3380 (BT && BT->isFloatingPoint()))
3381 AlignAsType = EltType;
3382 }
3383
Ulrich Weigandb7122372014-07-21 00:48:09 +00003384 // Likewise for ELFv2 homogeneous aggregates.
3385 const Type *Base = nullptr;
3386 uint64_t Members = 0;
3387 if (!AlignAsType && Kind == ELFv2 &&
3388 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3389 AlignAsType = Base;
3390
Ulrich Weigand581badc2014-07-10 17:20:07 +00003391 // With special case aggregates, only vector base types need alignment.
3392 if (AlignAsType)
3393 return AlignAsType->isVectorType();
3394
3395 // Otherwise, we only need alignment for any aggregate type that
3396 // has an alignment requirement of >= 16 bytes.
3397 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3398 return true;
3399
3400 return false;
3401}
3402
Ulrich Weigandb7122372014-07-21 00:48:09 +00003403/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3404/// aggregate. Base is set to the base element type, and Members is set
3405/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003406bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3407 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003408 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3409 uint64_t NElements = AT->getSize().getZExtValue();
3410 if (NElements == 0)
3411 return false;
3412 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3413 return false;
3414 Members *= NElements;
3415 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3416 const RecordDecl *RD = RT->getDecl();
3417 if (RD->hasFlexibleArrayMember())
3418 return false;
3419
3420 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003421
3422 // If this is a C++ record, check the bases first.
3423 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3424 for (const auto &I : CXXRD->bases()) {
3425 // Ignore empty records.
3426 if (isEmptyRecord(getContext(), I.getType(), true))
3427 continue;
3428
3429 uint64_t FldMembers;
3430 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3431 return false;
3432
3433 Members += FldMembers;
3434 }
3435 }
3436
Ulrich Weigandb7122372014-07-21 00:48:09 +00003437 for (const auto *FD : RD->fields()) {
3438 // Ignore (non-zero arrays of) empty records.
3439 QualType FT = FD->getType();
3440 while (const ConstantArrayType *AT =
3441 getContext().getAsConstantArrayType(FT)) {
3442 if (AT->getSize().getZExtValue() == 0)
3443 return false;
3444 FT = AT->getElementType();
3445 }
3446 if (isEmptyRecord(getContext(), FT, true))
3447 continue;
3448
3449 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3450 if (getContext().getLangOpts().CPlusPlus &&
3451 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3452 continue;
3453
3454 uint64_t FldMembers;
3455 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3456 return false;
3457
3458 Members = (RD->isUnion() ?
3459 std::max(Members, FldMembers) : Members + FldMembers);
3460 }
3461
3462 if (!Base)
3463 return false;
3464
3465 // Ensure there is no padding.
3466 if (getContext().getTypeSize(Base) * Members !=
3467 getContext().getTypeSize(Ty))
3468 return false;
3469 } else {
3470 Members = 1;
3471 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3472 Members = 2;
3473 Ty = CT->getElementType();
3474 }
3475
Reid Klecknere9f6a712014-10-31 17:10:41 +00003476 // Most ABIs only support float, double, and some vector type widths.
3477 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003478 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003479
3480 // The base type must be the same for all members. Types that
3481 // agree in both total size and mode (float vs. vector) are
3482 // treated as being equivalent here.
3483 const Type *TyPtr = Ty.getTypePtr();
3484 if (!Base)
3485 Base = TyPtr;
3486
3487 if (Base->isVectorType() != TyPtr->isVectorType() ||
3488 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3489 return false;
3490 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003491 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3492}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003493
Reid Klecknere9f6a712014-10-31 17:10:41 +00003494bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3495 // Homogeneous aggregates for ELFv2 must have base types of float,
3496 // double, long double, or 128-bit vectors.
3497 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3498 if (BT->getKind() == BuiltinType::Float ||
3499 BT->getKind() == BuiltinType::Double ||
3500 BT->getKind() == BuiltinType::LongDouble)
3501 return true;
3502 }
3503 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3504 if (getContext().getTypeSize(VT) == 128)
3505 return true;
3506 }
3507 return false;
3508}
3509
3510bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3511 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003512 // Vector types require one register, floating point types require one
3513 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003514 uint32_t NumRegs =
3515 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003516
3517 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003518 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003519}
3520
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003521ABIArgInfo
3522PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00003523 if (Ty->isAnyComplexType())
3524 return ABIArgInfo::getDirect();
3525
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003526 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3527 // or via reference (larger than 16 bytes).
3528 if (Ty->isVectorType()) {
3529 uint64_t Size = getContext().getTypeSize(Ty);
3530 if (Size > 128)
3531 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3532 else if (Size < 128) {
3533 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3534 return ABIArgInfo::getDirect(CoerceTy);
3535 }
3536 }
3537
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003538 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003539 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003540 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003541
Ulrich Weigand581badc2014-07-10 17:20:07 +00003542 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3543 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003544
3545 // ELFv2 homogeneous aggregates are passed as array types.
3546 const Type *Base = nullptr;
3547 uint64_t Members = 0;
3548 if (Kind == ELFv2 &&
3549 isHomogeneousAggregate(Ty, Base, Members)) {
3550 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3551 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3552 return ABIArgInfo::getDirect(CoerceTy);
3553 }
3554
Ulrich Weigand601957f2014-07-21 00:56:36 +00003555 // If an aggregate may end up fully in registers, we do not
3556 // use the ByVal method, but pass the aggregate as array.
3557 // This is usually beneficial since we avoid forcing the
3558 // back-end to store the argument to memory.
3559 uint64_t Bits = getContext().getTypeSize(Ty);
3560 if (Bits > 0 && Bits <= 8 * GPRBits) {
3561 llvm::Type *CoerceTy;
3562
3563 // Types up to 8 bytes are passed as integer type (which will be
3564 // properly aligned in the argument save area doubleword).
3565 if (Bits <= GPRBits)
3566 CoerceTy = llvm::IntegerType::get(getVMContext(),
3567 llvm::RoundUpToAlignment(Bits, 8));
3568 // Larger types are passed as arrays, with the base type selected
3569 // according to the required alignment in the save area.
3570 else {
3571 uint64_t RegBits = ABIAlign * 8;
3572 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3573 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3574 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3575 }
3576
3577 return ABIArgInfo::getDirect(CoerceTy);
3578 }
3579
Ulrich Weigandb7122372014-07-21 00:48:09 +00003580 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003581 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3582 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003583 }
3584
3585 return (isPromotableTypeForABI(Ty) ?
3586 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3587}
3588
3589ABIArgInfo
3590PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3591 if (RetTy->isVoidType())
3592 return ABIArgInfo::getIgnore();
3593
Bill Schmidta3d121c2012-12-17 04:20:17 +00003594 if (RetTy->isAnyComplexType())
3595 return ABIArgInfo::getDirect();
3596
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003597 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3598 // or via reference (larger than 16 bytes).
3599 if (RetTy->isVectorType()) {
3600 uint64_t Size = getContext().getTypeSize(RetTy);
3601 if (Size > 128)
3602 return ABIArgInfo::getIndirect(0);
3603 else if (Size < 128) {
3604 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3605 return ABIArgInfo::getDirect(CoerceTy);
3606 }
3607 }
3608
Ulrich Weigandb7122372014-07-21 00:48:09 +00003609 if (isAggregateTypeForABI(RetTy)) {
3610 // ELFv2 homogeneous aggregates are returned as array types.
3611 const Type *Base = nullptr;
3612 uint64_t Members = 0;
3613 if (Kind == ELFv2 &&
3614 isHomogeneousAggregate(RetTy, Base, Members)) {
3615 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3616 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3617 return ABIArgInfo::getDirect(CoerceTy);
3618 }
3619
3620 // ELFv2 small aggregates are returned in up to two registers.
3621 uint64_t Bits = getContext().getTypeSize(RetTy);
3622 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3623 if (Bits == 0)
3624 return ABIArgInfo::getIgnore();
3625
3626 llvm::Type *CoerceTy;
3627 if (Bits > GPRBits) {
3628 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3629 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3630 } else
3631 CoerceTy = llvm::IntegerType::get(getVMContext(),
3632 llvm::RoundUpToAlignment(Bits, 8));
3633 return ABIArgInfo::getDirect(CoerceTy);
3634 }
3635
3636 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003637 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003638 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003639
3640 return (isPromotableTypeForABI(RetTy) ?
3641 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3642}
3643
Bill Schmidt25cb3492012-10-03 19:18:57 +00003644// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3645llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3646 QualType Ty,
3647 CodeGenFunction &CGF) const {
3648 llvm::Type *BP = CGF.Int8PtrTy;
3649 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3650
3651 CGBuilderTy &Builder = CGF.Builder;
3652 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3653 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3654
Ulrich Weigand581badc2014-07-10 17:20:07 +00003655 // Handle types that require 16-byte alignment in the parameter save area.
3656 if (isAlignedParamType(Ty)) {
3657 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3658 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3659 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3660 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3661 }
3662
Bill Schmidt924c4782013-01-14 17:45:36 +00003663 // Update the va_list pointer. The pointer should be bumped by the
3664 // size of the object. We can trust getTypeSize() except for a complex
3665 // type whose base type is smaller than a doubleword. For these, the
3666 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003667 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003668 QualType BaseTy;
3669 unsigned CplxBaseSize = 0;
3670
3671 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3672 BaseTy = CTy->getElementType();
3673 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3674 if (CplxBaseSize < 8)
3675 SizeInBytes = 16;
3676 }
3677
Bill Schmidt25cb3492012-10-03 19:18:57 +00003678 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3679 llvm::Value *NextAddr =
3680 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3681 "ap.next");
3682 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3683
Bill Schmidt924c4782013-01-14 17:45:36 +00003684 // If we have a complex type and the base type is smaller than 8 bytes,
3685 // the ABI calls for the real and imaginary parts to be right-adjusted
3686 // in separate doublewords. However, Clang expects us to produce a
3687 // pointer to a structure with the two parts packed tightly. So generate
3688 // loads of the real and imaginary parts relative to the va_list pointer,
3689 // and store them to a temporary structure.
3690 if (CplxBaseSize && CplxBaseSize < 8) {
3691 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3692 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003693 if (CGF.CGM.getDataLayout().isBigEndian()) {
3694 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3695 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3696 } else {
3697 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3698 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003699 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3700 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3701 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3702 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3703 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3704 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3705 "vacplx");
3706 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3707 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3708 Builder.CreateStore(Real, RealPtr, false);
3709 Builder.CreateStore(Imag, ImagPtr, false);
3710 return Ptr;
3711 }
3712
Bill Schmidt25cb3492012-10-03 19:18:57 +00003713 // If the argument is smaller than 8 bytes, it is right-adjusted in
3714 // its doubleword slot. Adjust the pointer to pick it up from the
3715 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003716 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003717 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3718 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3719 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3720 }
3721
3722 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3723 return Builder.CreateBitCast(Addr, PTy);
3724}
3725
3726static bool
3727PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3728 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003729 // This is calculated from the LLVM and GCC tables and verified
3730 // against gcc output. AFAIK all ABIs use the same encoding.
3731
3732 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3733
3734 llvm::IntegerType *i8 = CGF.Int8Ty;
3735 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3736 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3737 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3738
3739 // 0-31: r0-31, the 8-byte general-purpose registers
3740 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3741
3742 // 32-63: fp0-31, the 8-byte floating-point registers
3743 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3744
3745 // 64-76 are various 4-byte special-purpose registers:
3746 // 64: mq
3747 // 65: lr
3748 // 66: ctr
3749 // 67: ap
3750 // 68-75 cr0-7
3751 // 76: xer
3752 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3753
3754 // 77-108: v0-31, the 16-byte vector registers
3755 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3756
3757 // 109: vrsave
3758 // 110: vscr
3759 // 111: spe_acc
3760 // 112: spefscr
3761 // 113: sfp
3762 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3763
3764 return false;
3765}
John McCallea8d8bb2010-03-11 00:10:12 +00003766
Bill Schmidt25cb3492012-10-03 19:18:57 +00003767bool
3768PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3769 CodeGen::CodeGenFunction &CGF,
3770 llvm::Value *Address) const {
3771
3772 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3773}
3774
3775bool
3776PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3777 llvm::Value *Address) const {
3778
3779 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3780}
3781
Chris Lattner0cf24192010-06-28 20:05:43 +00003782//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003783// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003784//===----------------------------------------------------------------------===//
3785
3786namespace {
3787
Tim Northover573cbee2014-05-24 12:52:07 +00003788class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003789public:
3790 enum ABIKind {
3791 AAPCS = 0,
3792 DarwinPCS
3793 };
3794
3795private:
3796 ABIKind Kind;
3797
3798public:
Tim Northover573cbee2014-05-24 12:52:07 +00003799 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003800
3801private:
3802 ABIKind getABIKind() const { return Kind; }
3803 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3804
3805 ABIArgInfo classifyReturnType(QualType RetTy) const;
3806 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3807 bool &IsHA, unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003808 bool &IsSmallAggr, bool IsNamedArg) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003809 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3810 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3811 uint64_t Members) const override;
3812
Tim Northovera2ee4332014-03-29 15:09:45 +00003813 bool isIllegalVectorType(QualType Ty) const;
3814
NAKAMURA Takumi8c894962014-11-01 01:32:27 +00003815 virtual void computeInfo(CGFunctionInfo &FI) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003816 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3817 // number of SIMD and Floating-point registers allocated so far.
3818 // If the argument is an HFA or an HVA and there are sufficient unallocated
3819 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3820 // and Floating-point Registers (with one register per member of the HFA or
3821 // HVA). Otherwise, the NSRN is set to 8.
3822 unsigned AllocatedVFP = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003823
Tim Northovera2ee4332014-03-29 15:09:45 +00003824 // To correctly handle small aggregates, we need to keep track of the number
3825 // of GPRs allocated so far. If the small aggregate can't all fit into
3826 // registers, it will be on stack. We don't allow the aggregate to be
3827 // partially in registers.
3828 unsigned AllocatedGPR = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003829
3830 // Find the number of named arguments. Variadic arguments get special
3831 // treatment with the Darwin ABI.
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003832 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Bob Wilson373af732014-04-21 01:23:39 +00003833
Reid Kleckner40ca9132014-05-13 22:05:45 +00003834 if (!getCXXABI().classifyReturnType(FI))
3835 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003836 unsigned ArgNo = 0;
Tim Northovera2ee4332014-03-29 15:09:45 +00003837 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003838 it != ie; ++it, ++ArgNo) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003839 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3840 bool IsHA = false, IsSmallAggr = false;
3841 const unsigned NumVFPs = 8;
3842 const unsigned NumGPRs = 8;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003843 bool IsNamedArg = ArgNo < NumRequiredArgs;
Tim Northovera2ee4332014-03-29 15:09:45 +00003844 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Bob Wilson373af732014-04-21 01:23:39 +00003845 AllocatedGPR, IsSmallAggr, IsNamedArg);
Tim Northover5ffc0922014-04-17 10:20:38 +00003846
3847 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3848 // as sequences of floats since they'll get "holes" inserted as
3849 // padding by the back end.
Tim Northover07f16242014-04-18 10:47:44 +00003850 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3851 getContext().getTypeAlign(it->type) < 64) {
3852 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3853 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
Tim Northover5ffc0922014-04-17 10:20:38 +00003854
Tim Northover07f16242014-04-18 10:47:44 +00003855 llvm::Type *CoerceTy = llvm::ArrayType::get(
3856 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3857 it->info = ABIArgInfo::getDirect(CoerceTy);
Tim Northover5ffc0922014-04-17 10:20:38 +00003858 }
3859
Tim Northovera2ee4332014-03-29 15:09:45 +00003860 // If we do not have enough VFP registers for the HA, any VFP registers
3861 // that are unallocated are marked as unavailable. To achieve this, we add
3862 // padding of (NumVFPs - PreAllocation) floats.
3863 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3864 llvm::Type *PaddingTy = llvm::ArrayType::get(
3865 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Tim Northover5ffc0922014-04-17 10:20:38 +00003866 it->info.setPaddingType(PaddingTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00003867 }
Tim Northover5ffc0922014-04-17 10:20:38 +00003868
Tim Northovera2ee4332014-03-29 15:09:45 +00003869 // If we do not have enough GPRs for the small aggregate, any GPR regs
3870 // that are unallocated are marked as unavailable.
3871 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3872 llvm::Type *PaddingTy = llvm::ArrayType::get(
3873 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3874 it->info =
3875 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3876 }
3877 }
3878 }
3879
3880 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3881 CodeGenFunction &CGF) const;
3882
3883 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3884 CodeGenFunction &CGF) const;
3885
3886 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
NAKAMURA Takumi8c894962014-11-01 01:32:27 +00003887 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003888 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3889 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3890 }
3891};
3892
Tim Northover573cbee2014-05-24 12:52:07 +00003893class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003894public:
Tim Northover573cbee2014-05-24 12:52:07 +00003895 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3896 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003897
3898 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3899 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3900 }
3901
3902 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3903
3904 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3905};
3906}
3907
Tim Northover573cbee2014-05-24 12:52:07 +00003908ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3909 unsigned &AllocatedVFP,
3910 bool &IsHA,
3911 unsigned &AllocatedGPR,
3912 bool &IsSmallAggr,
3913 bool IsNamedArg) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003914 // Handle illegal vector types here.
3915 if (isIllegalVectorType(Ty)) {
3916 uint64_t Size = getContext().getTypeSize(Ty);
3917 if (Size <= 32) {
3918 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3919 AllocatedGPR++;
3920 return ABIArgInfo::getDirect(ResType);
3921 }
3922 if (Size == 64) {
3923 llvm::Type *ResType =
3924 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3925 AllocatedVFP++;
3926 return ABIArgInfo::getDirect(ResType);
3927 }
3928 if (Size == 128) {
3929 llvm::Type *ResType =
3930 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3931 AllocatedVFP++;
3932 return ABIArgInfo::getDirect(ResType);
3933 }
3934 AllocatedGPR++;
3935 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3936 }
3937 if (Ty->isVectorType())
3938 // Size of a legal vector should be either 64 or 128.
3939 AllocatedVFP++;
3940 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3941 if (BT->getKind() == BuiltinType::Half ||
3942 BT->getKind() == BuiltinType::Float ||
3943 BT->getKind() == BuiltinType::Double ||
3944 BT->getKind() == BuiltinType::LongDouble)
3945 AllocatedVFP++;
3946 }
3947
3948 if (!isAggregateTypeForABI(Ty)) {
3949 // Treat an enum type as its underlying type.
3950 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3951 Ty = EnumTy->getDecl()->getIntegerType();
3952
3953 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003954 unsigned Alignment = getContext().getTypeAlign(Ty);
3955 if (!isDarwinPCS() && Alignment > 64)
3956 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3957
Tim Northovera2ee4332014-03-29 15:09:45 +00003958 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3959 AllocatedGPR += RegsNeeded;
3960 }
3961 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3962 ? ABIArgInfo::getExtend()
3963 : ABIArgInfo::getDirect());
3964 }
3965
3966 // Structures with either a non-trivial destructor or a non-trivial
3967 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003968 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003969 AllocatedGPR++;
Reid Kleckner40ca9132014-05-13 22:05:45 +00003970 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3971 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003972 }
3973
3974 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3975 // elsewhere for GNU compatibility.
3976 if (isEmptyRecord(getContext(), Ty, true)) {
3977 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3978 return ABIArgInfo::getIgnore();
3979
3980 ++AllocatedGPR;
3981 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3982 }
3983
3984 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003985 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003986 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003987 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003988 IsHA = true;
Bob Wilson373af732014-04-21 01:23:39 +00003989 if (!IsNamedArg && isDarwinPCS()) {
3990 // With the Darwin ABI, variadic arguments are always passed on the stack
3991 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3992 uint64_t Size = getContext().getTypeSize(Ty);
3993 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3994 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3995 }
3996 AllocatedVFP += Members;
Tim Northovera2ee4332014-03-29 15:09:45 +00003997 return ABIArgInfo::getExpand();
3998 }
3999
4000 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4001 uint64_t Size = getContext().getTypeSize(Ty);
4002 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004003 unsigned Alignment = getContext().getTypeAlign(Ty);
4004 if (!isDarwinPCS() && Alignment > 64)
4005 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
4006
Tim Northovera2ee4332014-03-29 15:09:45 +00004007 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
4008 AllocatedGPR += Size / 64;
4009 IsSmallAggr = true;
4010 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4011 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004012 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004013 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4014 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4015 }
4016 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4017 }
4018
4019 AllocatedGPR++;
4020 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4021}
4022
Tim Northover573cbee2014-05-24 12:52:07 +00004023ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004024 if (RetTy->isVoidType())
4025 return ABIArgInfo::getIgnore();
4026
4027 // Large vector types should be returned via memory.
4028 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4029 return ABIArgInfo::getIndirect(0);
4030
4031 if (!isAggregateTypeForABI(RetTy)) {
4032 // Treat an enum type as its underlying type.
4033 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4034 RetTy = EnumTy->getDecl()->getIntegerType();
4035
Tim Northover4dab6982014-04-18 13:46:08 +00004036 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4037 ? ABIArgInfo::getExtend()
4038 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004039 }
4040
Tim Northovera2ee4332014-03-29 15:09:45 +00004041 if (isEmptyRecord(getContext(), RetTy, true))
4042 return ABIArgInfo::getIgnore();
4043
Craig Topper8a13c412014-05-21 05:09:00 +00004044 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004045 uint64_t Members = 0;
4046 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004047 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4048 return ABIArgInfo::getDirect();
4049
4050 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4051 uint64_t Size = getContext().getTypeSize(RetTy);
4052 if (Size <= 128) {
4053 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
4054 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4055 }
4056
4057 return ABIArgInfo::getIndirect(0);
4058}
4059
Tim Northover573cbee2014-05-24 12:52:07 +00004060/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4061bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004062 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4063 // Check whether VT is legal.
4064 unsigned NumElements = VT->getNumElements();
4065 uint64_t Size = getContext().getTypeSize(VT);
4066 // NumElements should be power of 2 between 1 and 16.
4067 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4068 return true;
4069 return Size != 64 && (Size != 128 || NumElements == 1);
4070 }
4071 return false;
4072}
4073
Reid Klecknere9f6a712014-10-31 17:10:41 +00004074bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4075 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4076 // point type or a short-vector type. This is the same as the 32-bit ABI,
4077 // but with the difference that any floating-point type is allowed,
4078 // including __fp16.
4079 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4080 if (BT->isFloatingPoint())
4081 return true;
4082 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4083 unsigned VecSize = getContext().getTypeSize(VT);
4084 if (VecSize == 64 || VecSize == 128)
4085 return true;
4086 }
4087 return false;
4088}
4089
4090bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4091 uint64_t Members) const {
4092 return Members <= 4;
4093}
4094
4095llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
4096 CodeGenFunction &CGF) const {
4097 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
4098 bool IsHA = false, IsSmallAggr = false;
4099 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
4100 IsSmallAggr, false /*IsNamedArg*/);
4101 bool IsIndirect = AI.isIndirect();
4102
Tim Northovera2ee4332014-03-29 15:09:45 +00004103 // The AArch64 va_list type and handling is specified in the Procedure Call
4104 // Standard, section B.4:
4105 //
4106 // struct {
4107 // void *__stack;
4108 // void *__gr_top;
4109 // void *__vr_top;
4110 // int __gr_offs;
4111 // int __vr_offs;
4112 // };
4113
4114 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4115 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4116 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4117 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4118 auto &Ctx = CGF.getContext();
4119
Craig Topper8a13c412014-05-21 05:09:00 +00004120 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004121 int reg_top_index;
4122 int RegSize;
4123 if (AllocatedGPR) {
4124 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
4125 // 3 is the field number of __gr_offs
4126 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4127 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4128 reg_top_index = 1; // field number for __gr_top
4129 RegSize = 8 * AllocatedGPR;
4130 } else {
4131 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
4132 // 4 is the field number of __vr_offs.
4133 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4134 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4135 reg_top_index = 2; // field number for __vr_top
4136 RegSize = 16 * AllocatedVFP;
4137 }
4138
4139 //=======================================
4140 // Find out where argument was passed
4141 //=======================================
4142
4143 // If reg_offs >= 0 we're already using the stack for this type of
4144 // argument. We don't want to keep updating reg_offs (in case it overflows,
4145 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4146 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004147 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004148 UsingStack = CGF.Builder.CreateICmpSGE(
4149 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4150
4151 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4152
4153 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004154 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004155 CGF.EmitBlock(MaybeRegBlock);
4156
4157 // Integer arguments may need to correct register alignment (for example a
4158 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4159 // align __gr_offs to calculate the potential address.
4160 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4161 int Align = Ctx.getTypeAlign(Ty) / 8;
4162
4163 reg_offs = CGF.Builder.CreateAdd(
4164 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4165 "align_regoffs");
4166 reg_offs = CGF.Builder.CreateAnd(
4167 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4168 "aligned_regoffs");
4169 }
4170
4171 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004172 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004173 NewOffset = CGF.Builder.CreateAdd(
4174 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4175 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4176
4177 // Now we're in a position to decide whether this argument really was in
4178 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004179 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004180 InRegs = CGF.Builder.CreateICmpSLE(
4181 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4182
4183 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4184
4185 //=======================================
4186 // Argument was in registers
4187 //=======================================
4188
4189 // Now we emit the code for if the argument was originally passed in
4190 // registers. First start the appropriate block:
4191 CGF.EmitBlock(InRegBlock);
4192
Craig Topper8a13c412014-05-21 05:09:00 +00004193 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004194 reg_top_p =
4195 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4196 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4197 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004198 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004199 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4200
4201 if (IsIndirect) {
4202 // If it's been passed indirectly (actually a struct), whatever we find from
4203 // stored registers or on the stack will actually be a struct **.
4204 MemTy = llvm::PointerType::getUnqual(MemTy);
4205 }
4206
Craig Topper8a13c412014-05-21 05:09:00 +00004207 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004208 uint64_t NumMembers = 0;
4209 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004210 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004211 // Homogeneous aggregates passed in registers will have their elements split
4212 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4213 // qN+1, ...). We reload and store into a temporary local variable
4214 // contiguously.
4215 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4216 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4217 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4218 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4219 int Offset = 0;
4220
4221 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4222 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4223 for (unsigned i = 0; i < NumMembers; ++i) {
4224 llvm::Value *BaseOffset =
4225 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4226 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4227 LoadAddr = CGF.Builder.CreateBitCast(
4228 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
4229 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4230
4231 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4232 CGF.Builder.CreateStore(Elem, StoreAddr);
4233 }
4234
4235 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4236 } else {
4237 // Otherwise the object is contiguous in memory
4238 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004239 if (CGF.CGM.getDataLayout().isBigEndian() &&
4240 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004241 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4242 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4243 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4244
4245 BaseAddr = CGF.Builder.CreateAdd(
4246 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4247
4248 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4249 }
4250
4251 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4252 }
4253
4254 CGF.EmitBranch(ContBlock);
4255
4256 //=======================================
4257 // Argument was on the stack
4258 //=======================================
4259 CGF.EmitBlock(OnStackBlock);
4260
Craig Topper8a13c412014-05-21 05:09:00 +00004261 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004262 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4263 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4264
4265 // Again, stack arguments may need realigmnent. In this case both integer and
4266 // floating-point ones might be affected.
4267 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4268 int Align = Ctx.getTypeAlign(Ty) / 8;
4269
4270 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4271
4272 OnStackAddr = CGF.Builder.CreateAdd(
4273 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4274 "align_stack");
4275 OnStackAddr = CGF.Builder.CreateAnd(
4276 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4277 "align_stack");
4278
4279 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4280 }
4281
4282 uint64_t StackSize;
4283 if (IsIndirect)
4284 StackSize = 8;
4285 else
4286 StackSize = Ctx.getTypeSize(Ty) / 8;
4287
4288 // All stack slots are 8 bytes
4289 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4290
4291 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4292 llvm::Value *NewStack =
4293 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4294
4295 // Write the new value of __stack for the next call to va_arg
4296 CGF.Builder.CreateStore(NewStack, stack_p);
4297
4298 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4299 Ctx.getTypeSize(Ty) < 64) {
4300 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4301 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4302
4303 OnStackAddr = CGF.Builder.CreateAdd(
4304 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4305
4306 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4307 }
4308
4309 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4310
4311 CGF.EmitBranch(ContBlock);
4312
4313 //=======================================
4314 // Tidy up
4315 //=======================================
4316 CGF.EmitBlock(ContBlock);
4317
4318 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4319 ResAddr->addIncoming(RegAddr, InRegBlock);
4320 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4321
4322 if (IsIndirect)
4323 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4324
4325 return ResAddr;
4326}
4327
Tim Northover573cbee2014-05-24 12:52:07 +00004328llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004329 CodeGenFunction &CGF) const {
4330 // We do not support va_arg for aggregates or illegal vector types.
4331 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4332 // other cases.
4333 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004334 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004335
4336 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4337 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4338
Craig Topper8a13c412014-05-21 05:09:00 +00004339 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004340 uint64_t Members = 0;
4341 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004342
4343 bool isIndirect = false;
4344 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4345 // be passed indirectly.
4346 if (Size > 16 && !isHA) {
4347 isIndirect = true;
4348 Size = 8;
4349 Align = 8;
4350 }
4351
4352 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4353 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4354
4355 CGBuilderTy &Builder = CGF.Builder;
4356 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4357 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4358
4359 if (isEmptyRecord(getContext(), Ty, true)) {
4360 // These are ignored for parameter passing purposes.
4361 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4362 return Builder.CreateBitCast(Addr, PTy);
4363 }
4364
4365 const uint64_t MinABIAlign = 8;
4366 if (Align > MinABIAlign) {
4367 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4368 Addr = Builder.CreateGEP(Addr, Offset);
4369 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4370 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4371 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4372 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4373 }
4374
4375 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4376 llvm::Value *NextAddr = Builder.CreateGEP(
4377 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4378 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4379
4380 if (isIndirect)
4381 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4382 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4383 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4384
4385 return AddrTyped;
4386}
4387
4388//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004389// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004390//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004391
4392namespace {
4393
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004394class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004395public:
4396 enum ABIKind {
4397 APCS = 0,
4398 AAPCS = 1,
4399 AAPCS_VFP
4400 };
4401
4402private:
4403 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00004404 mutable int VFPRegs[16];
4405 const unsigned NumVFPs;
4406 const unsigned NumGPRs;
4407 mutable unsigned AllocatedGPRs;
4408 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004409
4410public:
Oliver Stannard405bded2014-02-11 09:25:50 +00004411 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4412 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00004413 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004414 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00004415 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004416
John McCall3480ef22011-08-30 01:42:09 +00004417 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004418 switch (getTarget().getTriple().getEnvironment()) {
4419 case llvm::Triple::Android:
4420 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004421 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004422 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004423 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004424 return true;
4425 default:
4426 return false;
4427 }
John McCall3480ef22011-08-30 01:42:09 +00004428 }
4429
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004430 bool isEABIHF() const {
4431 switch (getTarget().getTriple().getEnvironment()) {
4432 case llvm::Triple::EABIHF:
4433 case llvm::Triple::GNUEABIHF:
4434 return true;
4435 default:
4436 return false;
4437 }
4438 }
4439
Daniel Dunbar020daa92009-09-12 01:00:39 +00004440 ABIKind getABIKind() const { return Kind; }
4441
Tim Northovera484bc02013-10-01 14:34:25 +00004442private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004443 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00004444 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004445 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00004446 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004447
Reid Klecknere9f6a712014-10-31 17:10:41 +00004448 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4449 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4450 uint64_t Members) const override;
4451
Craig Topper4f12f102014-03-12 06:41:41 +00004452 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004453
Craig Topper4f12f102014-03-12 06:41:41 +00004454 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4455 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004456
4457 llvm::CallingConv::ID getLLVMDefaultCC() const;
4458 llvm::CallingConv::ID getABIDefaultCC() const;
4459 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004460
4461 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4462 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4463 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004464};
4465
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004466class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4467public:
Chris Lattner2b037972010-07-29 02:01:43 +00004468 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4469 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004470
John McCall3480ef22011-08-30 01:42:09 +00004471 const ARMABIInfo &getABIInfo() const {
4472 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4473 }
4474
Craig Topper4f12f102014-03-12 06:41:41 +00004475 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004476 return 13;
4477 }
Roman Divackyc1617352011-05-18 19:36:54 +00004478
Craig Topper4f12f102014-03-12 06:41:41 +00004479 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004480 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4481 }
4482
Roman Divackyc1617352011-05-18 19:36:54 +00004483 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004484 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004485 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004486
4487 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004488 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004489 return false;
4490 }
John McCall3480ef22011-08-30 01:42:09 +00004491
Craig Topper4f12f102014-03-12 06:41:41 +00004492 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004493 if (getABIInfo().isEABI()) return 88;
4494 return TargetCodeGenInfo::getSizeOfUnwindException();
4495 }
Tim Northovera484bc02013-10-01 14:34:25 +00004496
4497 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004498 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004499 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4500 if (!FD)
4501 return;
4502
4503 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4504 if (!Attr)
4505 return;
4506
4507 const char *Kind;
4508 switch (Attr->getInterrupt()) {
4509 case ARMInterruptAttr::Generic: Kind = ""; break;
4510 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4511 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4512 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4513 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4514 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4515 }
4516
4517 llvm::Function *Fn = cast<llvm::Function>(GV);
4518
4519 Fn->addFnAttr("interrupt", Kind);
4520
4521 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4522 return;
4523
4524 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4525 // however this is not necessarily true on taking any interrupt. Instruct
4526 // the backend to perform a realignment as part of the function prologue.
4527 llvm::AttrBuilder B;
4528 B.addStackAlignmentAttr(8);
4529 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4530 llvm::AttributeSet::get(CGM.getLLVMContext(),
4531 llvm::AttributeSet::FunctionIndex,
4532 B));
4533 }
4534
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004535};
4536
Daniel Dunbard59655c2009-09-12 00:59:49 +00004537}
4538
Chris Lattner22326a12010-07-29 02:31:05 +00004539void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004540 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00004541 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00004542 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4543 // VFP registers of the appropriate type unallocated then the argument is
4544 // allocated to the lowest-numbered sequence of such registers.
4545 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4546 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00004547 resetAllocatedRegs();
4548
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004549 const bool isAAPCS_VFP =
4550 getABIKind() == ARMABIInfo::AAPCS_VFP && !FI.isVariadic();
4551
Reid Kleckner40ca9132014-05-13 22:05:45 +00004552 if (getCXXABI().classifyReturnType(FI)) {
4553 if (FI.getReturnInfo().isIndirect())
4554 markAllocatedGPRs(1, 1);
4555 } else {
4556 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4557 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004558 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004559 unsigned PreAllocationVFPs = AllocatedVFPs;
4560 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00004561 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00004562 // 6.1.2.3 There is one VFP co-processor register class using registers
4563 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00004564 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00004565
4566 // If we have allocated some arguments onto the stack (due to running
4567 // out of VFP registers), we cannot split an argument between GPRs and
4568 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00004569 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00004570 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4571 // unusable anyway.
Oliver Stannarde0228512014-07-18 09:09:31 +00004572 // We do not have to do this if the argument is being passed ByVal, as the
4573 // backend can handle that situation correctly.
Oliver Stannard405bded2014-02-11 09:25:50 +00004574 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Oliver Stannarde0228512014-07-18 09:09:31 +00004575 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4576 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4577 StackUsed && !IsByVal) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004578 llvm::Type *PaddingTy = llvm::ArrayType::get(
4579 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004580 if (I.info.canHaveCoerceToType()) {
4581 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004582 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004583 } else {
4584 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004585 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004586 }
Manman Ren2a523d82012-10-30 23:21:41 +00004587 }
4588 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004589
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004590 // Always honor user-specified calling convention.
4591 if (FI.getCallingConvention() != llvm::CallingConv::C)
4592 return;
4593
John McCall882987f2013-02-28 19:01:20 +00004594 llvm::CallingConv::ID cc = getRuntimeCC();
4595 if (cc != llvm::CallingConv::C)
4596 FI.setEffectiveCallingConvention(cc);
4597}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004598
John McCall882987f2013-02-28 19:01:20 +00004599/// Return the default calling convention that LLVM will use.
4600llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4601 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004602 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004603 return llvm::CallingConv::ARM_AAPCS_VFP;
4604 else if (isEABI())
4605 return llvm::CallingConv::ARM_AAPCS;
4606 else
4607 return llvm::CallingConv::ARM_APCS;
4608}
4609
4610/// Return the calling convention that our ABI would like us to use
4611/// as the C calling convention.
4612llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004613 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004614 case APCS: return llvm::CallingConv::ARM_APCS;
4615 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4616 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004617 }
John McCall882987f2013-02-28 19:01:20 +00004618 llvm_unreachable("bad ABI kind");
4619}
4620
4621void ARMABIInfo::setRuntimeCC() {
4622 assert(getRuntimeCC() == llvm::CallingConv::C);
4623
4624 // Don't muddy up the IR with a ton of explicit annotations if
4625 // they'd just match what LLVM will infer from the triple.
4626 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4627 if (abiCC != getLLVMDefaultCC())
4628 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004629}
4630
Manman Renb505d332012-10-31 19:02:26 +00004631/// markAllocatedVFPs - update VFPRegs according to the alignment and
4632/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004633void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4634 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004635 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004636 if (AllocatedVFPs >= 16) {
4637 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4638 // the stack.
4639 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004640 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004641 }
Manman Renb505d332012-10-31 19:02:26 +00004642 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4643 // VFP registers of the appropriate type unallocated then the argument is
4644 // allocated to the lowest-numbered sequence of such registers.
4645 for (unsigned I = 0; I < 16; I += Alignment) {
4646 bool FoundSlot = true;
4647 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4648 if (J >= 16 || VFPRegs[J]) {
4649 FoundSlot = false;
4650 break;
4651 }
4652 if (FoundSlot) {
4653 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4654 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004655 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004656 return;
4657 }
4658 }
4659 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4660 // unallocated are marked as unavailable.
4661 for (unsigned I = 0; I < 16; I++)
4662 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004663 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004664}
4665
Oliver Stannard405bded2014-02-11 09:25:50 +00004666/// Update AllocatedGPRs to record the number of general purpose registers
4667/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4668/// this represents arguments being stored on the stack.
4669void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004670 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004671 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4672
4673 if (Alignment == 2 && AllocatedGPRs & 0x1)
4674 AllocatedGPRs += 1;
4675
4676 AllocatedGPRs += NumRequired;
4677}
4678
4679void ARMABIInfo::resetAllocatedRegs(void) const {
4680 AllocatedGPRs = 0;
4681 AllocatedVFPs = 0;
4682 for (unsigned i = 0; i < NumVFPs; ++i)
4683 VFPRegs[i] = 0;
4684}
4685
James Molloy6f244b62014-05-09 16:21:39 +00004686ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004687 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004688 // We update number of allocated VFPs according to
4689 // 6.1.2.1 The following argument types are VFP CPRCs:
4690 // A single-precision floating-point type (including promoted
4691 // half-precision types); A double-precision floating-point type;
4692 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4693 // with a Base Type of a single- or double-precision floating-point type,
4694 // 64-bit containerized vectors or 128-bit containerized vectors with one
4695 // to four Elements.
4696
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004697 const bool isAAPCS_VFP =
4698 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4699
Manman Renfef9e312012-10-16 19:18:39 +00004700 // Handle illegal vector types here.
4701 if (isIllegalVectorType(Ty)) {
4702 uint64_t Size = getContext().getTypeSize(Ty);
4703 if (Size <= 32) {
4704 llvm::Type *ResType =
4705 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004706 markAllocatedGPRs(1, 1);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004707 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004708 }
4709 if (Size == 64) {
4710 llvm::Type *ResType = llvm::VectorType::get(
4711 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004712 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4713 markAllocatedGPRs(2, 2);
4714 } else {
4715 markAllocatedVFPs(2, 2);
4716 IsCPRC = true;
4717 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004718 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004719 }
4720 if (Size == 128) {
4721 llvm::Type *ResType = llvm::VectorType::get(
4722 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004723 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4724 markAllocatedGPRs(2, 4);
4725 } else {
4726 markAllocatedVFPs(4, 4);
4727 IsCPRC = true;
4728 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004729 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004730 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004731 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004732 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4733 }
Manman Renb505d332012-10-31 19:02:26 +00004734 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004735 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4736 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4737 uint64_t Size = getContext().getTypeSize(VT);
4738 // Size of a legal vector should be power of 2 and above 64.
4739 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4740 IsCPRC = true;
4741 }
Manman Ren2a523d82012-10-30 23:21:41 +00004742 }
Manman Renb505d332012-10-31 19:02:26 +00004743 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004744 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4745 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4746 if (BT->getKind() == BuiltinType::Half ||
4747 BT->getKind() == BuiltinType::Float) {
4748 markAllocatedVFPs(1, 1);
4749 IsCPRC = true;
4750 }
4751 if (BT->getKind() == BuiltinType::Double ||
4752 BT->getKind() == BuiltinType::LongDouble) {
4753 markAllocatedVFPs(2, 2);
4754 IsCPRC = true;
4755 }
4756 }
Manman Ren2a523d82012-10-30 23:21:41 +00004757 }
Manman Renfef9e312012-10-16 19:18:39 +00004758
John McCalla1dee5302010-08-22 10:59:02 +00004759 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004760 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004761 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004762 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004763 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004764
Oliver Stannard405bded2014-02-11 09:25:50 +00004765 unsigned Size = getContext().getTypeSize(Ty);
4766 if (!IsCPRC)
4767 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004768 return (Ty->isPromotableIntegerType()
4769 ? ABIArgInfo::getExtend()
4770 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004771 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004772
Oliver Stannard405bded2014-02-11 09:25:50 +00004773 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4774 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004775 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004776 }
Tim Northover1060eae2013-06-21 22:49:34 +00004777
Daniel Dunbar09d33622009-09-14 21:54:03 +00004778 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004779 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004780 return ABIArgInfo::getIgnore();
4781
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004782 if (isAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004783 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4784 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004785 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004786 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004787 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004788 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004789 // Base can be a floating-point or a vector.
4790 if (Base->isVectorType()) {
4791 // ElementSize is in number of floats.
4792 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004793 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004794 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004795 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004796 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004797 else {
4798 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4799 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004800 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004801 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004802 IsCPRC = true;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004803 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004804 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004805 }
4806
Manman Ren6c30e132012-08-13 21:23:55 +00004807 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004808 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4809 // most 8-byte. We realign the indirect argument if type alignment is bigger
4810 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004811 uint64_t ABIAlign = 4;
4812 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4813 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4814 getABIKind() == ARMABIInfo::AAPCS)
4815 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004816 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004817 // Update Allocated GPRs. Since this is only used when the size of the
4818 // argument is greater than 64 bytes, this will always use up any available
4819 // registers (of which there are 4). We also don't care about getting the
4820 // alignment right, because general-purpose registers cannot be back-filled.
4821 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004822 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004823 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004824 }
4825
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004826 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004827 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004828 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004829 // FIXME: Try to match the types of the arguments more accurately where
4830 // we can.
4831 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004832 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4833 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004834 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004835 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004836 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4837 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004838 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004839 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004840
Chris Lattnera5f58b02011-07-09 17:41:47 +00004841 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00004842 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004843 return ABIArgInfo::getDirect(STy, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004844}
4845
Chris Lattner458b2aa2010-07-29 02:16:43 +00004846static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004847 llvm::LLVMContext &VMContext) {
4848 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4849 // is called integer-like if its size is less than or equal to one word, and
4850 // the offset of each of its addressable sub-fields is zero.
4851
4852 uint64_t Size = Context.getTypeSize(Ty);
4853
4854 // Check that the type fits in a word.
4855 if (Size > 32)
4856 return false;
4857
4858 // FIXME: Handle vector types!
4859 if (Ty->isVectorType())
4860 return false;
4861
Daniel Dunbard53bac72009-09-14 02:20:34 +00004862 // Float types are never treated as "integer like".
4863 if (Ty->isRealFloatingType())
4864 return false;
4865
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004866 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004867 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004868 return true;
4869
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004870 // Small complex integer types are "integer like".
4871 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4872 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004873
4874 // Single element and zero sized arrays should be allowed, by the definition
4875 // above, but they are not.
4876
4877 // Otherwise, it must be a record type.
4878 const RecordType *RT = Ty->getAs<RecordType>();
4879 if (!RT) return false;
4880
4881 // Ignore records with flexible arrays.
4882 const RecordDecl *RD = RT->getDecl();
4883 if (RD->hasFlexibleArrayMember())
4884 return false;
4885
4886 // Check that all sub-fields are at offset 0, and are themselves "integer
4887 // like".
4888 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4889
4890 bool HadField = false;
4891 unsigned idx = 0;
4892 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4893 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004894 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004895
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004896 // Bit-fields are not addressable, we only need to verify they are "integer
4897 // like". We still have to disallow a subsequent non-bitfield, for example:
4898 // struct { int : 0; int x }
4899 // is non-integer like according to gcc.
4900 if (FD->isBitField()) {
4901 if (!RD->isUnion())
4902 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004903
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004904 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4905 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004906
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004907 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004908 }
4909
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004910 // Check if this field is at offset 0.
4911 if (Layout.getFieldOffset(idx) != 0)
4912 return false;
4913
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004914 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4915 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004916
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004917 // Only allow at most one field in a structure. This doesn't match the
4918 // wording above, but follows gcc in situations with a field following an
4919 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004920 if (!RD->isUnion()) {
4921 if (HadField)
4922 return false;
4923
4924 HadField = true;
4925 }
4926 }
4927
4928 return true;
4929}
4930
Oliver Stannard405bded2014-02-11 09:25:50 +00004931ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4932 bool isVariadic) const {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004933 const bool isAAPCS_VFP =
4934 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4935
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004936 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004937 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004938
Daniel Dunbar19964db2010-09-23 01:54:32 +00004939 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004940 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4941 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004942 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004943 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004944
John McCalla1dee5302010-08-22 10:59:02 +00004945 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004946 // Treat an enum type as its underlying type.
4947 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4948 RetTy = EnumTy->getDecl()->getIntegerType();
4949
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004950 return (RetTy->isPromotableIntegerType()
4951 ? ABIArgInfo::getExtend()
4952 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004953 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004954
4955 // Are we following APCS?
4956 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004957 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004958 return ABIArgInfo::getIgnore();
4959
Daniel Dunbareedf1512010-02-01 23:31:19 +00004960 // Complex types are all returned as packed integers.
4961 //
4962 // FIXME: Consider using 2 x vector types if the back end handles them
4963 // correctly.
4964 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004965 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4966 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004967
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004968 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004969 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004970 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004971 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004972 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004973 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004974 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004975 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4976 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004977 }
4978
4979 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004980 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004981 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004982 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004983
4984 // Otherwise this is an AAPCS variant.
4985
Chris Lattner458b2aa2010-07-29 02:16:43 +00004986 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004987 return ABIArgInfo::getIgnore();
4988
Bob Wilson1d9269a2011-11-02 04:51:36 +00004989 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00004990 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Craig Topper8a13c412014-05-21 05:09:00 +00004991 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004992 uint64_t Members;
4993 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004994 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004995 // Homogeneous Aggregates are returned directly.
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004996 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004997 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004998 }
4999
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005000 // Aggregates <= 4 bytes are returned in r0; other aggregates
5001 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005002 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005003 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005004 if (getDataLayout().isBigEndian())
5005 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005006 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
5007 nullptr, !isAAPCS_VFP);
Christian Pirkerc3d32172014-07-03 09:28:12 +00005008
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005009 // Return in the smallest viable integer type.
5010 if (Size <= 8)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005011 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()), 0,
5012 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005013 if (Size <= 16)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005014 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()), 0,
5015 nullptr, !isAAPCS_VFP);
5016 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
5017 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005018 }
5019
Oliver Stannard405bded2014-02-11 09:25:50 +00005020 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005021 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005022}
5023
Manman Renfef9e312012-10-16 19:18:39 +00005024/// isIllegalVector - check whether Ty is an illegal vector type.
5025bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5026 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5027 // Check whether VT is legal.
5028 unsigned NumElements = VT->getNumElements();
5029 uint64_t Size = getContext().getTypeSize(VT);
5030 // NumElements should be power of 2.
5031 if ((NumElements & (NumElements - 1)) != 0)
5032 return true;
5033 // Size should be greater than 32 bits.
5034 return Size <= 32;
5035 }
5036 return false;
5037}
5038
Reid Klecknere9f6a712014-10-31 17:10:41 +00005039bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5040 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5041 // double, or 64-bit or 128-bit vectors.
5042 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5043 if (BT->getKind() == BuiltinType::Float ||
5044 BT->getKind() == BuiltinType::Double ||
5045 BT->getKind() == BuiltinType::LongDouble)
5046 return true;
5047 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5048 unsigned VecSize = getContext().getTypeSize(VT);
5049 if (VecSize == 64 || VecSize == 128)
5050 return true;
5051 }
5052 return false;
5053}
5054
5055bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5056 uint64_t Members) const {
5057 return Members <= 4;
5058}
5059
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005060llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00005061 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00005062 llvm::Type *BP = CGF.Int8PtrTy;
5063 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005064
5065 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00005066 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005067 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00005068
Tim Northover1711cc92013-06-21 23:05:33 +00005069 if (isEmptyRecord(getContext(), Ty, true)) {
5070 // These are ignored for parameter passing purposes.
5071 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5072 return Builder.CreateBitCast(Addr, PTy);
5073 }
5074
Manman Rencca54d02012-10-16 19:01:37 +00005075 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00005076 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00005077 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00005078
5079 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5080 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00005081 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5082 getABIKind() == ARMABIInfo::AAPCS)
5083 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5084 else
5085 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00005086 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5087 if (isIllegalVectorType(Ty) && Size > 16) {
5088 IsIndirect = true;
5089 Size = 4;
5090 TyAlign = 4;
5091 }
Manman Rencca54d02012-10-16 19:01:37 +00005092
5093 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00005094 if (TyAlign > 4) {
5095 assert((TyAlign & (TyAlign - 1)) == 0 &&
5096 "Alignment is not power of 2!");
5097 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
5098 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
5099 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00005100 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00005101 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005102
5103 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00005104 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005105 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00005106 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005107 "ap.next");
5108 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5109
Manman Renfef9e312012-10-16 19:18:39 +00005110 if (IsIndirect)
5111 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00005112 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00005113 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5114 // may not be correctly aligned for the vector type. We create an aligned
5115 // temporary space and copy the content over from ap.cur to the temporary
5116 // space. This is necessary if the natural alignment of the type is greater
5117 // than the ABI alignment.
5118 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5119 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5120 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5121 "var.align");
5122 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5123 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5124 Builder.CreateMemCpy(Dst, Src,
5125 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5126 TyAlign, false);
5127 Addr = AlignedTemp; //The content is in aligned location.
5128 }
5129 llvm::Type *PTy =
5130 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5131 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5132
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005133 return AddrTyped;
5134}
5135
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00005136namespace {
5137
Derek Schuffa2020962012-10-16 22:30:41 +00005138class NaClARMABIInfo : public ABIInfo {
5139 public:
5140 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5141 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005142 void computeInfo(CGFunctionInfo &FI) const override;
5143 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5144 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00005145 private:
5146 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
5147 ARMABIInfo NInfo; // Used for everything else.
5148};
5149
5150class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
5151 public:
5152 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5153 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
5154};
5155
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00005156}
5157
Derek Schuffa2020962012-10-16 22:30:41 +00005158void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5159 if (FI.getASTCallingConvention() == CC_PnaclCall)
5160 PInfo.computeInfo(FI);
5161 else
5162 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
5163}
5164
5165llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5166 CodeGenFunction &CGF) const {
5167 // Always use the native convention; calling pnacl-style varargs functions
5168 // is unsupported.
5169 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
5170}
5171
Chris Lattner0cf24192010-06-28 20:05:43 +00005172//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005173// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005174//===----------------------------------------------------------------------===//
5175
5176namespace {
5177
Justin Holewinski83e96682012-05-24 17:43:12 +00005178class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005179public:
Justin Holewinski36837432013-03-30 14:38:24 +00005180 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005181
5182 ABIArgInfo classifyReturnType(QualType RetTy) const;
5183 ABIArgInfo classifyArgumentType(QualType Ty) const;
5184
Craig Topper4f12f102014-03-12 06:41:41 +00005185 void computeInfo(CGFunctionInfo &FI) const override;
5186 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5187 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005188};
5189
Justin Holewinski83e96682012-05-24 17:43:12 +00005190class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005191public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005192 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5193 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005194
5195 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5196 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005197private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005198 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5199 // resulting MDNode to the nvvm.annotations MDNode.
5200 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005201};
5202
Justin Holewinski83e96682012-05-24 17:43:12 +00005203ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005204 if (RetTy->isVoidType())
5205 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005206
5207 // note: this is different from default ABI
5208 if (!RetTy->isScalarType())
5209 return ABIArgInfo::getDirect();
5210
5211 // Treat an enum type as its underlying type.
5212 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5213 RetTy = EnumTy->getDecl()->getIntegerType();
5214
5215 return (RetTy->isPromotableIntegerType() ?
5216 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005217}
5218
Justin Holewinski83e96682012-05-24 17:43:12 +00005219ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005220 // Treat an enum type as its underlying type.
5221 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5222 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005223
Eli Bendersky95338a02014-10-29 13:43:21 +00005224 // Return aggregates type as indirect by value
5225 if (isAggregateTypeForABI(Ty))
5226 return ABIArgInfo::getIndirect(0, /* byval */ true);
5227
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005228 return (Ty->isPromotableIntegerType() ?
5229 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005230}
5231
Justin Holewinski83e96682012-05-24 17:43:12 +00005232void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005233 if (!getCXXABI().classifyReturnType(FI))
5234 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005235 for (auto &I : FI.arguments())
5236 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005237
5238 // Always honor user-specified calling convention.
5239 if (FI.getCallingConvention() != llvm::CallingConv::C)
5240 return;
5241
John McCall882987f2013-02-28 19:01:20 +00005242 FI.setEffectiveCallingConvention(getRuntimeCC());
5243}
5244
Justin Holewinski83e96682012-05-24 17:43:12 +00005245llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5246 CodeGenFunction &CFG) const {
5247 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005248}
5249
Justin Holewinski83e96682012-05-24 17:43:12 +00005250void NVPTXTargetCodeGenInfo::
5251SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5252 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005253 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5254 if (!FD) return;
5255
5256 llvm::Function *F = cast<llvm::Function>(GV);
5257
5258 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005259 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005260 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005261 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005262 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005263 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005264 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5265 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005266 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005267 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005268 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005269 }
Justin Holewinski38031972011-10-05 17:58:44 +00005270
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005271 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005272 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005273 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005274 // __global__ functions cannot be called from the device, we do not
5275 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005276 if (FD->hasAttr<CUDAGlobalAttr>()) {
5277 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5278 addNVVMMetadata(F, "kernel", 1);
5279 }
5280 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5281 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5282 addNVVMMetadata(F, "maxntidx",
5283 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5284 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5285 // zero value from getMinBlocks either means it was not specified in
5286 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5287 // don't have to add a PTX directive.
5288 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5289 if (MinCTASM > 0) {
5290 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5291 addNVVMMetadata(F, "minctasm", MinCTASM);
5292 }
5293 }
Justin Holewinski38031972011-10-05 17:58:44 +00005294 }
5295}
5296
Eli Benderskye06a2c42014-04-15 16:57:05 +00005297void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5298 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005299 llvm::Module *M = F->getParent();
5300 llvm::LLVMContext &Ctx = M->getContext();
5301
5302 // Get "nvvm.annotations" metadata node
5303 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5304
Eli Benderskye1627b42014-04-15 17:19:26 +00005305 llvm::Value *MDVals[] = {
5306 F, llvm::MDString::get(Ctx, Name),
5307 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinski36837432013-03-30 14:38:24 +00005308 // Append metadata to nvvm.annotations
5309 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5310}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005311}
5312
5313//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005314// SystemZ ABI Implementation
5315//===----------------------------------------------------------------------===//
5316
5317namespace {
5318
5319class SystemZABIInfo : public ABIInfo {
5320public:
5321 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5322
5323 bool isPromotableIntegerType(QualType Ty) const;
5324 bool isCompoundType(QualType Ty) const;
5325 bool isFPArgumentType(QualType Ty) const;
5326
5327 ABIArgInfo classifyReturnType(QualType RetTy) const;
5328 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5329
Craig Topper4f12f102014-03-12 06:41:41 +00005330 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005331 if (!getCXXABI().classifyReturnType(FI))
5332 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005333 for (auto &I : FI.arguments())
5334 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005335 }
5336
Craig Topper4f12f102014-03-12 06:41:41 +00005337 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5338 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005339};
5340
5341class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5342public:
5343 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5344 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5345};
5346
5347}
5348
5349bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5350 // Treat an enum type as its underlying type.
5351 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5352 Ty = EnumTy->getDecl()->getIntegerType();
5353
5354 // Promotable integer types are required to be promoted by the ABI.
5355 if (Ty->isPromotableIntegerType())
5356 return true;
5357
5358 // 32-bit values must also be promoted.
5359 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5360 switch (BT->getKind()) {
5361 case BuiltinType::Int:
5362 case BuiltinType::UInt:
5363 return true;
5364 default:
5365 return false;
5366 }
5367 return false;
5368}
5369
5370bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5371 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5372}
5373
5374bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5375 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5376 switch (BT->getKind()) {
5377 case BuiltinType::Float:
5378 case BuiltinType::Double:
5379 return true;
5380 default:
5381 return false;
5382 }
5383
5384 if (const RecordType *RT = Ty->getAsStructureType()) {
5385 const RecordDecl *RD = RT->getDecl();
5386 bool Found = false;
5387
5388 // If this is a C++ record, check the bases first.
5389 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005390 for (const auto &I : CXXRD->bases()) {
5391 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005392
5393 // Empty bases don't affect things either way.
5394 if (isEmptyRecord(getContext(), Base, true))
5395 continue;
5396
5397 if (Found)
5398 return false;
5399 Found = isFPArgumentType(Base);
5400 if (!Found)
5401 return false;
5402 }
5403
5404 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005405 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005406 // Empty bitfields don't affect things either way.
5407 // Unlike isSingleElementStruct(), empty structure and array fields
5408 // do count. So do anonymous bitfields that aren't zero-sized.
5409 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5410 return true;
5411
5412 // Unlike isSingleElementStruct(), arrays do not count.
5413 // Nested isFPArgumentType structures still do though.
5414 if (Found)
5415 return false;
5416 Found = isFPArgumentType(FD->getType());
5417 if (!Found)
5418 return false;
5419 }
5420
5421 // Unlike isSingleElementStruct(), trailing padding is allowed.
5422 // An 8-byte aligned struct s { float f; } is passed as a double.
5423 return Found;
5424 }
5425
5426 return false;
5427}
5428
5429llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5430 CodeGenFunction &CGF) const {
5431 // Assume that va_list type is correct; should be pointer to LLVM type:
5432 // struct {
5433 // i64 __gpr;
5434 // i64 __fpr;
5435 // i8 *__overflow_arg_area;
5436 // i8 *__reg_save_area;
5437 // };
5438
5439 // Every argument occupies 8 bytes and is passed by preference in either
5440 // GPRs or FPRs.
5441 Ty = CGF.getContext().getCanonicalType(Ty);
5442 ABIArgInfo AI = classifyArgumentType(Ty);
5443 bool InFPRs = isFPArgumentType(Ty);
5444
5445 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5446 bool IsIndirect = AI.isIndirect();
5447 unsigned UnpaddedBitSize;
5448 if (IsIndirect) {
5449 APTy = llvm::PointerType::getUnqual(APTy);
5450 UnpaddedBitSize = 64;
5451 } else
5452 UnpaddedBitSize = getContext().getTypeSize(Ty);
5453 unsigned PaddedBitSize = 64;
5454 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5455
5456 unsigned PaddedSize = PaddedBitSize / 8;
5457 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5458
5459 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5460 if (InFPRs) {
5461 MaxRegs = 4; // Maximum of 4 FPR arguments
5462 RegCountField = 1; // __fpr
5463 RegSaveIndex = 16; // save offset for f0
5464 RegPadding = 0; // floats are passed in the high bits of an FPR
5465 } else {
5466 MaxRegs = 5; // Maximum of 5 GPR arguments
5467 RegCountField = 0; // __gpr
5468 RegSaveIndex = 2; // save offset for r2
5469 RegPadding = Padding; // values are passed in the low bits of a GPR
5470 }
5471
5472 llvm::Value *RegCountPtr =
5473 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5474 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5475 llvm::Type *IndexTy = RegCount->getType();
5476 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5477 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005478 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005479
5480 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5481 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5482 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5483 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5484
5485 // Emit code to load the value if it was passed in registers.
5486 CGF.EmitBlock(InRegBlock);
5487
5488 // Work out the address of an argument register.
5489 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5490 llvm::Value *ScaledRegCount =
5491 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5492 llvm::Value *RegBase =
5493 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5494 llvm::Value *RegOffset =
5495 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5496 llvm::Value *RegSaveAreaPtr =
5497 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5498 llvm::Value *RegSaveArea =
5499 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5500 llvm::Value *RawRegAddr =
5501 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5502 llvm::Value *RegAddr =
5503 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5504
5505 // Update the register count
5506 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5507 llvm::Value *NewRegCount =
5508 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5509 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5510 CGF.EmitBranch(ContBlock);
5511
5512 // Emit code to load the value if it was passed in memory.
5513 CGF.EmitBlock(InMemBlock);
5514
5515 // Work out the address of a stack argument.
5516 llvm::Value *OverflowArgAreaPtr =
5517 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5518 llvm::Value *OverflowArgArea =
5519 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5520 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5521 llvm::Value *RawMemAddr =
5522 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5523 llvm::Value *MemAddr =
5524 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5525
5526 // Update overflow_arg_area_ptr pointer
5527 llvm::Value *NewOverflowArgArea =
5528 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5529 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5530 CGF.EmitBranch(ContBlock);
5531
5532 // Return the appropriate result.
5533 CGF.EmitBlock(ContBlock);
5534 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5535 ResAddr->addIncoming(RegAddr, InRegBlock);
5536 ResAddr->addIncoming(MemAddr, InMemBlock);
5537
5538 if (IsIndirect)
5539 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5540
5541 return ResAddr;
5542}
5543
Ulrich Weigand47445072013-05-06 16:26:41 +00005544ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5545 if (RetTy->isVoidType())
5546 return ABIArgInfo::getIgnore();
5547 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5548 return ABIArgInfo::getIndirect(0);
5549 return (isPromotableIntegerType(RetTy) ?
5550 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5551}
5552
5553ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5554 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005555 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005556 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5557
5558 // Integers and enums are extended to full register width.
5559 if (isPromotableIntegerType(Ty))
5560 return ABIArgInfo::getExtend();
5561
5562 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5563 uint64_t Size = getContext().getTypeSize(Ty);
5564 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005565 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005566
5567 // Handle small structures.
5568 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5569 // Structures with flexible arrays have variable length, so really
5570 // fail the size test above.
5571 const RecordDecl *RD = RT->getDecl();
5572 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005573 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005574
5575 // The structure is passed as an unextended integer, a float, or a double.
5576 llvm::Type *PassTy;
5577 if (isFPArgumentType(Ty)) {
5578 assert(Size == 32 || Size == 64);
5579 if (Size == 32)
5580 PassTy = llvm::Type::getFloatTy(getVMContext());
5581 else
5582 PassTy = llvm::Type::getDoubleTy(getVMContext());
5583 } else
5584 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5585 return ABIArgInfo::getDirect(PassTy);
5586 }
5587
5588 // Non-structure compounds are passed indirectly.
5589 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005590 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005591
Craig Topper8a13c412014-05-21 05:09:00 +00005592 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005593}
5594
5595//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005596// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005597//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005598
5599namespace {
5600
5601class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5602public:
Chris Lattner2b037972010-07-29 02:01:43 +00005603 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5604 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005605 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005606 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005607};
5608
5609}
5610
5611void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5612 llvm::GlobalValue *GV,
5613 CodeGen::CodeGenModule &M) const {
5614 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5615 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5616 // Handle 'interrupt' attribute:
5617 llvm::Function *F = cast<llvm::Function>(GV);
5618
5619 // Step 1: Set ISR calling convention.
5620 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5621
5622 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005623 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005624
5625 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005626 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005627 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5628 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005629 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005630 }
5631}
5632
Chris Lattner0cf24192010-06-28 20:05:43 +00005633//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005634// MIPS ABI Implementation. This works for both little-endian and
5635// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005636//===----------------------------------------------------------------------===//
5637
John McCall943fae92010-05-27 06:19:26 +00005638namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005639class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005640 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005641 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5642 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005643 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005644 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005645 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005646 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005647public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005648 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005649 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005650 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005651
5652 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005653 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005654 void computeInfo(CGFunctionInfo &FI) const override;
5655 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5656 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005657};
5658
John McCall943fae92010-05-27 06:19:26 +00005659class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005660 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005661public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005662 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5663 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005664 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005665
Craig Topper4f12f102014-03-12 06:41:41 +00005666 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005667 return 29;
5668 }
5669
Reed Kotler373feca2013-01-16 17:10:28 +00005670 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005671 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005672 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5673 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005674 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005675 if (FD->hasAttr<Mips16Attr>()) {
5676 Fn->addFnAttr("mips16");
5677 }
5678 else if (FD->hasAttr<NoMips16Attr>()) {
5679 Fn->addFnAttr("nomips16");
5680 }
Reed Kotler373feca2013-01-16 17:10:28 +00005681 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005682
John McCall943fae92010-05-27 06:19:26 +00005683 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005684 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005685
Craig Topper4f12f102014-03-12 06:41:41 +00005686 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005687 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005688 }
John McCall943fae92010-05-27 06:19:26 +00005689};
5690}
5691
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005692void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005693 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005694 llvm::IntegerType *IntTy =
5695 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005696
5697 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5698 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5699 ArgList.push_back(IntTy);
5700
5701 // If necessary, add one more integer type to ArgList.
5702 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5703
5704 if (R)
5705 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005706}
5707
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005708// In N32/64, an aligned double precision floating point field is passed in
5709// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005710llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005711 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5712
5713 if (IsO32) {
5714 CoerceToIntArgs(TySize, ArgList);
5715 return llvm::StructType::get(getVMContext(), ArgList);
5716 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005717
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005718 if (Ty->isComplexType())
5719 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005720
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005721 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005722
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005723 // Unions/vectors are passed in integer registers.
5724 if (!RT || !RT->isStructureOrClassType()) {
5725 CoerceToIntArgs(TySize, ArgList);
5726 return llvm::StructType::get(getVMContext(), ArgList);
5727 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005728
5729 const RecordDecl *RD = RT->getDecl();
5730 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005731 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005732
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005733 uint64_t LastOffset = 0;
5734 unsigned idx = 0;
5735 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5736
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005737 // Iterate over fields in the struct/class and check if there are any aligned
5738 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005739 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5740 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005741 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005742 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5743
5744 if (!BT || BT->getKind() != BuiltinType::Double)
5745 continue;
5746
5747 uint64_t Offset = Layout.getFieldOffset(idx);
5748 if (Offset % 64) // Ignore doubles that are not aligned.
5749 continue;
5750
5751 // Add ((Offset - LastOffset) / 64) args of type i64.
5752 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5753 ArgList.push_back(I64);
5754
5755 // Add double type.
5756 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5757 LastOffset = Offset + 64;
5758 }
5759
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005760 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5761 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005762
5763 return llvm::StructType::get(getVMContext(), ArgList);
5764}
5765
Akira Hatanakaddd66342013-10-29 18:41:15 +00005766llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5767 uint64_t Offset) const {
5768 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005769 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005770
Akira Hatanakaddd66342013-10-29 18:41:15 +00005771 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005772}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005773
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005774ABIArgInfo
5775MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005776 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005777 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005778 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005779
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005780 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5781 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005782 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5783 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005784
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005785 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005786 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005787 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005788 return ABIArgInfo::getIgnore();
5789
Mark Lacey3825e832013-10-06 01:33:34 +00005790 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005791 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005792 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005793 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005794
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005795 // If we have reached here, aggregates are passed directly by coercing to
5796 // another structure type. Padding is inserted if the offset of the
5797 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005798 ABIArgInfo ArgInfo =
5799 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5800 getPaddingType(OrigOffset, CurrOffset));
5801 ArgInfo.setInReg(true);
5802 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005803 }
5804
5805 // Treat an enum type as its underlying type.
5806 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5807 Ty = EnumTy->getDecl()->getIntegerType();
5808
Daniel Sanders5b445b32014-10-24 14:42:42 +00005809 // All integral types are promoted to the GPR width.
5810 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005811 return ABIArgInfo::getExtend();
5812
Akira Hatanakaddd66342013-10-29 18:41:15 +00005813 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005814 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005815}
5816
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005817llvm::Type*
5818MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005819 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005820 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005821
Akira Hatanakab6f74432012-02-09 18:49:26 +00005822 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005823 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005824 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5825 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005826
Akira Hatanakab6f74432012-02-09 18:49:26 +00005827 // N32/64 returns struct/classes in floating point registers if the
5828 // following conditions are met:
5829 // 1. The size of the struct/class is no larger than 128-bit.
5830 // 2. The struct/class has one or two fields all of which are floating
5831 // point types.
5832 // 3. The offset of the first field is zero (this follows what gcc does).
5833 //
5834 // Any other composite results are returned in integer registers.
5835 //
5836 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5837 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5838 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005839 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005840
Akira Hatanakab6f74432012-02-09 18:49:26 +00005841 if (!BT || !BT->isFloatingPoint())
5842 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005843
David Blaikie2d7c57e2012-04-30 02:36:29 +00005844 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005845 }
5846
5847 if (b == e)
5848 return llvm::StructType::get(getVMContext(), RTList,
5849 RD->hasAttr<PackedAttr>());
5850
5851 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005852 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005853 }
5854
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005855 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005856 return llvm::StructType::get(getVMContext(), RTList);
5857}
5858
Akira Hatanakab579fe52011-06-02 00:09:17 +00005859ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005860 uint64_t Size = getContext().getTypeSize(RetTy);
5861
Daniel Sandersed39f582014-09-04 13:28:14 +00005862 if (RetTy->isVoidType())
5863 return ABIArgInfo::getIgnore();
5864
5865 // O32 doesn't treat zero-sized structs differently from other structs.
5866 // However, N32/N64 ignores zero sized return values.
5867 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005868 return ABIArgInfo::getIgnore();
5869
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005870 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005871 if (Size <= 128) {
5872 if (RetTy->isAnyComplexType())
5873 return ABIArgInfo::getDirect();
5874
Daniel Sanderse5018b62014-09-04 15:05:39 +00005875 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005876 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005877 if (!IsO32 ||
5878 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5879 ABIArgInfo ArgInfo =
5880 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5881 ArgInfo.setInReg(true);
5882 return ArgInfo;
5883 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005884 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005885
5886 return ABIArgInfo::getIndirect(0);
5887 }
5888
5889 // Treat an enum type as its underlying type.
5890 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5891 RetTy = EnumTy->getDecl()->getIntegerType();
5892
5893 return (RetTy->isPromotableIntegerType() ?
5894 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5895}
5896
5897void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005898 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005899 if (!getCXXABI().classifyReturnType(FI))
5900 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005901
5902 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005903 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005904
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005905 for (auto &I : FI.arguments())
5906 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005907}
5908
5909llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5910 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005911 llvm::Type *BP = CGF.Int8PtrTy;
5912 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5913
5914 CGBuilderTy &Builder = CGF.Builder;
5915 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5916 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005917 int64_t TypeAlign =
5918 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005919 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5920 llvm::Value *AddrTyped;
5921 unsigned PtrWidth = getTarget().getPointerWidth(0);
5922 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5923
5924 if (TypeAlign > MinABIStackAlignInBytes) {
5925 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5926 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5927 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5928 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5929 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5930 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5931 }
5932 else
5933 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5934
5935 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5936 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
5937 uint64_t Offset =
5938 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5939 llvm::Value *NextAddr =
5940 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5941 "ap.next");
5942 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5943
5944 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005945}
5946
John McCall943fae92010-05-27 06:19:26 +00005947bool
5948MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5949 llvm::Value *Address) const {
5950 // This information comes from gcc's implementation, which seems to
5951 // as canonical as it gets.
5952
John McCall943fae92010-05-27 06:19:26 +00005953 // Everything on MIPS is 4 bytes. Double-precision FP registers
5954 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005955 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005956
5957 // 0-31 are the general purpose registers, $0 - $31.
5958 // 32-63 are the floating-point registers, $f0 - $f31.
5959 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5960 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005961 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005962
5963 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5964 // They are one bit wide and ignored here.
5965
5966 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5967 // (coprocessor 1 is the FP unit)
5968 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5969 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5970 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005971 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005972 return false;
5973}
5974
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005975//===----------------------------------------------------------------------===//
5976// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5977// Currently subclassed only to implement custom OpenCL C function attribute
5978// handling.
5979//===----------------------------------------------------------------------===//
5980
5981namespace {
5982
5983class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5984public:
5985 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5986 : DefaultTargetCodeGenInfo(CGT) {}
5987
Craig Topper4f12f102014-03-12 06:41:41 +00005988 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5989 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005990};
5991
5992void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5993 llvm::GlobalValue *GV,
5994 CodeGen::CodeGenModule &M) const {
5995 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5996 if (!FD) return;
5997
5998 llvm::Function *F = cast<llvm::Function>(GV);
5999
David Blaikiebbafb8a2012-03-11 07:00:24 +00006000 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006001 if (FD->hasAttr<OpenCLKernelAttr>()) {
6002 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006003 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006004 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6005 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006006 // Convert the reqd_work_group_size() attributes to metadata.
6007 llvm::LLVMContext &Context = F->getContext();
6008 llvm::NamedMDNode *OpenCLMetadata =
6009 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
6010
6011 SmallVector<llvm::Value*, 5> Operands;
6012 Operands.push_back(F);
6013
Chris Lattnerece04092012-02-07 00:39:47 +00006014 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006015 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00006016 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006017 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00006018 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006019 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006020
6021 // Add a boolean constant operand for "required" (true) or "hint" (false)
6022 // for implementing the work_group_size_hint attr later. Currently
6023 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00006024 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006025 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6026 }
6027 }
6028 }
6029}
6030
6031}
John McCall943fae92010-05-27 06:19:26 +00006032
Tony Linthicum76329bf2011-12-12 21:14:55 +00006033//===----------------------------------------------------------------------===//
6034// Hexagon ABI Implementation
6035//===----------------------------------------------------------------------===//
6036
6037namespace {
6038
6039class HexagonABIInfo : public ABIInfo {
6040
6041
6042public:
6043 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6044
6045private:
6046
6047 ABIArgInfo classifyReturnType(QualType RetTy) const;
6048 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6049
Craig Topper4f12f102014-03-12 06:41:41 +00006050 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006051
Craig Topper4f12f102014-03-12 06:41:41 +00006052 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6053 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006054};
6055
6056class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6057public:
6058 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6059 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6060
Craig Topper4f12f102014-03-12 06:41:41 +00006061 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006062 return 29;
6063 }
6064};
6065
6066}
6067
6068void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006069 if (!getCXXABI().classifyReturnType(FI))
6070 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006071 for (auto &I : FI.arguments())
6072 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006073}
6074
6075ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6076 if (!isAggregateTypeForABI(Ty)) {
6077 // Treat an enum type as its underlying type.
6078 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6079 Ty = EnumTy->getDecl()->getIntegerType();
6080
6081 return (Ty->isPromotableIntegerType() ?
6082 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6083 }
6084
6085 // Ignore empty records.
6086 if (isEmptyRecord(getContext(), Ty, true))
6087 return ABIArgInfo::getIgnore();
6088
Mark Lacey3825e832013-10-06 01:33:34 +00006089 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00006090 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006091
6092 uint64_t Size = getContext().getTypeSize(Ty);
6093 if (Size > 64)
6094 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6095 // Pass in the smallest viable integer type.
6096 else if (Size > 32)
6097 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6098 else if (Size > 16)
6099 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6100 else if (Size > 8)
6101 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6102 else
6103 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6104}
6105
6106ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6107 if (RetTy->isVoidType())
6108 return ABIArgInfo::getIgnore();
6109
6110 // Large vector types should be returned via memory.
6111 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6112 return ABIArgInfo::getIndirect(0);
6113
6114 if (!isAggregateTypeForABI(RetTy)) {
6115 // Treat an enum type as its underlying type.
6116 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6117 RetTy = EnumTy->getDecl()->getIntegerType();
6118
6119 return (RetTy->isPromotableIntegerType() ?
6120 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6121 }
6122
Tony Linthicum76329bf2011-12-12 21:14:55 +00006123 if (isEmptyRecord(getContext(), RetTy, true))
6124 return ABIArgInfo::getIgnore();
6125
6126 // Aggregates <= 8 bytes are returned in r0; other aggregates
6127 // are returned indirectly.
6128 uint64_t Size = getContext().getTypeSize(RetTy);
6129 if (Size <= 64) {
6130 // Return in the smallest viable integer type.
6131 if (Size <= 8)
6132 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6133 if (Size <= 16)
6134 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6135 if (Size <= 32)
6136 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6137 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6138 }
6139
6140 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6141}
6142
6143llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006144 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006145 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006146 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006147
6148 CGBuilderTy &Builder = CGF.Builder;
6149 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6150 "ap");
6151 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6152 llvm::Type *PTy =
6153 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6154 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6155
6156 uint64_t Offset =
6157 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6158 llvm::Value *NextAddr =
6159 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6160 "ap.next");
6161 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6162
6163 return AddrTyped;
6164}
6165
6166
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006167//===----------------------------------------------------------------------===//
6168// SPARC v9 ABI Implementation.
6169// Based on the SPARC Compliance Definition version 2.4.1.
6170//
6171// Function arguments a mapped to a nominal "parameter array" and promoted to
6172// registers depending on their type. Each argument occupies 8 or 16 bytes in
6173// the array, structs larger than 16 bytes are passed indirectly.
6174//
6175// One case requires special care:
6176//
6177// struct mixed {
6178// int i;
6179// float f;
6180// };
6181//
6182// When a struct mixed is passed by value, it only occupies 8 bytes in the
6183// parameter array, but the int is passed in an integer register, and the float
6184// is passed in a floating point register. This is represented as two arguments
6185// with the LLVM IR inreg attribute:
6186//
6187// declare void f(i32 inreg %i, float inreg %f)
6188//
6189// The code generator will only allocate 4 bytes from the parameter array for
6190// the inreg arguments. All other arguments are allocated a multiple of 8
6191// bytes.
6192//
6193namespace {
6194class SparcV9ABIInfo : public ABIInfo {
6195public:
6196 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6197
6198private:
6199 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006200 void computeInfo(CGFunctionInfo &FI) const override;
6201 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6202 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006203
6204 // Coercion type builder for structs passed in registers. The coercion type
6205 // serves two purposes:
6206 //
6207 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6208 // in registers.
6209 // 2. Expose aligned floating point elements as first-level elements, so the
6210 // code generator knows to pass them in floating point registers.
6211 //
6212 // We also compute the InReg flag which indicates that the struct contains
6213 // aligned 32-bit floats.
6214 //
6215 struct CoerceBuilder {
6216 llvm::LLVMContext &Context;
6217 const llvm::DataLayout &DL;
6218 SmallVector<llvm::Type*, 8> Elems;
6219 uint64_t Size;
6220 bool InReg;
6221
6222 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6223 : Context(c), DL(dl), Size(0), InReg(false) {}
6224
6225 // Pad Elems with integers until Size is ToSize.
6226 void pad(uint64_t ToSize) {
6227 assert(ToSize >= Size && "Cannot remove elements");
6228 if (ToSize == Size)
6229 return;
6230
6231 // Finish the current 64-bit word.
6232 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6233 if (Aligned > Size && Aligned <= ToSize) {
6234 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6235 Size = Aligned;
6236 }
6237
6238 // Add whole 64-bit words.
6239 while (Size + 64 <= ToSize) {
6240 Elems.push_back(llvm::Type::getInt64Ty(Context));
6241 Size += 64;
6242 }
6243
6244 // Final in-word padding.
6245 if (Size < ToSize) {
6246 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6247 Size = ToSize;
6248 }
6249 }
6250
6251 // Add a floating point element at Offset.
6252 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6253 // Unaligned floats are treated as integers.
6254 if (Offset % Bits)
6255 return;
6256 // The InReg flag is only required if there are any floats < 64 bits.
6257 if (Bits < 64)
6258 InReg = true;
6259 pad(Offset);
6260 Elems.push_back(Ty);
6261 Size = Offset + Bits;
6262 }
6263
6264 // Add a struct type to the coercion type, starting at Offset (in bits).
6265 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6266 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6267 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6268 llvm::Type *ElemTy = StrTy->getElementType(i);
6269 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6270 switch (ElemTy->getTypeID()) {
6271 case llvm::Type::StructTyID:
6272 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6273 break;
6274 case llvm::Type::FloatTyID:
6275 addFloat(ElemOffset, ElemTy, 32);
6276 break;
6277 case llvm::Type::DoubleTyID:
6278 addFloat(ElemOffset, ElemTy, 64);
6279 break;
6280 case llvm::Type::FP128TyID:
6281 addFloat(ElemOffset, ElemTy, 128);
6282 break;
6283 case llvm::Type::PointerTyID:
6284 if (ElemOffset % 64 == 0) {
6285 pad(ElemOffset);
6286 Elems.push_back(ElemTy);
6287 Size += 64;
6288 }
6289 break;
6290 default:
6291 break;
6292 }
6293 }
6294 }
6295
6296 // Check if Ty is a usable substitute for the coercion type.
6297 bool isUsableType(llvm::StructType *Ty) const {
6298 if (Ty->getNumElements() != Elems.size())
6299 return false;
6300 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6301 if (Elems[i] != Ty->getElementType(i))
6302 return false;
6303 return true;
6304 }
6305
6306 // Get the coercion type as a literal struct type.
6307 llvm::Type *getType() const {
6308 if (Elems.size() == 1)
6309 return Elems.front();
6310 else
6311 return llvm::StructType::get(Context, Elems);
6312 }
6313 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006314};
6315} // end anonymous namespace
6316
6317ABIArgInfo
6318SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6319 if (Ty->isVoidType())
6320 return ABIArgInfo::getIgnore();
6321
6322 uint64_t Size = getContext().getTypeSize(Ty);
6323
6324 // Anything too big to fit in registers is passed with an explicit indirect
6325 // pointer / sret pointer.
6326 if (Size > SizeLimit)
6327 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6328
6329 // Treat an enum type as its underlying type.
6330 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6331 Ty = EnumTy->getDecl()->getIntegerType();
6332
6333 // Integer types smaller than a register are extended.
6334 if (Size < 64 && Ty->isIntegerType())
6335 return ABIArgInfo::getExtend();
6336
6337 // Other non-aggregates go in registers.
6338 if (!isAggregateTypeForABI(Ty))
6339 return ABIArgInfo::getDirect();
6340
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006341 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6342 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6343 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6344 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6345
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006346 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006347 // Build a coercion type from the LLVM struct type.
6348 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6349 if (!StrTy)
6350 return ABIArgInfo::getDirect();
6351
6352 CoerceBuilder CB(getVMContext(), getDataLayout());
6353 CB.addStruct(0, StrTy);
6354 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6355
6356 // Try to use the original type for coercion.
6357 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6358
6359 if (CB.InReg)
6360 return ABIArgInfo::getDirectInReg(CoerceTy);
6361 else
6362 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006363}
6364
6365llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6366 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006367 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6368 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6369 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6370 AI.setCoerceToType(ArgTy);
6371
6372 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6373 CGBuilderTy &Builder = CGF.Builder;
6374 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6375 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6376 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6377 llvm::Value *ArgAddr;
6378 unsigned Stride;
6379
6380 switch (AI.getKind()) {
6381 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006382 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006383 llvm_unreachable("Unsupported ABI kind for va_arg");
6384
6385 case ABIArgInfo::Extend:
6386 Stride = 8;
6387 ArgAddr = Builder
6388 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6389 "extend");
6390 break;
6391
6392 case ABIArgInfo::Direct:
6393 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6394 ArgAddr = Addr;
6395 break;
6396
6397 case ABIArgInfo::Indirect:
6398 Stride = 8;
6399 ArgAddr = Builder.CreateBitCast(Addr,
6400 llvm::PointerType::getUnqual(ArgPtrTy),
6401 "indirect");
6402 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6403 break;
6404
6405 case ABIArgInfo::Ignore:
6406 return llvm::UndefValue::get(ArgPtrTy);
6407 }
6408
6409 // Update VAList.
6410 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6411 Builder.CreateStore(Addr, VAListAddrAsBPP);
6412
6413 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006414}
6415
6416void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6417 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006418 for (auto &I : FI.arguments())
6419 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006420}
6421
6422namespace {
6423class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6424public:
6425 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6426 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006427
Craig Topper4f12f102014-03-12 06:41:41 +00006428 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006429 return 14;
6430 }
6431
6432 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006433 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006434};
6435} // end anonymous namespace
6436
Roman Divackyf02c9942014-02-24 18:46:27 +00006437bool
6438SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6439 llvm::Value *Address) const {
6440 // This is calculated from the LLVM and GCC tables and verified
6441 // against gcc output. AFAIK all ABIs use the same encoding.
6442
6443 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6444
6445 llvm::IntegerType *i8 = CGF.Int8Ty;
6446 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6447 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6448
6449 // 0-31: the 8-byte general-purpose registers
6450 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6451
6452 // 32-63: f0-31, the 4-byte floating-point registers
6453 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6454
6455 // Y = 64
6456 // PSR = 65
6457 // WIM = 66
6458 // TBR = 67
6459 // PC = 68
6460 // NPC = 69
6461 // FSR = 70
6462 // CSR = 71
6463 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6464
6465 // 72-87: d0-15, the 8-byte floating-point registers
6466 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6467
6468 return false;
6469}
6470
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006471
Robert Lytton0e076492013-08-13 09:43:10 +00006472//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006473// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006474//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006475
Robert Lytton0e076492013-08-13 09:43:10 +00006476namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006477
6478/// A SmallStringEnc instance is used to build up the TypeString by passing
6479/// it by reference between functions that append to it.
6480typedef llvm::SmallString<128> SmallStringEnc;
6481
6482/// TypeStringCache caches the meta encodings of Types.
6483///
6484/// The reason for caching TypeStrings is two fold:
6485/// 1. To cache a type's encoding for later uses;
6486/// 2. As a means to break recursive member type inclusion.
6487///
6488/// A cache Entry can have a Status of:
6489/// NonRecursive: The type encoding is not recursive;
6490/// Recursive: The type encoding is recursive;
6491/// Incomplete: An incomplete TypeString;
6492/// IncompleteUsed: An incomplete TypeString that has been used in a
6493/// Recursive type encoding.
6494///
6495/// A NonRecursive entry will have all of its sub-members expanded as fully
6496/// as possible. Whilst it may contain types which are recursive, the type
6497/// itself is not recursive and thus its encoding may be safely used whenever
6498/// the type is encountered.
6499///
6500/// A Recursive entry will have all of its sub-members expanded as fully as
6501/// possible. The type itself is recursive and it may contain other types which
6502/// are recursive. The Recursive encoding must not be used during the expansion
6503/// of a recursive type's recursive branch. For simplicity the code uses
6504/// IncompleteCount to reject all usage of Recursive encodings for member types.
6505///
6506/// An Incomplete entry is always a RecordType and only encodes its
6507/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6508/// are placed into the cache during type expansion as a means to identify and
6509/// handle recursive inclusion of types as sub-members. If there is recursion
6510/// the entry becomes IncompleteUsed.
6511///
6512/// During the expansion of a RecordType's members:
6513///
6514/// If the cache contains a NonRecursive encoding for the member type, the
6515/// cached encoding is used;
6516///
6517/// If the cache contains a Recursive encoding for the member type, the
6518/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6519///
6520/// If the member is a RecordType, an Incomplete encoding is placed into the
6521/// cache to break potential recursive inclusion of itself as a sub-member;
6522///
6523/// Once a member RecordType has been expanded, its temporary incomplete
6524/// entry is removed from the cache. If a Recursive encoding was swapped out
6525/// it is swapped back in;
6526///
6527/// If an incomplete entry is used to expand a sub-member, the incomplete
6528/// entry is marked as IncompleteUsed. The cache keeps count of how many
6529/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6530///
6531/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6532/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6533/// Else the member is part of a recursive type and thus the recursion has
6534/// been exited too soon for the encoding to be correct for the member.
6535///
6536class TypeStringCache {
6537 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6538 struct Entry {
6539 std::string Str; // The encoded TypeString for the type.
6540 enum Status State; // Information about the encoding in 'Str'.
6541 std::string Swapped; // A temporary place holder for a Recursive encoding
6542 // during the expansion of RecordType's members.
6543 };
6544 std::map<const IdentifierInfo *, struct Entry> Map;
6545 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6546 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6547public:
Robert Lyttond263f142014-05-06 09:38:54 +00006548 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006549 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6550 bool removeIncomplete(const IdentifierInfo *ID);
6551 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6552 bool IsRecursive);
6553 StringRef lookupStr(const IdentifierInfo *ID);
6554};
6555
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006556/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006557/// FieldEncoding is a helper for this ordering process.
6558class FieldEncoding {
6559 bool HasName;
6560 std::string Enc;
6561public:
6562 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6563 StringRef str() {return Enc.c_str();};
6564 bool operator<(const FieldEncoding &rhs) const {
6565 if (HasName != rhs.HasName) return HasName;
6566 return Enc < rhs.Enc;
6567 }
6568};
6569
Robert Lytton7d1db152013-08-19 09:46:39 +00006570class XCoreABIInfo : public DefaultABIInfo {
6571public:
6572 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006573 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6574 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006575};
6576
Robert Lyttond21e2d72014-03-03 13:45:29 +00006577class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006578 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006579public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006580 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006581 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006582 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6583 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006584};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006585
Robert Lytton2d196952013-10-11 10:29:34 +00006586} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006587
Robert Lytton7d1db152013-08-19 09:46:39 +00006588llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6589 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006590 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006591
Robert Lytton2d196952013-10-11 10:29:34 +00006592 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006593 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6594 CGF.Int8PtrPtrTy);
6595 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006596
Robert Lytton2d196952013-10-11 10:29:34 +00006597 // Handle the argument.
6598 ABIArgInfo AI = classifyArgumentType(Ty);
6599 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6600 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6601 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006602 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006603 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006604 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006605 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006606 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006607 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006608 llvm_unreachable("Unsupported ABI kind for va_arg");
6609 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006610 Val = llvm::UndefValue::get(ArgPtrTy);
6611 ArgSize = 0;
6612 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006613 case ABIArgInfo::Extend:
6614 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006615 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6616 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6617 if (ArgSize < 4)
6618 ArgSize = 4;
6619 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006620 case ABIArgInfo::Indirect:
6621 llvm::Value *ArgAddr;
6622 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6623 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006624 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6625 ArgSize = 4;
6626 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006627 }
Robert Lytton2d196952013-10-11 10:29:34 +00006628
6629 // Increment the VAList.
6630 if (ArgSize) {
6631 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6632 Builder.CreateStore(APN, VAListAddrAsBPP);
6633 }
6634 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006635}
Robert Lytton0e076492013-08-13 09:43:10 +00006636
Robert Lytton844aeeb2014-05-02 09:33:20 +00006637/// During the expansion of a RecordType, an incomplete TypeString is placed
6638/// into the cache as a means to identify and break recursion.
6639/// If there is a Recursive encoding in the cache, it is swapped out and will
6640/// be reinserted by removeIncomplete().
6641/// All other types of encoding should have been used rather than arriving here.
6642void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6643 std::string StubEnc) {
6644 if (!ID)
6645 return;
6646 Entry &E = Map[ID];
6647 assert( (E.Str.empty() || E.State == Recursive) &&
6648 "Incorrectly use of addIncomplete");
6649 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6650 E.Swapped.swap(E.Str); // swap out the Recursive
6651 E.Str.swap(StubEnc);
6652 E.State = Incomplete;
6653 ++IncompleteCount;
6654}
6655
6656/// Once the RecordType has been expanded, the temporary incomplete TypeString
6657/// must be removed from the cache.
6658/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6659/// Returns true if the RecordType was defined recursively.
6660bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6661 if (!ID)
6662 return false;
6663 auto I = Map.find(ID);
6664 assert(I != Map.end() && "Entry not present");
6665 Entry &E = I->second;
6666 assert( (E.State == Incomplete ||
6667 E.State == IncompleteUsed) &&
6668 "Entry must be an incomplete type");
6669 bool IsRecursive = false;
6670 if (E.State == IncompleteUsed) {
6671 // We made use of our Incomplete encoding, thus we are recursive.
6672 IsRecursive = true;
6673 --IncompleteUsedCount;
6674 }
6675 if (E.Swapped.empty())
6676 Map.erase(I);
6677 else {
6678 // Swap the Recursive back.
6679 E.Swapped.swap(E.Str);
6680 E.Swapped.clear();
6681 E.State = Recursive;
6682 }
6683 --IncompleteCount;
6684 return IsRecursive;
6685}
6686
6687/// Add the encoded TypeString to the cache only if it is NonRecursive or
6688/// Recursive (viz: all sub-members were expanded as fully as possible).
6689void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6690 bool IsRecursive) {
6691 if (!ID || IncompleteUsedCount)
6692 return; // No key or it is is an incomplete sub-type so don't add.
6693 Entry &E = Map[ID];
6694 if (IsRecursive && !E.Str.empty()) {
6695 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6696 "This is not the same Recursive entry");
6697 // The parent container was not recursive after all, so we could have used
6698 // this Recursive sub-member entry after all, but we assumed the worse when
6699 // we started viz: IncompleteCount!=0.
6700 return;
6701 }
6702 assert(E.Str.empty() && "Entry already present");
6703 E.Str = Str.str();
6704 E.State = IsRecursive? Recursive : NonRecursive;
6705}
6706
6707/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6708/// are recursively expanding a type (IncompleteCount != 0) and the cached
6709/// encoding is Recursive, return an empty StringRef.
6710StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6711 if (!ID)
6712 return StringRef(); // We have no key.
6713 auto I = Map.find(ID);
6714 if (I == Map.end())
6715 return StringRef(); // We have no encoding.
6716 Entry &E = I->second;
6717 if (E.State == Recursive && IncompleteCount)
6718 return StringRef(); // We don't use Recursive encodings for member types.
6719
6720 if (E.State == Incomplete) {
6721 // The incomplete type is being used to break out of recursion.
6722 E.State = IncompleteUsed;
6723 ++IncompleteUsedCount;
6724 }
6725 return E.Str.c_str();
6726}
6727
6728/// The XCore ABI includes a type information section that communicates symbol
6729/// type information to the linker. The linker uses this information to verify
6730/// safety/correctness of things such as array bound and pointers et al.
6731/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6732/// This type information (TypeString) is emitted into meta data for all global
6733/// symbols: definitions, declarations, functions & variables.
6734///
6735/// The TypeString carries type, qualifier, name, size & value details.
6736/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6737/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6738/// The output is tested by test/CodeGen/xcore-stringtype.c.
6739///
6740static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6741 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6742
6743/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6744void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6745 CodeGen::CodeGenModule &CGM) const {
6746 SmallStringEnc Enc;
6747 if (getTypeString(Enc, D, CGM, TSC)) {
6748 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6749 llvm::SmallVector<llvm::Value *, 2> MDVals;
6750 MDVals.push_back(GV);
6751 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6752 llvm::NamedMDNode *MD =
6753 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6754 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6755 }
6756}
6757
6758static bool appendType(SmallStringEnc &Enc, QualType QType,
6759 const CodeGen::CodeGenModule &CGM,
6760 TypeStringCache &TSC);
6761
6762/// Helper function for appendRecordType().
6763/// Builds a SmallVector containing the encoded field types in declaration order.
6764static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6765 const RecordDecl *RD,
6766 const CodeGen::CodeGenModule &CGM,
6767 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006768 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006769 SmallStringEnc Enc;
6770 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006771 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006772 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006773 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006774 Enc += "b(";
6775 llvm::raw_svector_ostream OS(Enc);
6776 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006777 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006778 OS.flush();
6779 Enc += ':';
6780 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006781 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006782 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006783 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006784 Enc += ')';
6785 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006786 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006787 }
6788 return true;
6789}
6790
6791/// Appends structure and union types to Enc and adds encoding to cache.
6792/// Recursively calls appendType (via extractFieldType) for each field.
6793/// Union types have their fields ordered according to the ABI.
6794static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6795 const CodeGen::CodeGenModule &CGM,
6796 TypeStringCache &TSC, const IdentifierInfo *ID) {
6797 // Append the cached TypeString if we have one.
6798 StringRef TypeString = TSC.lookupStr(ID);
6799 if (!TypeString.empty()) {
6800 Enc += TypeString;
6801 return true;
6802 }
6803
6804 // Start to emit an incomplete TypeString.
6805 size_t Start = Enc.size();
6806 Enc += (RT->isUnionType()? 'u' : 's');
6807 Enc += '(';
6808 if (ID)
6809 Enc += ID->getName();
6810 Enc += "){";
6811
6812 // We collect all encoded fields and order as necessary.
6813 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006814 const RecordDecl *RD = RT->getDecl()->getDefinition();
6815 if (RD && !RD->field_empty()) {
6816 // An incomplete TypeString stub is placed in the cache for this RecordType
6817 // so that recursive calls to this RecordType will use it whilst building a
6818 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006819 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006820 std::string StubEnc(Enc.substr(Start).str());
6821 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6822 TSC.addIncomplete(ID, std::move(StubEnc));
6823 if (!extractFieldType(FE, RD, CGM, TSC)) {
6824 (void) TSC.removeIncomplete(ID);
6825 return false;
6826 }
6827 IsRecursive = TSC.removeIncomplete(ID);
6828 // The ABI requires unions to be sorted but not structures.
6829 // See FieldEncoding::operator< for sort algorithm.
6830 if (RT->isUnionType())
6831 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006832 // We can now complete the TypeString.
6833 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006834 for (unsigned I = 0; I != E; ++I) {
6835 if (I)
6836 Enc += ',';
6837 Enc += FE[I].str();
6838 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006839 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006840 Enc += '}';
6841 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6842 return true;
6843}
6844
6845/// Appends enum types to Enc and adds the encoding to the cache.
6846static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6847 TypeStringCache &TSC,
6848 const IdentifierInfo *ID) {
6849 // Append the cached TypeString if we have one.
6850 StringRef TypeString = TSC.lookupStr(ID);
6851 if (!TypeString.empty()) {
6852 Enc += TypeString;
6853 return true;
6854 }
6855
6856 size_t Start = Enc.size();
6857 Enc += "e(";
6858 if (ID)
6859 Enc += ID->getName();
6860 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006861
6862 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006863 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006864 SmallVector<FieldEncoding, 16> FE;
6865 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6866 ++I) {
6867 SmallStringEnc EnumEnc;
6868 EnumEnc += "m(";
6869 EnumEnc += I->getName();
6870 EnumEnc += "){";
6871 I->getInitVal().toString(EnumEnc);
6872 EnumEnc += '}';
6873 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6874 }
6875 std::sort(FE.begin(), FE.end());
6876 unsigned E = FE.size();
6877 for (unsigned I = 0; I != E; ++I) {
6878 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006879 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006880 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006881 }
6882 }
6883 Enc += '}';
6884 TSC.addIfComplete(ID, Enc.substr(Start), false);
6885 return true;
6886}
6887
6888/// Appends type's qualifier to Enc.
6889/// This is done prior to appending the type's encoding.
6890static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6891 // Qualifiers are emitted in alphabetical order.
6892 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6893 int Lookup = 0;
6894 if (QT.isConstQualified())
6895 Lookup += 1<<0;
6896 if (QT.isRestrictQualified())
6897 Lookup += 1<<1;
6898 if (QT.isVolatileQualified())
6899 Lookup += 1<<2;
6900 Enc += Table[Lookup];
6901}
6902
6903/// Appends built-in types to Enc.
6904static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6905 const char *EncType;
6906 switch (BT->getKind()) {
6907 case BuiltinType::Void:
6908 EncType = "0";
6909 break;
6910 case BuiltinType::Bool:
6911 EncType = "b";
6912 break;
6913 case BuiltinType::Char_U:
6914 EncType = "uc";
6915 break;
6916 case BuiltinType::UChar:
6917 EncType = "uc";
6918 break;
6919 case BuiltinType::SChar:
6920 EncType = "sc";
6921 break;
6922 case BuiltinType::UShort:
6923 EncType = "us";
6924 break;
6925 case BuiltinType::Short:
6926 EncType = "ss";
6927 break;
6928 case BuiltinType::UInt:
6929 EncType = "ui";
6930 break;
6931 case BuiltinType::Int:
6932 EncType = "si";
6933 break;
6934 case BuiltinType::ULong:
6935 EncType = "ul";
6936 break;
6937 case BuiltinType::Long:
6938 EncType = "sl";
6939 break;
6940 case BuiltinType::ULongLong:
6941 EncType = "ull";
6942 break;
6943 case BuiltinType::LongLong:
6944 EncType = "sll";
6945 break;
6946 case BuiltinType::Float:
6947 EncType = "ft";
6948 break;
6949 case BuiltinType::Double:
6950 EncType = "d";
6951 break;
6952 case BuiltinType::LongDouble:
6953 EncType = "ld";
6954 break;
6955 default:
6956 return false;
6957 }
6958 Enc += EncType;
6959 return true;
6960}
6961
6962/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6963static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6964 const CodeGen::CodeGenModule &CGM,
6965 TypeStringCache &TSC) {
6966 Enc += "p(";
6967 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6968 return false;
6969 Enc += ')';
6970 return true;
6971}
6972
6973/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006974static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6975 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006976 const CodeGen::CodeGenModule &CGM,
6977 TypeStringCache &TSC, StringRef NoSizeEnc) {
6978 if (AT->getSizeModifier() != ArrayType::Normal)
6979 return false;
6980 Enc += "a(";
6981 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6982 CAT->getSize().toStringUnsigned(Enc);
6983 else
6984 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6985 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006986 // The Qualifiers should be attached to the type rather than the array.
6987 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006988 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6989 return false;
6990 Enc += ')';
6991 return true;
6992}
6993
6994/// Appends a function encoding to Enc, calling appendType for the return type
6995/// and the arguments.
6996static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6997 const CodeGen::CodeGenModule &CGM,
6998 TypeStringCache &TSC) {
6999 Enc += "f{";
7000 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7001 return false;
7002 Enc += "}(";
7003 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7004 // N.B. we are only interested in the adjusted param types.
7005 auto I = FPT->param_type_begin();
7006 auto E = FPT->param_type_end();
7007 if (I != E) {
7008 do {
7009 if (!appendType(Enc, *I, CGM, TSC))
7010 return false;
7011 ++I;
7012 if (I != E)
7013 Enc += ',';
7014 } while (I != E);
7015 if (FPT->isVariadic())
7016 Enc += ",va";
7017 } else {
7018 if (FPT->isVariadic())
7019 Enc += "va";
7020 else
7021 Enc += '0';
7022 }
7023 }
7024 Enc += ')';
7025 return true;
7026}
7027
7028/// Handles the type's qualifier before dispatching a call to handle specific
7029/// type encodings.
7030static bool appendType(SmallStringEnc &Enc, QualType QType,
7031 const CodeGen::CodeGenModule &CGM,
7032 TypeStringCache &TSC) {
7033
7034 QualType QT = QType.getCanonicalType();
7035
Robert Lytton6adb20f2014-06-05 09:06:21 +00007036 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7037 // The Qualifiers should be attached to the type rather than the array.
7038 // Thus we don't call appendQualifier() here.
7039 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7040
Robert Lytton844aeeb2014-05-02 09:33:20 +00007041 appendQualifier(Enc, QT);
7042
7043 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7044 return appendBuiltinType(Enc, BT);
7045
Robert Lytton844aeeb2014-05-02 09:33:20 +00007046 if (const PointerType *PT = QT->getAs<PointerType>())
7047 return appendPointerType(Enc, PT, CGM, TSC);
7048
7049 if (const EnumType *ET = QT->getAs<EnumType>())
7050 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7051
7052 if (const RecordType *RT = QT->getAsStructureType())
7053 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7054
7055 if (const RecordType *RT = QT->getAsUnionType())
7056 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7057
7058 if (const FunctionType *FT = QT->getAs<FunctionType>())
7059 return appendFunctionType(Enc, FT, CGM, TSC);
7060
7061 return false;
7062}
7063
7064static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7065 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7066 if (!D)
7067 return false;
7068
7069 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7070 if (FD->getLanguageLinkage() != CLanguageLinkage)
7071 return false;
7072 return appendType(Enc, FD->getType(), CGM, TSC);
7073 }
7074
7075 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7076 if (VD->getLanguageLinkage() != CLanguageLinkage)
7077 return false;
7078 QualType QT = VD->getType().getCanonicalType();
7079 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7080 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007081 // The Qualifiers should be attached to the type rather than the array.
7082 // Thus we don't call appendQualifier() here.
7083 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007084 }
7085 return appendType(Enc, QT, CGM, TSC);
7086 }
7087 return false;
7088}
7089
7090
Robert Lytton0e076492013-08-13 09:43:10 +00007091//===----------------------------------------------------------------------===//
7092// Driver code
7093//===----------------------------------------------------------------------===//
7094
Rafael Espindola9f834732014-09-19 01:54:22 +00007095const llvm::Triple &CodeGenModule::getTriple() const {
7096 return getTarget().getTriple();
7097}
7098
7099bool CodeGenModule::supportsCOMDAT() const {
7100 return !getTriple().isOSBinFormatMachO();
7101}
7102
Chris Lattner2b037972010-07-29 02:01:43 +00007103const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007104 if (TheTargetCodeGenInfo)
7105 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007106
John McCallc8e01702013-04-16 22:48:15 +00007107 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007108 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007109 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007110 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007111
Derek Schuff09338a22012-09-06 17:37:28 +00007112 case llvm::Triple::le32:
7113 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007114 case llvm::Triple::mips:
7115 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007116 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7117
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007118 case llvm::Triple::mips64:
7119 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007120 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7121
Tim Northover25e8a672014-05-24 12:51:25 +00007122 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007123 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007124 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007125 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007126 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007127
Tim Northover573cbee2014-05-24 12:52:07 +00007128 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007129 }
7130
Daniel Dunbard59655c2009-09-12 00:59:49 +00007131 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007132 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007133 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007134 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007135 {
7136 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007137 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007138 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007139 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007140 (CodeGenOpts.FloatABI != "soft" &&
7141 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007142 Kind = ARMABIInfo::AAPCS_VFP;
7143
Derek Schuffa2020962012-10-16 22:30:41 +00007144 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00007145 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00007146 return *(TheTargetCodeGenInfo =
7147 new NaClARMTargetCodeGenInfo(Types, Kind));
7148 default:
7149 return *(TheTargetCodeGenInfo =
7150 new ARMTargetCodeGenInfo(Types, Kind));
7151 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007152 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007153
John McCallea8d8bb2010-03-11 00:10:12 +00007154 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007155 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007156 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007157 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007158 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007159 if (getTarget().getABI() == "elfv2")
7160 Kind = PPC64_SVR4_ABIInfo::ELFv2;
7161
Ulrich Weigandb7122372014-07-21 00:48:09 +00007162 return *(TheTargetCodeGenInfo =
7163 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7164 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007165 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007166 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007167 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007168 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007169 if (getTarget().getABI() == "elfv1")
7170 Kind = PPC64_SVR4_ABIInfo::ELFv1;
7171
Ulrich Weigandb7122372014-07-21 00:48:09 +00007172 return *(TheTargetCodeGenInfo =
7173 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7174 }
John McCallea8d8bb2010-03-11 00:10:12 +00007175
Peter Collingbournec947aae2012-05-20 23:28:41 +00007176 case llvm::Triple::nvptx:
7177 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007178 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007179
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007180 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007181 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007182
Ulrich Weigand47445072013-05-06 16:26:41 +00007183 case llvm::Triple::systemz:
7184 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
7185
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007186 case llvm::Triple::tce:
7187 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7188
Eli Friedman33465822011-07-08 23:31:17 +00007189 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007190 bool IsDarwinVectorABI = Triple.isOSDarwin();
7191 bool IsSmallStructInRegABI =
7192 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00007193 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007194
John McCall1fe2a8c2013-06-18 02:46:29 +00007195 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007196 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007197 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007198 IsDarwinVectorABI, IsSmallStructInRegABI,
7199 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007200 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007201 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007202 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007203 new X86_32TargetCodeGenInfo(Types,
7204 IsDarwinVectorABI, IsSmallStructInRegABI,
7205 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007206 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007207 }
Eli Friedman33465822011-07-08 23:31:17 +00007208 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007209
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007210 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007211 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007212
Chris Lattner04dc9572010-08-31 16:44:54 +00007213 switch (Triple.getOS()) {
7214 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007215 return *(TheTargetCodeGenInfo =
7216 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Eli Benderskyd7c92032012-12-04 18:38:10 +00007217 case llvm::Triple::NaCl:
Alexander Musman09184fe2014-09-30 05:29:28 +00007218 return *(TheTargetCodeGenInfo =
7219 new NaClX86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007220 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007221 return *(TheTargetCodeGenInfo =
7222 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007223 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007224 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007225 case llvm::Triple::hexagon:
7226 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007227 case llvm::Triple::sparcv9:
7228 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007229 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007230 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007231 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007232}