blob: 70348c5350a50b2c73b38055bf2a6b7e3f355fde [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
3075
3076namespace {
3077class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3078public:
Chris Lattner2b037972010-07-29 02:01:43 +00003079 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003080
Craig Topper4f12f102014-03-12 06:41:41 +00003081 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003082 // This is recovered from gcc output.
3083 return 1; // r1 is the dedicated stack pointer
3084 }
3085
3086 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003087 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003088
3089 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3090 return 16; // Natural alignment for Altivec vectors.
3091 }
John McCallea8d8bb2010-03-11 00:10:12 +00003092};
3093
3094}
3095
3096bool
3097PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3098 llvm::Value *Address) const {
3099 // This is calculated from the LLVM and GCC tables and verified
3100 // against gcc output. AFAIK all ABIs use the same encoding.
3101
3102 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003103
Chris Lattnerece04092012-02-07 00:39:47 +00003104 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003105 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3106 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3107 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3108
3109 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003110 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003111
3112 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003113 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003114
3115 // 64-76 are various 4-byte special-purpose registers:
3116 // 64: mq
3117 // 65: lr
3118 // 66: ctr
3119 // 67: ap
3120 // 68-75 cr0-7
3121 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003122 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003123
3124 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003125 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003126
3127 // 109: vrsave
3128 // 110: vscr
3129 // 111: spe_acc
3130 // 112: spefscr
3131 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003132 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003133
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003134 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003135}
3136
Roman Divackyd966e722012-05-09 18:22:46 +00003137// PowerPC-64
3138
3139namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003140/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3141class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003142public:
3143 enum ABIKind {
3144 ELFv1 = 0,
3145 ELFv2
3146 };
3147
3148private:
3149 static const unsigned GPRBits = 64;
3150 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003151
3152public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003153 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3154 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003155
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003156 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003157 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003158
3159 ABIArgInfo classifyReturnType(QualType RetTy) const;
3160 ABIArgInfo classifyArgumentType(QualType Ty) const;
3161
Reid Klecknere9f6a712014-10-31 17:10:41 +00003162 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3163 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3164 uint64_t Members) const override;
3165
Bill Schmidt84d37792012-10-12 19:26:17 +00003166 // TODO: We can add more logic to computeInfo to improve performance.
3167 // Example: For aggregate arguments that fit in a register, we could
3168 // use getDirectInReg (as is done below for structs containing a single
3169 // floating-point value) to avoid pushing them to memory on function
3170 // entry. This would require changing the logic in PPCISelLowering
3171 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003172 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003173 if (!getCXXABI().classifyReturnType(FI))
3174 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003175 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003176 // We rely on the default argument classification for the most part.
3177 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003178 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003179 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003180 if (T) {
3181 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003182 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3183 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003184 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003185 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003186 continue;
3187 }
3188 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003189 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003190 }
3191 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003192
Craig Topper4f12f102014-03-12 06:41:41 +00003193 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3194 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003195};
3196
3197class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3198public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003199 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3200 PPC64_SVR4_ABIInfo::ABIKind Kind)
3201 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003202
Craig Topper4f12f102014-03-12 06:41:41 +00003203 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003204 // This is recovered from gcc output.
3205 return 1; // r1 is the dedicated stack pointer
3206 }
3207
3208 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003209 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003210
3211 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3212 return 16; // Natural alignment for Altivec and VSX vectors.
3213 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003214};
3215
Roman Divackyd966e722012-05-09 18:22:46 +00003216class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3217public:
3218 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3219
Craig Topper4f12f102014-03-12 06:41:41 +00003220 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003221 // This is recovered from gcc output.
3222 return 1; // r1 is the dedicated stack pointer
3223 }
3224
3225 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003226 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003227
3228 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3229 return 16; // Natural alignment for Altivec vectors.
3230 }
Roman Divackyd966e722012-05-09 18:22:46 +00003231};
3232
3233}
3234
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003235// Return true if the ABI requires Ty to be passed sign- or zero-
3236// extended to 64 bits.
3237bool
3238PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3239 // Treat an enum type as its underlying type.
3240 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3241 Ty = EnumTy->getDecl()->getIntegerType();
3242
3243 // Promotable integer types are required to be promoted by the ABI.
3244 if (Ty->isPromotableIntegerType())
3245 return true;
3246
3247 // In addition to the usual promotable integer types, we also need to
3248 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3249 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3250 switch (BT->getKind()) {
3251 case BuiltinType::Int:
3252 case BuiltinType::UInt:
3253 return true;
3254 default:
3255 break;
3256 }
3257
3258 return false;
3259}
3260
Ulrich Weigand581badc2014-07-10 17:20:07 +00003261/// isAlignedParamType - Determine whether a type requires 16-byte
3262/// alignment in the parameter area.
3263bool
3264PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3265 // Complex types are passed just like their elements.
3266 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3267 Ty = CTy->getElementType();
3268
3269 // Only vector types of size 16 bytes need alignment (larger types are
3270 // passed via reference, smaller types are not aligned).
3271 if (Ty->isVectorType())
3272 return getContext().getTypeSize(Ty) == 128;
3273
3274 // For single-element float/vector structs, we consider the whole type
3275 // to have the same alignment requirements as its single element.
3276 const Type *AlignAsType = nullptr;
3277 const Type *EltType = isSingleElementStruct(Ty, getContext());
3278 if (EltType) {
3279 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3280 if ((EltType->isVectorType() &&
3281 getContext().getTypeSize(EltType) == 128) ||
3282 (BT && BT->isFloatingPoint()))
3283 AlignAsType = EltType;
3284 }
3285
Ulrich Weigandb7122372014-07-21 00:48:09 +00003286 // Likewise for ELFv2 homogeneous aggregates.
3287 const Type *Base = nullptr;
3288 uint64_t Members = 0;
3289 if (!AlignAsType && Kind == ELFv2 &&
3290 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3291 AlignAsType = Base;
3292
Ulrich Weigand581badc2014-07-10 17:20:07 +00003293 // With special case aggregates, only vector base types need alignment.
3294 if (AlignAsType)
3295 return AlignAsType->isVectorType();
3296
3297 // Otherwise, we only need alignment for any aggregate type that
3298 // has an alignment requirement of >= 16 bytes.
3299 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3300 return true;
3301
3302 return false;
3303}
3304
Ulrich Weigandb7122372014-07-21 00:48:09 +00003305/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3306/// aggregate. Base is set to the base element type, and Members is set
3307/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003308bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3309 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003310 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3311 uint64_t NElements = AT->getSize().getZExtValue();
3312 if (NElements == 0)
3313 return false;
3314 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3315 return false;
3316 Members *= NElements;
3317 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3318 const RecordDecl *RD = RT->getDecl();
3319 if (RD->hasFlexibleArrayMember())
3320 return false;
3321
3322 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003323
3324 // If this is a C++ record, check the bases first.
3325 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3326 for (const auto &I : CXXRD->bases()) {
3327 // Ignore empty records.
3328 if (isEmptyRecord(getContext(), I.getType(), true))
3329 continue;
3330
3331 uint64_t FldMembers;
3332 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3333 return false;
3334
3335 Members += FldMembers;
3336 }
3337 }
3338
Ulrich Weigandb7122372014-07-21 00:48:09 +00003339 for (const auto *FD : RD->fields()) {
3340 // Ignore (non-zero arrays of) empty records.
3341 QualType FT = FD->getType();
3342 while (const ConstantArrayType *AT =
3343 getContext().getAsConstantArrayType(FT)) {
3344 if (AT->getSize().getZExtValue() == 0)
3345 return false;
3346 FT = AT->getElementType();
3347 }
3348 if (isEmptyRecord(getContext(), FT, true))
3349 continue;
3350
3351 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3352 if (getContext().getLangOpts().CPlusPlus &&
3353 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3354 continue;
3355
3356 uint64_t FldMembers;
3357 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3358 return false;
3359
3360 Members = (RD->isUnion() ?
3361 std::max(Members, FldMembers) : Members + FldMembers);
3362 }
3363
3364 if (!Base)
3365 return false;
3366
3367 // Ensure there is no padding.
3368 if (getContext().getTypeSize(Base) * Members !=
3369 getContext().getTypeSize(Ty))
3370 return false;
3371 } else {
3372 Members = 1;
3373 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3374 Members = 2;
3375 Ty = CT->getElementType();
3376 }
3377
Reid Klecknere9f6a712014-10-31 17:10:41 +00003378 // Most ABIs only support float, double, and some vector type widths.
3379 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003380 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003381
3382 // The base type must be the same for all members. Types that
3383 // agree in both total size and mode (float vs. vector) are
3384 // treated as being equivalent here.
3385 const Type *TyPtr = Ty.getTypePtr();
3386 if (!Base)
3387 Base = TyPtr;
3388
3389 if (Base->isVectorType() != TyPtr->isVectorType() ||
3390 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3391 return false;
3392 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003393 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3394}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003395
Reid Klecknere9f6a712014-10-31 17:10:41 +00003396bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3397 // Homogeneous aggregates for ELFv2 must have base types of float,
3398 // double, long double, or 128-bit vectors.
3399 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3400 if (BT->getKind() == BuiltinType::Float ||
3401 BT->getKind() == BuiltinType::Double ||
3402 BT->getKind() == BuiltinType::LongDouble)
3403 return true;
3404 }
3405 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3406 if (getContext().getTypeSize(VT) == 128)
3407 return true;
3408 }
3409 return false;
3410}
3411
3412bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3413 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003414 // Vector types require one register, floating point types require one
3415 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003416 uint32_t NumRegs =
3417 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003418
3419 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003420 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003421}
3422
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003423ABIArgInfo
3424PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00003425 if (Ty->isAnyComplexType())
3426 return ABIArgInfo::getDirect();
3427
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003428 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3429 // or via reference (larger than 16 bytes).
3430 if (Ty->isVectorType()) {
3431 uint64_t Size = getContext().getTypeSize(Ty);
3432 if (Size > 128)
3433 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3434 else if (Size < 128) {
3435 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3436 return ABIArgInfo::getDirect(CoerceTy);
3437 }
3438 }
3439
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003440 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003441 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003442 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003443
Ulrich Weigand581badc2014-07-10 17:20:07 +00003444 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3445 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003446
3447 // ELFv2 homogeneous aggregates are passed as array types.
3448 const Type *Base = nullptr;
3449 uint64_t Members = 0;
3450 if (Kind == ELFv2 &&
3451 isHomogeneousAggregate(Ty, Base, Members)) {
3452 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3453 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3454 return ABIArgInfo::getDirect(CoerceTy);
3455 }
3456
Ulrich Weigand601957f2014-07-21 00:56:36 +00003457 // If an aggregate may end up fully in registers, we do not
3458 // use the ByVal method, but pass the aggregate as array.
3459 // This is usually beneficial since we avoid forcing the
3460 // back-end to store the argument to memory.
3461 uint64_t Bits = getContext().getTypeSize(Ty);
3462 if (Bits > 0 && Bits <= 8 * GPRBits) {
3463 llvm::Type *CoerceTy;
3464
3465 // Types up to 8 bytes are passed as integer type (which will be
3466 // properly aligned in the argument save area doubleword).
3467 if (Bits <= GPRBits)
3468 CoerceTy = llvm::IntegerType::get(getVMContext(),
3469 llvm::RoundUpToAlignment(Bits, 8));
3470 // Larger types are passed as arrays, with the base type selected
3471 // according to the required alignment in the save area.
3472 else {
3473 uint64_t RegBits = ABIAlign * 8;
3474 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3475 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3476 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3477 }
3478
3479 return ABIArgInfo::getDirect(CoerceTy);
3480 }
3481
Ulrich Weigandb7122372014-07-21 00:48:09 +00003482 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003483 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3484 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003485 }
3486
3487 return (isPromotableTypeForABI(Ty) ?
3488 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3489}
3490
3491ABIArgInfo
3492PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3493 if (RetTy->isVoidType())
3494 return ABIArgInfo::getIgnore();
3495
Bill Schmidta3d121c2012-12-17 04:20:17 +00003496 if (RetTy->isAnyComplexType())
3497 return ABIArgInfo::getDirect();
3498
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003499 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3500 // or via reference (larger than 16 bytes).
3501 if (RetTy->isVectorType()) {
3502 uint64_t Size = getContext().getTypeSize(RetTy);
3503 if (Size > 128)
3504 return ABIArgInfo::getIndirect(0);
3505 else if (Size < 128) {
3506 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3507 return ABIArgInfo::getDirect(CoerceTy);
3508 }
3509 }
3510
Ulrich Weigandb7122372014-07-21 00:48:09 +00003511 if (isAggregateTypeForABI(RetTy)) {
3512 // ELFv2 homogeneous aggregates are returned as array types.
3513 const Type *Base = nullptr;
3514 uint64_t Members = 0;
3515 if (Kind == ELFv2 &&
3516 isHomogeneousAggregate(RetTy, Base, Members)) {
3517 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3518 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3519 return ABIArgInfo::getDirect(CoerceTy);
3520 }
3521
3522 // ELFv2 small aggregates are returned in up to two registers.
3523 uint64_t Bits = getContext().getTypeSize(RetTy);
3524 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3525 if (Bits == 0)
3526 return ABIArgInfo::getIgnore();
3527
3528 llvm::Type *CoerceTy;
3529 if (Bits > GPRBits) {
3530 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3531 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3532 } else
3533 CoerceTy = llvm::IntegerType::get(getVMContext(),
3534 llvm::RoundUpToAlignment(Bits, 8));
3535 return ABIArgInfo::getDirect(CoerceTy);
3536 }
3537
3538 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003539 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003540 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003541
3542 return (isPromotableTypeForABI(RetTy) ?
3543 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3544}
3545
Bill Schmidt25cb3492012-10-03 19:18:57 +00003546// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3547llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3548 QualType Ty,
3549 CodeGenFunction &CGF) const {
3550 llvm::Type *BP = CGF.Int8PtrTy;
3551 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3552
3553 CGBuilderTy &Builder = CGF.Builder;
3554 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3555 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3556
Ulrich Weigand581badc2014-07-10 17:20:07 +00003557 // Handle types that require 16-byte alignment in the parameter save area.
3558 if (isAlignedParamType(Ty)) {
3559 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3560 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3561 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3562 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3563 }
3564
Bill Schmidt924c4782013-01-14 17:45:36 +00003565 // Update the va_list pointer. The pointer should be bumped by the
3566 // size of the object. We can trust getTypeSize() except for a complex
3567 // type whose base type is smaller than a doubleword. For these, the
3568 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003569 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003570 QualType BaseTy;
3571 unsigned CplxBaseSize = 0;
3572
3573 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3574 BaseTy = CTy->getElementType();
3575 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3576 if (CplxBaseSize < 8)
3577 SizeInBytes = 16;
3578 }
3579
Bill Schmidt25cb3492012-10-03 19:18:57 +00003580 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3581 llvm::Value *NextAddr =
3582 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3583 "ap.next");
3584 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3585
Bill Schmidt924c4782013-01-14 17:45:36 +00003586 // If we have a complex type and the base type is smaller than 8 bytes,
3587 // the ABI calls for the real and imaginary parts to be right-adjusted
3588 // in separate doublewords. However, Clang expects us to produce a
3589 // pointer to a structure with the two parts packed tightly. So generate
3590 // loads of the real and imaginary parts relative to the va_list pointer,
3591 // and store them to a temporary structure.
3592 if (CplxBaseSize && CplxBaseSize < 8) {
3593 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3594 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003595 if (CGF.CGM.getDataLayout().isBigEndian()) {
3596 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3597 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3598 } else {
3599 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3600 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003601 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3602 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3603 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3604 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3605 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3606 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3607 "vacplx");
3608 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3609 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3610 Builder.CreateStore(Real, RealPtr, false);
3611 Builder.CreateStore(Imag, ImagPtr, false);
3612 return Ptr;
3613 }
3614
Bill Schmidt25cb3492012-10-03 19:18:57 +00003615 // If the argument is smaller than 8 bytes, it is right-adjusted in
3616 // its doubleword slot. Adjust the pointer to pick it up from the
3617 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003618 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003619 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3620 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3621 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3622 }
3623
3624 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3625 return Builder.CreateBitCast(Addr, PTy);
3626}
3627
3628static bool
3629PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3630 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003631 // This is calculated from the LLVM and GCC tables and verified
3632 // against gcc output. AFAIK all ABIs use the same encoding.
3633
3634 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3635
3636 llvm::IntegerType *i8 = CGF.Int8Ty;
3637 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3638 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3639 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3640
3641 // 0-31: r0-31, the 8-byte general-purpose registers
3642 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3643
3644 // 32-63: fp0-31, the 8-byte floating-point registers
3645 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3646
3647 // 64-76 are various 4-byte special-purpose registers:
3648 // 64: mq
3649 // 65: lr
3650 // 66: ctr
3651 // 67: ap
3652 // 68-75 cr0-7
3653 // 76: xer
3654 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3655
3656 // 77-108: v0-31, the 16-byte vector registers
3657 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3658
3659 // 109: vrsave
3660 // 110: vscr
3661 // 111: spe_acc
3662 // 112: spefscr
3663 // 113: sfp
3664 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3665
3666 return false;
3667}
John McCallea8d8bb2010-03-11 00:10:12 +00003668
Bill Schmidt25cb3492012-10-03 19:18:57 +00003669bool
3670PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3671 CodeGen::CodeGenFunction &CGF,
3672 llvm::Value *Address) const {
3673
3674 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3675}
3676
3677bool
3678PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3679 llvm::Value *Address) const {
3680
3681 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3682}
3683
Chris Lattner0cf24192010-06-28 20:05:43 +00003684//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003685// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003686//===----------------------------------------------------------------------===//
3687
3688namespace {
3689
Tim Northover573cbee2014-05-24 12:52:07 +00003690class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003691public:
3692 enum ABIKind {
3693 AAPCS = 0,
3694 DarwinPCS
3695 };
3696
3697private:
3698 ABIKind Kind;
3699
3700public:
Tim Northover573cbee2014-05-24 12:52:07 +00003701 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003702
3703private:
3704 ABIKind getABIKind() const { return Kind; }
3705 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3706
3707 ABIArgInfo classifyReturnType(QualType RetTy) const;
3708 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3709 bool &IsHA, unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003710 bool &IsSmallAggr, bool IsNamedArg) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003711 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3712 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3713 uint64_t Members) const override;
3714
Tim Northovera2ee4332014-03-29 15:09:45 +00003715 bool isIllegalVectorType(QualType Ty) const;
3716
NAKAMURA Takumi8c894962014-11-01 01:32:27 +00003717 virtual void computeInfo(CGFunctionInfo &FI) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003718 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3719 // number of SIMD and Floating-point registers allocated so far.
3720 // If the argument is an HFA or an HVA and there are sufficient unallocated
3721 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3722 // and Floating-point Registers (with one register per member of the HFA or
3723 // HVA). Otherwise, the NSRN is set to 8.
3724 unsigned AllocatedVFP = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003725
Tim Northovera2ee4332014-03-29 15:09:45 +00003726 // To correctly handle small aggregates, we need to keep track of the number
3727 // of GPRs allocated so far. If the small aggregate can't all fit into
3728 // registers, it will be on stack. We don't allow the aggregate to be
3729 // partially in registers.
3730 unsigned AllocatedGPR = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003731
3732 // Find the number of named arguments. Variadic arguments get special
3733 // treatment with the Darwin ABI.
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003734 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Bob Wilson373af732014-04-21 01:23:39 +00003735
Reid Kleckner40ca9132014-05-13 22:05:45 +00003736 if (!getCXXABI().classifyReturnType(FI))
3737 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003738 unsigned ArgNo = 0;
Tim Northovera2ee4332014-03-29 15:09:45 +00003739 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003740 it != ie; ++it, ++ArgNo) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003741 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3742 bool IsHA = false, IsSmallAggr = false;
3743 const unsigned NumVFPs = 8;
3744 const unsigned NumGPRs = 8;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003745 bool IsNamedArg = ArgNo < NumRequiredArgs;
Tim Northovera2ee4332014-03-29 15:09:45 +00003746 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Bob Wilson373af732014-04-21 01:23:39 +00003747 AllocatedGPR, IsSmallAggr, IsNamedArg);
Tim Northover5ffc0922014-04-17 10:20:38 +00003748
3749 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3750 // as sequences of floats since they'll get "holes" inserted as
3751 // padding by the back end.
Tim Northover07f16242014-04-18 10:47:44 +00003752 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3753 getContext().getTypeAlign(it->type) < 64) {
3754 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3755 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
Tim Northover5ffc0922014-04-17 10:20:38 +00003756
Tim Northover07f16242014-04-18 10:47:44 +00003757 llvm::Type *CoerceTy = llvm::ArrayType::get(
3758 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3759 it->info = ABIArgInfo::getDirect(CoerceTy);
Tim Northover5ffc0922014-04-17 10:20:38 +00003760 }
3761
Tim Northovera2ee4332014-03-29 15:09:45 +00003762 // If we do not have enough VFP registers for the HA, any VFP registers
3763 // that are unallocated are marked as unavailable. To achieve this, we add
3764 // padding of (NumVFPs - PreAllocation) floats.
3765 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3766 llvm::Type *PaddingTy = llvm::ArrayType::get(
3767 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Tim Northover5ffc0922014-04-17 10:20:38 +00003768 it->info.setPaddingType(PaddingTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00003769 }
Tim Northover5ffc0922014-04-17 10:20:38 +00003770
Tim Northovera2ee4332014-03-29 15:09:45 +00003771 // If we do not have enough GPRs for the small aggregate, any GPR regs
3772 // that are unallocated are marked as unavailable.
3773 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3774 llvm::Type *PaddingTy = llvm::ArrayType::get(
3775 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3776 it->info =
3777 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3778 }
3779 }
3780 }
3781
3782 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3783 CodeGenFunction &CGF) const;
3784
3785 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3786 CodeGenFunction &CGF) const;
3787
3788 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
NAKAMURA Takumi8c894962014-11-01 01:32:27 +00003789 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003790 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3791 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3792 }
3793};
3794
Tim Northover573cbee2014-05-24 12:52:07 +00003795class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003796public:
Tim Northover573cbee2014-05-24 12:52:07 +00003797 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3798 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003799
3800 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3801 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3802 }
3803
3804 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3805
3806 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3807};
3808}
3809
Tim Northover573cbee2014-05-24 12:52:07 +00003810ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3811 unsigned &AllocatedVFP,
3812 bool &IsHA,
3813 unsigned &AllocatedGPR,
3814 bool &IsSmallAggr,
3815 bool IsNamedArg) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003816 // Handle illegal vector types here.
3817 if (isIllegalVectorType(Ty)) {
3818 uint64_t Size = getContext().getTypeSize(Ty);
3819 if (Size <= 32) {
3820 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3821 AllocatedGPR++;
3822 return ABIArgInfo::getDirect(ResType);
3823 }
3824 if (Size == 64) {
3825 llvm::Type *ResType =
3826 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3827 AllocatedVFP++;
3828 return ABIArgInfo::getDirect(ResType);
3829 }
3830 if (Size == 128) {
3831 llvm::Type *ResType =
3832 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3833 AllocatedVFP++;
3834 return ABIArgInfo::getDirect(ResType);
3835 }
3836 AllocatedGPR++;
3837 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3838 }
3839 if (Ty->isVectorType())
3840 // Size of a legal vector should be either 64 or 128.
3841 AllocatedVFP++;
3842 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3843 if (BT->getKind() == BuiltinType::Half ||
3844 BT->getKind() == BuiltinType::Float ||
3845 BT->getKind() == BuiltinType::Double ||
3846 BT->getKind() == BuiltinType::LongDouble)
3847 AllocatedVFP++;
3848 }
3849
3850 if (!isAggregateTypeForABI(Ty)) {
3851 // Treat an enum type as its underlying type.
3852 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3853 Ty = EnumTy->getDecl()->getIntegerType();
3854
3855 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003856 unsigned Alignment = getContext().getTypeAlign(Ty);
3857 if (!isDarwinPCS() && Alignment > 64)
3858 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3859
Tim Northovera2ee4332014-03-29 15:09:45 +00003860 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3861 AllocatedGPR += RegsNeeded;
3862 }
3863 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3864 ? ABIArgInfo::getExtend()
3865 : ABIArgInfo::getDirect());
3866 }
3867
3868 // Structures with either a non-trivial destructor or a non-trivial
3869 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003870 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003871 AllocatedGPR++;
Reid Kleckner40ca9132014-05-13 22:05:45 +00003872 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3873 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003874 }
3875
3876 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3877 // elsewhere for GNU compatibility.
3878 if (isEmptyRecord(getContext(), Ty, true)) {
3879 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3880 return ABIArgInfo::getIgnore();
3881
3882 ++AllocatedGPR;
3883 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3884 }
3885
3886 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003887 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003888 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003889 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003890 IsHA = true;
Bob Wilson373af732014-04-21 01:23:39 +00003891 if (!IsNamedArg && isDarwinPCS()) {
3892 // With the Darwin ABI, variadic arguments are always passed on the stack
3893 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3894 uint64_t Size = getContext().getTypeSize(Ty);
3895 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3896 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3897 }
3898 AllocatedVFP += Members;
Tim Northovera2ee4332014-03-29 15:09:45 +00003899 return ABIArgInfo::getExpand();
3900 }
3901
3902 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3903 uint64_t Size = getContext().getTypeSize(Ty);
3904 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003905 unsigned Alignment = getContext().getTypeAlign(Ty);
3906 if (!isDarwinPCS() && Alignment > 64)
3907 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3908
Tim Northovera2ee4332014-03-29 15:09:45 +00003909 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3910 AllocatedGPR += Size / 64;
3911 IsSmallAggr = true;
3912 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3913 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003914 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003915 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3916 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3917 }
3918 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3919 }
3920
3921 AllocatedGPR++;
3922 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3923}
3924
Tim Northover573cbee2014-05-24 12:52:07 +00003925ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003926 if (RetTy->isVoidType())
3927 return ABIArgInfo::getIgnore();
3928
3929 // Large vector types should be returned via memory.
3930 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3931 return ABIArgInfo::getIndirect(0);
3932
3933 if (!isAggregateTypeForABI(RetTy)) {
3934 // Treat an enum type as its underlying type.
3935 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3936 RetTy = EnumTy->getDecl()->getIntegerType();
3937
Tim Northover4dab6982014-04-18 13:46:08 +00003938 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3939 ? ABIArgInfo::getExtend()
3940 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003941 }
3942
Tim Northovera2ee4332014-03-29 15:09:45 +00003943 if (isEmptyRecord(getContext(), RetTy, true))
3944 return ABIArgInfo::getIgnore();
3945
Craig Topper8a13c412014-05-21 05:09:00 +00003946 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003947 uint64_t Members = 0;
3948 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00003949 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3950 return ABIArgInfo::getDirect();
3951
3952 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3953 uint64_t Size = getContext().getTypeSize(RetTy);
3954 if (Size <= 128) {
3955 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3956 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3957 }
3958
3959 return ABIArgInfo::getIndirect(0);
3960}
3961
Tim Northover573cbee2014-05-24 12:52:07 +00003962/// isIllegalVectorType - check whether the vector type is legal for AArch64.
3963bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003964 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3965 // Check whether VT is legal.
3966 unsigned NumElements = VT->getNumElements();
3967 uint64_t Size = getContext().getTypeSize(VT);
3968 // NumElements should be power of 2 between 1 and 16.
3969 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3970 return true;
3971 return Size != 64 && (Size != 128 || NumElements == 1);
3972 }
3973 return false;
3974}
3975
Reid Klecknere9f6a712014-10-31 17:10:41 +00003976bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3977 // Homogeneous aggregates for AAPCS64 must have base types of a floating
3978 // point type or a short-vector type. This is the same as the 32-bit ABI,
3979 // but with the difference that any floating-point type is allowed,
3980 // including __fp16.
3981 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3982 if (BT->isFloatingPoint())
3983 return true;
3984 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3985 unsigned VecSize = getContext().getTypeSize(VT);
3986 if (VecSize == 64 || VecSize == 128)
3987 return true;
3988 }
3989 return false;
3990}
3991
3992bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
3993 uint64_t Members) const {
3994 return Members <= 4;
3995}
3996
3997llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3998 CodeGenFunction &CGF) const {
3999 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
4000 bool IsHA = false, IsSmallAggr = false;
4001 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
4002 IsSmallAggr, false /*IsNamedArg*/);
4003 bool IsIndirect = AI.isIndirect();
4004
Tim Northovera2ee4332014-03-29 15:09:45 +00004005 // The AArch64 va_list type and handling is specified in the Procedure Call
4006 // Standard, section B.4:
4007 //
4008 // struct {
4009 // void *__stack;
4010 // void *__gr_top;
4011 // void *__vr_top;
4012 // int __gr_offs;
4013 // int __vr_offs;
4014 // };
4015
4016 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4017 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4018 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4019 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4020 auto &Ctx = CGF.getContext();
4021
Craig Topper8a13c412014-05-21 05:09:00 +00004022 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004023 int reg_top_index;
4024 int RegSize;
4025 if (AllocatedGPR) {
4026 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
4027 // 3 is the field number of __gr_offs
4028 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4029 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4030 reg_top_index = 1; // field number for __gr_top
4031 RegSize = 8 * AllocatedGPR;
4032 } else {
4033 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
4034 // 4 is the field number of __vr_offs.
4035 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4036 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4037 reg_top_index = 2; // field number for __vr_top
4038 RegSize = 16 * AllocatedVFP;
4039 }
4040
4041 //=======================================
4042 // Find out where argument was passed
4043 //=======================================
4044
4045 // If reg_offs >= 0 we're already using the stack for this type of
4046 // argument. We don't want to keep updating reg_offs (in case it overflows,
4047 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4048 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004049 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004050 UsingStack = CGF.Builder.CreateICmpSGE(
4051 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4052
4053 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4054
4055 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004056 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004057 CGF.EmitBlock(MaybeRegBlock);
4058
4059 // Integer arguments may need to correct register alignment (for example a
4060 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4061 // align __gr_offs to calculate the potential address.
4062 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4063 int Align = Ctx.getTypeAlign(Ty) / 8;
4064
4065 reg_offs = CGF.Builder.CreateAdd(
4066 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4067 "align_regoffs");
4068 reg_offs = CGF.Builder.CreateAnd(
4069 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4070 "aligned_regoffs");
4071 }
4072
4073 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004074 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004075 NewOffset = CGF.Builder.CreateAdd(
4076 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4077 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4078
4079 // Now we're in a position to decide whether this argument really was in
4080 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004081 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004082 InRegs = CGF.Builder.CreateICmpSLE(
4083 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4084
4085 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4086
4087 //=======================================
4088 // Argument was in registers
4089 //=======================================
4090
4091 // Now we emit the code for if the argument was originally passed in
4092 // registers. First start the appropriate block:
4093 CGF.EmitBlock(InRegBlock);
4094
Craig Topper8a13c412014-05-21 05:09:00 +00004095 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004096 reg_top_p =
4097 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4098 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4099 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004100 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004101 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4102
4103 if (IsIndirect) {
4104 // If it's been passed indirectly (actually a struct), whatever we find from
4105 // stored registers or on the stack will actually be a struct **.
4106 MemTy = llvm::PointerType::getUnqual(MemTy);
4107 }
4108
Craig Topper8a13c412014-05-21 05:09:00 +00004109 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004110 uint64_t NumMembers = 0;
4111 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004112 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004113 // Homogeneous aggregates passed in registers will have their elements split
4114 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4115 // qN+1, ...). We reload and store into a temporary local variable
4116 // contiguously.
4117 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4118 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4119 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4120 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4121 int Offset = 0;
4122
4123 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4124 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4125 for (unsigned i = 0; i < NumMembers; ++i) {
4126 llvm::Value *BaseOffset =
4127 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4128 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4129 LoadAddr = CGF.Builder.CreateBitCast(
4130 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
4131 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4132
4133 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4134 CGF.Builder.CreateStore(Elem, StoreAddr);
4135 }
4136
4137 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4138 } else {
4139 // Otherwise the object is contiguous in memory
4140 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004141 if (CGF.CGM.getDataLayout().isBigEndian() &&
4142 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004143 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4144 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4145 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4146
4147 BaseAddr = CGF.Builder.CreateAdd(
4148 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4149
4150 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4151 }
4152
4153 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4154 }
4155
4156 CGF.EmitBranch(ContBlock);
4157
4158 //=======================================
4159 // Argument was on the stack
4160 //=======================================
4161 CGF.EmitBlock(OnStackBlock);
4162
Craig Topper8a13c412014-05-21 05:09:00 +00004163 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004164 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4165 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4166
4167 // Again, stack arguments may need realigmnent. In this case both integer and
4168 // floating-point ones might be affected.
4169 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4170 int Align = Ctx.getTypeAlign(Ty) / 8;
4171
4172 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4173
4174 OnStackAddr = CGF.Builder.CreateAdd(
4175 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4176 "align_stack");
4177 OnStackAddr = CGF.Builder.CreateAnd(
4178 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4179 "align_stack");
4180
4181 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4182 }
4183
4184 uint64_t StackSize;
4185 if (IsIndirect)
4186 StackSize = 8;
4187 else
4188 StackSize = Ctx.getTypeSize(Ty) / 8;
4189
4190 // All stack slots are 8 bytes
4191 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4192
4193 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4194 llvm::Value *NewStack =
4195 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4196
4197 // Write the new value of __stack for the next call to va_arg
4198 CGF.Builder.CreateStore(NewStack, stack_p);
4199
4200 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4201 Ctx.getTypeSize(Ty) < 64) {
4202 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4203 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4204
4205 OnStackAddr = CGF.Builder.CreateAdd(
4206 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4207
4208 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4209 }
4210
4211 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4212
4213 CGF.EmitBranch(ContBlock);
4214
4215 //=======================================
4216 // Tidy up
4217 //=======================================
4218 CGF.EmitBlock(ContBlock);
4219
4220 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4221 ResAddr->addIncoming(RegAddr, InRegBlock);
4222 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4223
4224 if (IsIndirect)
4225 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4226
4227 return ResAddr;
4228}
4229
Tim Northover573cbee2014-05-24 12:52:07 +00004230llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004231 CodeGenFunction &CGF) const {
4232 // We do not support va_arg for aggregates or illegal vector types.
4233 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4234 // other cases.
4235 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004236 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004237
4238 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4239 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4240
Craig Topper8a13c412014-05-21 05:09:00 +00004241 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004242 uint64_t Members = 0;
4243 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004244
4245 bool isIndirect = false;
4246 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4247 // be passed indirectly.
4248 if (Size > 16 && !isHA) {
4249 isIndirect = true;
4250 Size = 8;
4251 Align = 8;
4252 }
4253
4254 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4255 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4256
4257 CGBuilderTy &Builder = CGF.Builder;
4258 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4259 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4260
4261 if (isEmptyRecord(getContext(), Ty, true)) {
4262 // These are ignored for parameter passing purposes.
4263 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4264 return Builder.CreateBitCast(Addr, PTy);
4265 }
4266
4267 const uint64_t MinABIAlign = 8;
4268 if (Align > MinABIAlign) {
4269 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4270 Addr = Builder.CreateGEP(Addr, Offset);
4271 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4272 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4273 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4274 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4275 }
4276
4277 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4278 llvm::Value *NextAddr = Builder.CreateGEP(
4279 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4280 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4281
4282 if (isIndirect)
4283 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4284 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4285 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4286
4287 return AddrTyped;
4288}
4289
4290//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004291// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004292//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004293
4294namespace {
4295
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004296class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004297public:
4298 enum ABIKind {
4299 APCS = 0,
4300 AAPCS = 1,
4301 AAPCS_VFP
4302 };
4303
4304private:
4305 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00004306 mutable int VFPRegs[16];
4307 const unsigned NumVFPs;
4308 const unsigned NumGPRs;
4309 mutable unsigned AllocatedGPRs;
4310 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004311
4312public:
Oliver Stannard405bded2014-02-11 09:25:50 +00004313 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4314 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00004315 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004316 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00004317 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004318
John McCall3480ef22011-08-30 01:42:09 +00004319 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004320 switch (getTarget().getTriple().getEnvironment()) {
4321 case llvm::Triple::Android:
4322 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004323 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004324 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004325 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004326 return true;
4327 default:
4328 return false;
4329 }
John McCall3480ef22011-08-30 01:42:09 +00004330 }
4331
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004332 bool isEABIHF() const {
4333 switch (getTarget().getTriple().getEnvironment()) {
4334 case llvm::Triple::EABIHF:
4335 case llvm::Triple::GNUEABIHF:
4336 return true;
4337 default:
4338 return false;
4339 }
4340 }
4341
Daniel Dunbar020daa92009-09-12 01:00:39 +00004342 ABIKind getABIKind() const { return Kind; }
4343
Tim Northovera484bc02013-10-01 14:34:25 +00004344private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004345 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00004346 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004347 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00004348 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004349
Reid Klecknere9f6a712014-10-31 17:10:41 +00004350 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4351 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4352 uint64_t Members) const override;
4353
Craig Topper4f12f102014-03-12 06:41:41 +00004354 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004355
Craig Topper4f12f102014-03-12 06:41:41 +00004356 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4357 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004358
4359 llvm::CallingConv::ID getLLVMDefaultCC() const;
4360 llvm::CallingConv::ID getABIDefaultCC() const;
4361 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004362
4363 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4364 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4365 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004366};
4367
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004368class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4369public:
Chris Lattner2b037972010-07-29 02:01:43 +00004370 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4371 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004372
John McCall3480ef22011-08-30 01:42:09 +00004373 const ARMABIInfo &getABIInfo() const {
4374 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4375 }
4376
Craig Topper4f12f102014-03-12 06:41:41 +00004377 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004378 return 13;
4379 }
Roman Divackyc1617352011-05-18 19:36:54 +00004380
Craig Topper4f12f102014-03-12 06:41:41 +00004381 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004382 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4383 }
4384
Roman Divackyc1617352011-05-18 19:36:54 +00004385 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004386 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004387 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004388
4389 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004390 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004391 return false;
4392 }
John McCall3480ef22011-08-30 01:42:09 +00004393
Craig Topper4f12f102014-03-12 06:41:41 +00004394 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004395 if (getABIInfo().isEABI()) return 88;
4396 return TargetCodeGenInfo::getSizeOfUnwindException();
4397 }
Tim Northovera484bc02013-10-01 14:34:25 +00004398
4399 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004400 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004401 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4402 if (!FD)
4403 return;
4404
4405 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4406 if (!Attr)
4407 return;
4408
4409 const char *Kind;
4410 switch (Attr->getInterrupt()) {
4411 case ARMInterruptAttr::Generic: Kind = ""; break;
4412 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4413 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4414 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4415 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4416 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4417 }
4418
4419 llvm::Function *Fn = cast<llvm::Function>(GV);
4420
4421 Fn->addFnAttr("interrupt", Kind);
4422
4423 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4424 return;
4425
4426 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4427 // however this is not necessarily true on taking any interrupt. Instruct
4428 // the backend to perform a realignment as part of the function prologue.
4429 llvm::AttrBuilder B;
4430 B.addStackAlignmentAttr(8);
4431 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4432 llvm::AttributeSet::get(CGM.getLLVMContext(),
4433 llvm::AttributeSet::FunctionIndex,
4434 B));
4435 }
4436
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004437};
4438
Daniel Dunbard59655c2009-09-12 00:59:49 +00004439}
4440
Chris Lattner22326a12010-07-29 02:31:05 +00004441void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004442 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00004443 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00004444 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4445 // VFP registers of the appropriate type unallocated then the argument is
4446 // allocated to the lowest-numbered sequence of such registers.
4447 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4448 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00004449 resetAllocatedRegs();
4450
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004451 const bool isAAPCS_VFP =
4452 getABIKind() == ARMABIInfo::AAPCS_VFP && !FI.isVariadic();
4453
Reid Kleckner40ca9132014-05-13 22:05:45 +00004454 if (getCXXABI().classifyReturnType(FI)) {
4455 if (FI.getReturnInfo().isIndirect())
4456 markAllocatedGPRs(1, 1);
4457 } else {
4458 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4459 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004460 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004461 unsigned PreAllocationVFPs = AllocatedVFPs;
4462 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00004463 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00004464 // 6.1.2.3 There is one VFP co-processor register class using registers
4465 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00004466 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00004467
4468 // If we have allocated some arguments onto the stack (due to running
4469 // out of VFP registers), we cannot split an argument between GPRs and
4470 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00004471 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00004472 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4473 // unusable anyway.
Oliver Stannarde0228512014-07-18 09:09:31 +00004474 // We do not have to do this if the argument is being passed ByVal, as the
4475 // backend can handle that situation correctly.
Oliver Stannard405bded2014-02-11 09:25:50 +00004476 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Oliver Stannarde0228512014-07-18 09:09:31 +00004477 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4478 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4479 StackUsed && !IsByVal) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004480 llvm::Type *PaddingTy = llvm::ArrayType::get(
4481 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004482 if (I.info.canHaveCoerceToType()) {
4483 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004484 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004485 } else {
4486 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004487 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004488 }
Manman Ren2a523d82012-10-30 23:21:41 +00004489 }
4490 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004491
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004492 // Always honor user-specified calling convention.
4493 if (FI.getCallingConvention() != llvm::CallingConv::C)
4494 return;
4495
John McCall882987f2013-02-28 19:01:20 +00004496 llvm::CallingConv::ID cc = getRuntimeCC();
4497 if (cc != llvm::CallingConv::C)
4498 FI.setEffectiveCallingConvention(cc);
4499}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004500
John McCall882987f2013-02-28 19:01:20 +00004501/// Return the default calling convention that LLVM will use.
4502llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4503 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004504 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004505 return llvm::CallingConv::ARM_AAPCS_VFP;
4506 else if (isEABI())
4507 return llvm::CallingConv::ARM_AAPCS;
4508 else
4509 return llvm::CallingConv::ARM_APCS;
4510}
4511
4512/// Return the calling convention that our ABI would like us to use
4513/// as the C calling convention.
4514llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004515 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004516 case APCS: return llvm::CallingConv::ARM_APCS;
4517 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4518 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004519 }
John McCall882987f2013-02-28 19:01:20 +00004520 llvm_unreachable("bad ABI kind");
4521}
4522
4523void ARMABIInfo::setRuntimeCC() {
4524 assert(getRuntimeCC() == llvm::CallingConv::C);
4525
4526 // Don't muddy up the IR with a ton of explicit annotations if
4527 // they'd just match what LLVM will infer from the triple.
4528 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4529 if (abiCC != getLLVMDefaultCC())
4530 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004531}
4532
Manman Renb505d332012-10-31 19:02:26 +00004533/// markAllocatedVFPs - update VFPRegs according to the alignment and
4534/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004535void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4536 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004537 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004538 if (AllocatedVFPs >= 16) {
4539 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4540 // the stack.
4541 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004542 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004543 }
Manman Renb505d332012-10-31 19:02:26 +00004544 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4545 // VFP registers of the appropriate type unallocated then the argument is
4546 // allocated to the lowest-numbered sequence of such registers.
4547 for (unsigned I = 0; I < 16; I += Alignment) {
4548 bool FoundSlot = true;
4549 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4550 if (J >= 16 || VFPRegs[J]) {
4551 FoundSlot = false;
4552 break;
4553 }
4554 if (FoundSlot) {
4555 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4556 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004557 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004558 return;
4559 }
4560 }
4561 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4562 // unallocated are marked as unavailable.
4563 for (unsigned I = 0; I < 16; I++)
4564 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004565 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004566}
4567
Oliver Stannard405bded2014-02-11 09:25:50 +00004568/// Update AllocatedGPRs to record the number of general purpose registers
4569/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4570/// this represents arguments being stored on the stack.
4571void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004572 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004573 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4574
4575 if (Alignment == 2 && AllocatedGPRs & 0x1)
4576 AllocatedGPRs += 1;
4577
4578 AllocatedGPRs += NumRequired;
4579}
4580
4581void ARMABIInfo::resetAllocatedRegs(void) const {
4582 AllocatedGPRs = 0;
4583 AllocatedVFPs = 0;
4584 for (unsigned i = 0; i < NumVFPs; ++i)
4585 VFPRegs[i] = 0;
4586}
4587
James Molloy6f244b62014-05-09 16:21:39 +00004588ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004589 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004590 // We update number of allocated VFPs according to
4591 // 6.1.2.1 The following argument types are VFP CPRCs:
4592 // A single-precision floating-point type (including promoted
4593 // half-precision types); A double-precision floating-point type;
4594 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4595 // with a Base Type of a single- or double-precision floating-point type,
4596 // 64-bit containerized vectors or 128-bit containerized vectors with one
4597 // to four Elements.
4598
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004599 const bool isAAPCS_VFP =
4600 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4601
Manman Renfef9e312012-10-16 19:18:39 +00004602 // Handle illegal vector types here.
4603 if (isIllegalVectorType(Ty)) {
4604 uint64_t Size = getContext().getTypeSize(Ty);
4605 if (Size <= 32) {
4606 llvm::Type *ResType =
4607 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004608 markAllocatedGPRs(1, 1);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004609 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004610 }
4611 if (Size == 64) {
4612 llvm::Type *ResType = llvm::VectorType::get(
4613 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004614 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4615 markAllocatedGPRs(2, 2);
4616 } else {
4617 markAllocatedVFPs(2, 2);
4618 IsCPRC = true;
4619 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004620 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004621 }
4622 if (Size == 128) {
4623 llvm::Type *ResType = llvm::VectorType::get(
4624 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004625 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4626 markAllocatedGPRs(2, 4);
4627 } else {
4628 markAllocatedVFPs(4, 4);
4629 IsCPRC = true;
4630 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004631 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004632 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004633 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004634 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4635 }
Manman Renb505d332012-10-31 19:02:26 +00004636 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004637 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4638 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4639 uint64_t Size = getContext().getTypeSize(VT);
4640 // Size of a legal vector should be power of 2 and above 64.
4641 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4642 IsCPRC = true;
4643 }
Manman Ren2a523d82012-10-30 23:21:41 +00004644 }
Manman Renb505d332012-10-31 19:02:26 +00004645 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004646 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4647 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4648 if (BT->getKind() == BuiltinType::Half ||
4649 BT->getKind() == BuiltinType::Float) {
4650 markAllocatedVFPs(1, 1);
4651 IsCPRC = true;
4652 }
4653 if (BT->getKind() == BuiltinType::Double ||
4654 BT->getKind() == BuiltinType::LongDouble) {
4655 markAllocatedVFPs(2, 2);
4656 IsCPRC = true;
4657 }
4658 }
Manman Ren2a523d82012-10-30 23:21:41 +00004659 }
Manman Renfef9e312012-10-16 19:18:39 +00004660
John McCalla1dee5302010-08-22 10:59:02 +00004661 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004662 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004663 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004664 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004665 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004666
Oliver Stannard405bded2014-02-11 09:25:50 +00004667 unsigned Size = getContext().getTypeSize(Ty);
4668 if (!IsCPRC)
4669 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004670 return (Ty->isPromotableIntegerType()
4671 ? ABIArgInfo::getExtend()
4672 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004673 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004674
Oliver Stannard405bded2014-02-11 09:25:50 +00004675 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4676 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004677 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004678 }
Tim Northover1060eae2013-06-21 22:49:34 +00004679
Daniel Dunbar09d33622009-09-14 21:54:03 +00004680 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004681 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004682 return ABIArgInfo::getIgnore();
4683
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004684 if (isAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004685 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4686 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004687 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004688 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004689 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004690 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004691 // Base can be a floating-point or a vector.
4692 if (Base->isVectorType()) {
4693 // ElementSize is in number of floats.
4694 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004695 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004696 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004697 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004698 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004699 else {
4700 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4701 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004702 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004703 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004704 IsCPRC = true;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004705 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004706 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004707 }
4708
Manman Ren6c30e132012-08-13 21:23:55 +00004709 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004710 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4711 // most 8-byte. We realign the indirect argument if type alignment is bigger
4712 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004713 uint64_t ABIAlign = 4;
4714 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4715 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4716 getABIKind() == ARMABIInfo::AAPCS)
4717 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004718 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004719 // Update Allocated GPRs. Since this is only used when the size of the
4720 // argument is greater than 64 bytes, this will always use up any available
4721 // registers (of which there are 4). We also don't care about getting the
4722 // alignment right, because general-purpose registers cannot be back-filled.
4723 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004724 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004725 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004726 }
4727
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004728 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004729 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004730 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004731 // FIXME: Try to match the types of the arguments more accurately where
4732 // we can.
4733 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004734 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4735 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004736 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004737 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004738 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4739 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004740 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004741 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004742
Chris Lattnera5f58b02011-07-09 17:41:47 +00004743 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00004744 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004745 return ABIArgInfo::getDirect(STy, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004746}
4747
Chris Lattner458b2aa2010-07-29 02:16:43 +00004748static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004749 llvm::LLVMContext &VMContext) {
4750 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4751 // is called integer-like if its size is less than or equal to one word, and
4752 // the offset of each of its addressable sub-fields is zero.
4753
4754 uint64_t Size = Context.getTypeSize(Ty);
4755
4756 // Check that the type fits in a word.
4757 if (Size > 32)
4758 return false;
4759
4760 // FIXME: Handle vector types!
4761 if (Ty->isVectorType())
4762 return false;
4763
Daniel Dunbard53bac72009-09-14 02:20:34 +00004764 // Float types are never treated as "integer like".
4765 if (Ty->isRealFloatingType())
4766 return false;
4767
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004768 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004769 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004770 return true;
4771
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004772 // Small complex integer types are "integer like".
4773 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4774 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004775
4776 // Single element and zero sized arrays should be allowed, by the definition
4777 // above, but they are not.
4778
4779 // Otherwise, it must be a record type.
4780 const RecordType *RT = Ty->getAs<RecordType>();
4781 if (!RT) return false;
4782
4783 // Ignore records with flexible arrays.
4784 const RecordDecl *RD = RT->getDecl();
4785 if (RD->hasFlexibleArrayMember())
4786 return false;
4787
4788 // Check that all sub-fields are at offset 0, and are themselves "integer
4789 // like".
4790 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4791
4792 bool HadField = false;
4793 unsigned idx = 0;
4794 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4795 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004796 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004797
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004798 // Bit-fields are not addressable, we only need to verify they are "integer
4799 // like". We still have to disallow a subsequent non-bitfield, for example:
4800 // struct { int : 0; int x }
4801 // is non-integer like according to gcc.
4802 if (FD->isBitField()) {
4803 if (!RD->isUnion())
4804 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004805
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004806 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4807 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004808
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004809 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004810 }
4811
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004812 // Check if this field is at offset 0.
4813 if (Layout.getFieldOffset(idx) != 0)
4814 return false;
4815
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004816 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4817 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004818
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004819 // Only allow at most one field in a structure. This doesn't match the
4820 // wording above, but follows gcc in situations with a field following an
4821 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004822 if (!RD->isUnion()) {
4823 if (HadField)
4824 return false;
4825
4826 HadField = true;
4827 }
4828 }
4829
4830 return true;
4831}
4832
Oliver Stannard405bded2014-02-11 09:25:50 +00004833ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4834 bool isVariadic) const {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004835 const bool isAAPCS_VFP =
4836 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4837
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004838 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004839 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004840
Daniel Dunbar19964db2010-09-23 01:54:32 +00004841 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004842 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4843 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004844 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004845 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004846
John McCalla1dee5302010-08-22 10:59:02 +00004847 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004848 // Treat an enum type as its underlying type.
4849 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4850 RetTy = EnumTy->getDecl()->getIntegerType();
4851
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004852 return (RetTy->isPromotableIntegerType()
4853 ? ABIArgInfo::getExtend()
4854 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004855 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004856
4857 // Are we following APCS?
4858 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004859 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004860 return ABIArgInfo::getIgnore();
4861
Daniel Dunbareedf1512010-02-01 23:31:19 +00004862 // Complex types are all returned as packed integers.
4863 //
4864 // FIXME: Consider using 2 x vector types if the back end handles them
4865 // correctly.
4866 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004867 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4868 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004869
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004870 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004871 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004872 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004873 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004874 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004875 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004876 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004877 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4878 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004879 }
4880
4881 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004882 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004883 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004884 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004885
4886 // Otherwise this is an AAPCS variant.
4887
Chris Lattner458b2aa2010-07-29 02:16:43 +00004888 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004889 return ABIArgInfo::getIgnore();
4890
Bob Wilson1d9269a2011-11-02 04:51:36 +00004891 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00004892 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Craig Topper8a13c412014-05-21 05:09:00 +00004893 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004894 uint64_t Members;
4895 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004896 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004897 // Homogeneous Aggregates are returned directly.
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004898 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004899 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004900 }
4901
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004902 // Aggregates <= 4 bytes are returned in r0; other aggregates
4903 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004904 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004905 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004906 if (getDataLayout().isBigEndian())
4907 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004908 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4909 nullptr, !isAAPCS_VFP);
Christian Pirkerc3d32172014-07-03 09:28:12 +00004910
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004911 // Return in the smallest viable integer type.
4912 if (Size <= 8)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004913 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()), 0,
4914 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004915 if (Size <= 16)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004916 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()), 0,
4917 nullptr, !isAAPCS_VFP);
4918 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4919 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004920 }
4921
Oliver Stannard405bded2014-02-11 09:25:50 +00004922 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004923 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004924}
4925
Manman Renfef9e312012-10-16 19:18:39 +00004926/// isIllegalVector - check whether Ty is an illegal vector type.
4927bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4928 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4929 // Check whether VT is legal.
4930 unsigned NumElements = VT->getNumElements();
4931 uint64_t Size = getContext().getTypeSize(VT);
4932 // NumElements should be power of 2.
4933 if ((NumElements & (NumElements - 1)) != 0)
4934 return true;
4935 // Size should be greater than 32 bits.
4936 return Size <= 32;
4937 }
4938 return false;
4939}
4940
Reid Klecknere9f6a712014-10-31 17:10:41 +00004941bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4942 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4943 // double, or 64-bit or 128-bit vectors.
4944 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4945 if (BT->getKind() == BuiltinType::Float ||
4946 BT->getKind() == BuiltinType::Double ||
4947 BT->getKind() == BuiltinType::LongDouble)
4948 return true;
4949 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4950 unsigned VecSize = getContext().getTypeSize(VT);
4951 if (VecSize == 64 || VecSize == 128)
4952 return true;
4953 }
4954 return false;
4955}
4956
4957bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4958 uint64_t Members) const {
4959 return Members <= 4;
4960}
4961
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004962llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004963 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004964 llvm::Type *BP = CGF.Int8PtrTy;
4965 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004966
4967 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004968 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004969 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004970
Tim Northover1711cc92013-06-21 23:05:33 +00004971 if (isEmptyRecord(getContext(), Ty, true)) {
4972 // These are ignored for parameter passing purposes.
4973 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4974 return Builder.CreateBitCast(Addr, PTy);
4975 }
4976
Manman Rencca54d02012-10-16 19:01:37 +00004977 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004978 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004979 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004980
4981 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4982 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004983 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4984 getABIKind() == ARMABIInfo::AAPCS)
4985 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4986 else
4987 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004988 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4989 if (isIllegalVectorType(Ty) && Size > 16) {
4990 IsIndirect = true;
4991 Size = 4;
4992 TyAlign = 4;
4993 }
Manman Rencca54d02012-10-16 19:01:37 +00004994
4995 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004996 if (TyAlign > 4) {
4997 assert((TyAlign & (TyAlign - 1)) == 0 &&
4998 "Alignment is not power of 2!");
4999 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
5000 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
5001 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00005002 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00005003 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005004
5005 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00005006 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005007 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00005008 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005009 "ap.next");
5010 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5011
Manman Renfef9e312012-10-16 19:18:39 +00005012 if (IsIndirect)
5013 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00005014 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00005015 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5016 // may not be correctly aligned for the vector type. We create an aligned
5017 // temporary space and copy the content over from ap.cur to the temporary
5018 // space. This is necessary if the natural alignment of the type is greater
5019 // than the ABI alignment.
5020 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5021 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5022 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5023 "var.align");
5024 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5025 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5026 Builder.CreateMemCpy(Dst, Src,
5027 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5028 TyAlign, false);
5029 Addr = AlignedTemp; //The content is in aligned location.
5030 }
5031 llvm::Type *PTy =
5032 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5033 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5034
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005035 return AddrTyped;
5036}
5037
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00005038namespace {
5039
Derek Schuffa2020962012-10-16 22:30:41 +00005040class NaClARMABIInfo : public ABIInfo {
5041 public:
5042 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5043 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005044 void computeInfo(CGFunctionInfo &FI) const override;
5045 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5046 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00005047 private:
5048 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
5049 ARMABIInfo NInfo; // Used for everything else.
5050};
5051
5052class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
5053 public:
5054 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5055 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
5056};
5057
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00005058}
5059
Derek Schuffa2020962012-10-16 22:30:41 +00005060void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5061 if (FI.getASTCallingConvention() == CC_PnaclCall)
5062 PInfo.computeInfo(FI);
5063 else
5064 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
5065}
5066
5067llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5068 CodeGenFunction &CGF) const {
5069 // Always use the native convention; calling pnacl-style varargs functions
5070 // is unsupported.
5071 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
5072}
5073
Chris Lattner0cf24192010-06-28 20:05:43 +00005074//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005075// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005076//===----------------------------------------------------------------------===//
5077
5078namespace {
5079
Justin Holewinski83e96682012-05-24 17:43:12 +00005080class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005081public:
Justin Holewinski36837432013-03-30 14:38:24 +00005082 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005083
5084 ABIArgInfo classifyReturnType(QualType RetTy) const;
5085 ABIArgInfo classifyArgumentType(QualType Ty) const;
5086
Craig Topper4f12f102014-03-12 06:41:41 +00005087 void computeInfo(CGFunctionInfo &FI) const override;
5088 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5089 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005090};
5091
Justin Holewinski83e96682012-05-24 17:43:12 +00005092class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005093public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005094 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5095 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005096
5097 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5098 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005099private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005100 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5101 // resulting MDNode to the nvvm.annotations MDNode.
5102 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005103};
5104
Justin Holewinski83e96682012-05-24 17:43:12 +00005105ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005106 if (RetTy->isVoidType())
5107 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005108
5109 // note: this is different from default ABI
5110 if (!RetTy->isScalarType())
5111 return ABIArgInfo::getDirect();
5112
5113 // Treat an enum type as its underlying type.
5114 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5115 RetTy = EnumTy->getDecl()->getIntegerType();
5116
5117 return (RetTy->isPromotableIntegerType() ?
5118 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005119}
5120
Justin Holewinski83e96682012-05-24 17:43:12 +00005121ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005122 // Treat an enum type as its underlying type.
5123 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5124 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005125
Eli Bendersky95338a02014-10-29 13:43:21 +00005126 // Return aggregates type as indirect by value
5127 if (isAggregateTypeForABI(Ty))
5128 return ABIArgInfo::getIndirect(0, /* byval */ true);
5129
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005130 return (Ty->isPromotableIntegerType() ?
5131 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005132}
5133
Justin Holewinski83e96682012-05-24 17:43:12 +00005134void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005135 if (!getCXXABI().classifyReturnType(FI))
5136 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005137 for (auto &I : FI.arguments())
5138 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005139
5140 // Always honor user-specified calling convention.
5141 if (FI.getCallingConvention() != llvm::CallingConv::C)
5142 return;
5143
John McCall882987f2013-02-28 19:01:20 +00005144 FI.setEffectiveCallingConvention(getRuntimeCC());
5145}
5146
Justin Holewinski83e96682012-05-24 17:43:12 +00005147llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5148 CodeGenFunction &CFG) const {
5149 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005150}
5151
Justin Holewinski83e96682012-05-24 17:43:12 +00005152void NVPTXTargetCodeGenInfo::
5153SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5154 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005155 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5156 if (!FD) return;
5157
5158 llvm::Function *F = cast<llvm::Function>(GV);
5159
5160 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005161 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005162 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005163 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005164 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005165 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005166 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5167 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005168 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005169 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005170 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005171 }
Justin Holewinski38031972011-10-05 17:58:44 +00005172
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005173 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005174 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005175 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005176 // __global__ functions cannot be called from the device, we do not
5177 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005178 if (FD->hasAttr<CUDAGlobalAttr>()) {
5179 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5180 addNVVMMetadata(F, "kernel", 1);
5181 }
5182 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5183 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5184 addNVVMMetadata(F, "maxntidx",
5185 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5186 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5187 // zero value from getMinBlocks either means it was not specified in
5188 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5189 // don't have to add a PTX directive.
5190 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5191 if (MinCTASM > 0) {
5192 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5193 addNVVMMetadata(F, "minctasm", MinCTASM);
5194 }
5195 }
Justin Holewinski38031972011-10-05 17:58:44 +00005196 }
5197}
5198
Eli Benderskye06a2c42014-04-15 16:57:05 +00005199void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5200 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005201 llvm::Module *M = F->getParent();
5202 llvm::LLVMContext &Ctx = M->getContext();
5203
5204 // Get "nvvm.annotations" metadata node
5205 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5206
Eli Benderskye1627b42014-04-15 17:19:26 +00005207 llvm::Value *MDVals[] = {
5208 F, llvm::MDString::get(Ctx, Name),
5209 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinski36837432013-03-30 14:38:24 +00005210 // Append metadata to nvvm.annotations
5211 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5212}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005213}
5214
5215//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005216// SystemZ ABI Implementation
5217//===----------------------------------------------------------------------===//
5218
5219namespace {
5220
5221class SystemZABIInfo : public ABIInfo {
5222public:
5223 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5224
5225 bool isPromotableIntegerType(QualType Ty) const;
5226 bool isCompoundType(QualType Ty) const;
5227 bool isFPArgumentType(QualType Ty) const;
5228
5229 ABIArgInfo classifyReturnType(QualType RetTy) const;
5230 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5231
Craig Topper4f12f102014-03-12 06:41:41 +00005232 void computeInfo(CGFunctionInfo &FI) const override {
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);
Ulrich Weigand47445072013-05-06 16:26:41 +00005237 }
5238
Craig Topper4f12f102014-03-12 06:41:41 +00005239 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5240 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005241};
5242
5243class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5244public:
5245 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5246 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5247};
5248
5249}
5250
5251bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5252 // Treat an enum type as its underlying type.
5253 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5254 Ty = EnumTy->getDecl()->getIntegerType();
5255
5256 // Promotable integer types are required to be promoted by the ABI.
5257 if (Ty->isPromotableIntegerType())
5258 return true;
5259
5260 // 32-bit values must also be promoted.
5261 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5262 switch (BT->getKind()) {
5263 case BuiltinType::Int:
5264 case BuiltinType::UInt:
5265 return true;
5266 default:
5267 return false;
5268 }
5269 return false;
5270}
5271
5272bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5273 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5274}
5275
5276bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5277 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5278 switch (BT->getKind()) {
5279 case BuiltinType::Float:
5280 case BuiltinType::Double:
5281 return true;
5282 default:
5283 return false;
5284 }
5285
5286 if (const RecordType *RT = Ty->getAsStructureType()) {
5287 const RecordDecl *RD = RT->getDecl();
5288 bool Found = false;
5289
5290 // If this is a C++ record, check the bases first.
5291 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005292 for (const auto &I : CXXRD->bases()) {
5293 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005294
5295 // Empty bases don't affect things either way.
5296 if (isEmptyRecord(getContext(), Base, true))
5297 continue;
5298
5299 if (Found)
5300 return false;
5301 Found = isFPArgumentType(Base);
5302 if (!Found)
5303 return false;
5304 }
5305
5306 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005307 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005308 // Empty bitfields don't affect things either way.
5309 // Unlike isSingleElementStruct(), empty structure and array fields
5310 // do count. So do anonymous bitfields that aren't zero-sized.
5311 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5312 return true;
5313
5314 // Unlike isSingleElementStruct(), arrays do not count.
5315 // Nested isFPArgumentType structures still do though.
5316 if (Found)
5317 return false;
5318 Found = isFPArgumentType(FD->getType());
5319 if (!Found)
5320 return false;
5321 }
5322
5323 // Unlike isSingleElementStruct(), trailing padding is allowed.
5324 // An 8-byte aligned struct s { float f; } is passed as a double.
5325 return Found;
5326 }
5327
5328 return false;
5329}
5330
5331llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5332 CodeGenFunction &CGF) const {
5333 // Assume that va_list type is correct; should be pointer to LLVM type:
5334 // struct {
5335 // i64 __gpr;
5336 // i64 __fpr;
5337 // i8 *__overflow_arg_area;
5338 // i8 *__reg_save_area;
5339 // };
5340
5341 // Every argument occupies 8 bytes and is passed by preference in either
5342 // GPRs or FPRs.
5343 Ty = CGF.getContext().getCanonicalType(Ty);
5344 ABIArgInfo AI = classifyArgumentType(Ty);
5345 bool InFPRs = isFPArgumentType(Ty);
5346
5347 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5348 bool IsIndirect = AI.isIndirect();
5349 unsigned UnpaddedBitSize;
5350 if (IsIndirect) {
5351 APTy = llvm::PointerType::getUnqual(APTy);
5352 UnpaddedBitSize = 64;
5353 } else
5354 UnpaddedBitSize = getContext().getTypeSize(Ty);
5355 unsigned PaddedBitSize = 64;
5356 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5357
5358 unsigned PaddedSize = PaddedBitSize / 8;
5359 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5360
5361 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5362 if (InFPRs) {
5363 MaxRegs = 4; // Maximum of 4 FPR arguments
5364 RegCountField = 1; // __fpr
5365 RegSaveIndex = 16; // save offset for f0
5366 RegPadding = 0; // floats are passed in the high bits of an FPR
5367 } else {
5368 MaxRegs = 5; // Maximum of 5 GPR arguments
5369 RegCountField = 0; // __gpr
5370 RegSaveIndex = 2; // save offset for r2
5371 RegPadding = Padding; // values are passed in the low bits of a GPR
5372 }
5373
5374 llvm::Value *RegCountPtr =
5375 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5376 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5377 llvm::Type *IndexTy = RegCount->getType();
5378 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5379 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005380 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005381
5382 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5383 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5384 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5385 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5386
5387 // Emit code to load the value if it was passed in registers.
5388 CGF.EmitBlock(InRegBlock);
5389
5390 // Work out the address of an argument register.
5391 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5392 llvm::Value *ScaledRegCount =
5393 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5394 llvm::Value *RegBase =
5395 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5396 llvm::Value *RegOffset =
5397 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5398 llvm::Value *RegSaveAreaPtr =
5399 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5400 llvm::Value *RegSaveArea =
5401 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5402 llvm::Value *RawRegAddr =
5403 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5404 llvm::Value *RegAddr =
5405 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5406
5407 // Update the register count
5408 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5409 llvm::Value *NewRegCount =
5410 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5411 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5412 CGF.EmitBranch(ContBlock);
5413
5414 // Emit code to load the value if it was passed in memory.
5415 CGF.EmitBlock(InMemBlock);
5416
5417 // Work out the address of a stack argument.
5418 llvm::Value *OverflowArgAreaPtr =
5419 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5420 llvm::Value *OverflowArgArea =
5421 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5422 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5423 llvm::Value *RawMemAddr =
5424 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5425 llvm::Value *MemAddr =
5426 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5427
5428 // Update overflow_arg_area_ptr pointer
5429 llvm::Value *NewOverflowArgArea =
5430 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5431 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5432 CGF.EmitBranch(ContBlock);
5433
5434 // Return the appropriate result.
5435 CGF.EmitBlock(ContBlock);
5436 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5437 ResAddr->addIncoming(RegAddr, InRegBlock);
5438 ResAddr->addIncoming(MemAddr, InMemBlock);
5439
5440 if (IsIndirect)
5441 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5442
5443 return ResAddr;
5444}
5445
Ulrich Weigand47445072013-05-06 16:26:41 +00005446ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5447 if (RetTy->isVoidType())
5448 return ABIArgInfo::getIgnore();
5449 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5450 return ABIArgInfo::getIndirect(0);
5451 return (isPromotableIntegerType(RetTy) ?
5452 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5453}
5454
5455ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5456 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005457 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005458 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5459
5460 // Integers and enums are extended to full register width.
5461 if (isPromotableIntegerType(Ty))
5462 return ABIArgInfo::getExtend();
5463
5464 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5465 uint64_t Size = getContext().getTypeSize(Ty);
5466 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005467 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005468
5469 // Handle small structures.
5470 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5471 // Structures with flexible arrays have variable length, so really
5472 // fail the size test above.
5473 const RecordDecl *RD = RT->getDecl();
5474 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005475 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005476
5477 // The structure is passed as an unextended integer, a float, or a double.
5478 llvm::Type *PassTy;
5479 if (isFPArgumentType(Ty)) {
5480 assert(Size == 32 || Size == 64);
5481 if (Size == 32)
5482 PassTy = llvm::Type::getFloatTy(getVMContext());
5483 else
5484 PassTy = llvm::Type::getDoubleTy(getVMContext());
5485 } else
5486 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5487 return ABIArgInfo::getDirect(PassTy);
5488 }
5489
5490 // Non-structure compounds are passed indirectly.
5491 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005492 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005493
Craig Topper8a13c412014-05-21 05:09:00 +00005494 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005495}
5496
5497//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005498// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005499//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005500
5501namespace {
5502
5503class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5504public:
Chris Lattner2b037972010-07-29 02:01:43 +00005505 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5506 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005507 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005508 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005509};
5510
5511}
5512
5513void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5514 llvm::GlobalValue *GV,
5515 CodeGen::CodeGenModule &M) const {
5516 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5517 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5518 // Handle 'interrupt' attribute:
5519 llvm::Function *F = cast<llvm::Function>(GV);
5520
5521 // Step 1: Set ISR calling convention.
5522 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5523
5524 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005525 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005526
5527 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005528 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005529 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5530 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005531 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005532 }
5533}
5534
Chris Lattner0cf24192010-06-28 20:05:43 +00005535//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005536// MIPS ABI Implementation. This works for both little-endian and
5537// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005538//===----------------------------------------------------------------------===//
5539
John McCall943fae92010-05-27 06:19:26 +00005540namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005541class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005542 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005543 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5544 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005545 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005546 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005547 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005548 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005549public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005550 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005551 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005552 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005553
5554 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005555 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005556 void computeInfo(CGFunctionInfo &FI) const override;
5557 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5558 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005559};
5560
John McCall943fae92010-05-27 06:19:26 +00005561class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005562 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005563public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005564 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5565 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005566 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005567
Craig Topper4f12f102014-03-12 06:41:41 +00005568 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005569 return 29;
5570 }
5571
Reed Kotler373feca2013-01-16 17:10:28 +00005572 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005573 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005574 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5575 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005576 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005577 if (FD->hasAttr<Mips16Attr>()) {
5578 Fn->addFnAttr("mips16");
5579 }
5580 else if (FD->hasAttr<NoMips16Attr>()) {
5581 Fn->addFnAttr("nomips16");
5582 }
Reed Kotler373feca2013-01-16 17:10:28 +00005583 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005584
John McCall943fae92010-05-27 06:19:26 +00005585 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005586 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005587
Craig Topper4f12f102014-03-12 06:41:41 +00005588 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005589 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005590 }
John McCall943fae92010-05-27 06:19:26 +00005591};
5592}
5593
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005594void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005595 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005596 llvm::IntegerType *IntTy =
5597 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005598
5599 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5600 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5601 ArgList.push_back(IntTy);
5602
5603 // If necessary, add one more integer type to ArgList.
5604 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5605
5606 if (R)
5607 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005608}
5609
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005610// In N32/64, an aligned double precision floating point field is passed in
5611// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005612llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005613 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5614
5615 if (IsO32) {
5616 CoerceToIntArgs(TySize, ArgList);
5617 return llvm::StructType::get(getVMContext(), ArgList);
5618 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005619
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005620 if (Ty->isComplexType())
5621 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005622
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005623 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005624
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005625 // Unions/vectors are passed in integer registers.
5626 if (!RT || !RT->isStructureOrClassType()) {
5627 CoerceToIntArgs(TySize, ArgList);
5628 return llvm::StructType::get(getVMContext(), ArgList);
5629 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005630
5631 const RecordDecl *RD = RT->getDecl();
5632 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005633 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005634
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005635 uint64_t LastOffset = 0;
5636 unsigned idx = 0;
5637 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5638
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005639 // Iterate over fields in the struct/class and check if there are any aligned
5640 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005641 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5642 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005643 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005644 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5645
5646 if (!BT || BT->getKind() != BuiltinType::Double)
5647 continue;
5648
5649 uint64_t Offset = Layout.getFieldOffset(idx);
5650 if (Offset % 64) // Ignore doubles that are not aligned.
5651 continue;
5652
5653 // Add ((Offset - LastOffset) / 64) args of type i64.
5654 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5655 ArgList.push_back(I64);
5656
5657 // Add double type.
5658 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5659 LastOffset = Offset + 64;
5660 }
5661
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005662 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5663 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005664
5665 return llvm::StructType::get(getVMContext(), ArgList);
5666}
5667
Akira Hatanakaddd66342013-10-29 18:41:15 +00005668llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5669 uint64_t Offset) const {
5670 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005671 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005672
Akira Hatanakaddd66342013-10-29 18:41:15 +00005673 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005674}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005675
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005676ABIArgInfo
5677MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005678 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005679 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005680 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005681
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005682 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5683 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005684 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5685 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005686
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005687 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005688 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005689 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005690 return ABIArgInfo::getIgnore();
5691
Mark Lacey3825e832013-10-06 01:33:34 +00005692 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005693 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005694 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005695 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005696
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005697 // If we have reached here, aggregates are passed directly by coercing to
5698 // another structure type. Padding is inserted if the offset of the
5699 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005700 ABIArgInfo ArgInfo =
5701 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5702 getPaddingType(OrigOffset, CurrOffset));
5703 ArgInfo.setInReg(true);
5704 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005705 }
5706
5707 // Treat an enum type as its underlying type.
5708 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5709 Ty = EnumTy->getDecl()->getIntegerType();
5710
Daniel Sanders5b445b32014-10-24 14:42:42 +00005711 // All integral types are promoted to the GPR width.
5712 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005713 return ABIArgInfo::getExtend();
5714
Akira Hatanakaddd66342013-10-29 18:41:15 +00005715 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005716 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005717}
5718
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005719llvm::Type*
5720MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005721 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005722 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005723
Akira Hatanakab6f74432012-02-09 18:49:26 +00005724 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005725 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005726 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5727 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005728
Akira Hatanakab6f74432012-02-09 18:49:26 +00005729 // N32/64 returns struct/classes in floating point registers if the
5730 // following conditions are met:
5731 // 1. The size of the struct/class is no larger than 128-bit.
5732 // 2. The struct/class has one or two fields all of which are floating
5733 // point types.
5734 // 3. The offset of the first field is zero (this follows what gcc does).
5735 //
5736 // Any other composite results are returned in integer registers.
5737 //
5738 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5739 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5740 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005741 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005742
Akira Hatanakab6f74432012-02-09 18:49:26 +00005743 if (!BT || !BT->isFloatingPoint())
5744 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005745
David Blaikie2d7c57e2012-04-30 02:36:29 +00005746 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005747 }
5748
5749 if (b == e)
5750 return llvm::StructType::get(getVMContext(), RTList,
5751 RD->hasAttr<PackedAttr>());
5752
5753 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005754 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005755 }
5756
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005757 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005758 return llvm::StructType::get(getVMContext(), RTList);
5759}
5760
Akira Hatanakab579fe52011-06-02 00:09:17 +00005761ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005762 uint64_t Size = getContext().getTypeSize(RetTy);
5763
Daniel Sandersed39f582014-09-04 13:28:14 +00005764 if (RetTy->isVoidType())
5765 return ABIArgInfo::getIgnore();
5766
5767 // O32 doesn't treat zero-sized structs differently from other structs.
5768 // However, N32/N64 ignores zero sized return values.
5769 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005770 return ABIArgInfo::getIgnore();
5771
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005772 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005773 if (Size <= 128) {
5774 if (RetTy->isAnyComplexType())
5775 return ABIArgInfo::getDirect();
5776
Daniel Sanderse5018b62014-09-04 15:05:39 +00005777 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005778 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005779 if (!IsO32 ||
5780 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5781 ABIArgInfo ArgInfo =
5782 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5783 ArgInfo.setInReg(true);
5784 return ArgInfo;
5785 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005786 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005787
5788 return ABIArgInfo::getIndirect(0);
5789 }
5790
5791 // Treat an enum type as its underlying type.
5792 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5793 RetTy = EnumTy->getDecl()->getIntegerType();
5794
5795 return (RetTy->isPromotableIntegerType() ?
5796 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5797}
5798
5799void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005800 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005801 if (!getCXXABI().classifyReturnType(FI))
5802 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005803
5804 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005805 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005806
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005807 for (auto &I : FI.arguments())
5808 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005809}
5810
5811llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5812 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005813 llvm::Type *BP = CGF.Int8PtrTy;
5814 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5815
5816 CGBuilderTy &Builder = CGF.Builder;
5817 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5818 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005819 int64_t TypeAlign =
5820 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005821 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5822 llvm::Value *AddrTyped;
5823 unsigned PtrWidth = getTarget().getPointerWidth(0);
5824 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5825
5826 if (TypeAlign > MinABIStackAlignInBytes) {
5827 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5828 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5829 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5830 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5831 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5832 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5833 }
5834 else
5835 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5836
5837 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5838 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
5839 uint64_t Offset =
5840 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5841 llvm::Value *NextAddr =
5842 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5843 "ap.next");
5844 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5845
5846 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005847}
5848
John McCall943fae92010-05-27 06:19:26 +00005849bool
5850MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5851 llvm::Value *Address) const {
5852 // This information comes from gcc's implementation, which seems to
5853 // as canonical as it gets.
5854
John McCall943fae92010-05-27 06:19:26 +00005855 // Everything on MIPS is 4 bytes. Double-precision FP registers
5856 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005857 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005858
5859 // 0-31 are the general purpose registers, $0 - $31.
5860 // 32-63 are the floating-point registers, $f0 - $f31.
5861 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5862 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005863 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005864
5865 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5866 // They are one bit wide and ignored here.
5867
5868 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5869 // (coprocessor 1 is the FP unit)
5870 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5871 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5872 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005873 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005874 return false;
5875}
5876
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005877//===----------------------------------------------------------------------===//
5878// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5879// Currently subclassed only to implement custom OpenCL C function attribute
5880// handling.
5881//===----------------------------------------------------------------------===//
5882
5883namespace {
5884
5885class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5886public:
5887 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5888 : DefaultTargetCodeGenInfo(CGT) {}
5889
Craig Topper4f12f102014-03-12 06:41:41 +00005890 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5891 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005892};
5893
5894void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5895 llvm::GlobalValue *GV,
5896 CodeGen::CodeGenModule &M) const {
5897 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5898 if (!FD) return;
5899
5900 llvm::Function *F = cast<llvm::Function>(GV);
5901
David Blaikiebbafb8a2012-03-11 07:00:24 +00005902 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005903 if (FD->hasAttr<OpenCLKernelAttr>()) {
5904 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005905 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005906 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5907 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005908 // Convert the reqd_work_group_size() attributes to metadata.
5909 llvm::LLVMContext &Context = F->getContext();
5910 llvm::NamedMDNode *OpenCLMetadata =
5911 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5912
5913 SmallVector<llvm::Value*, 5> Operands;
5914 Operands.push_back(F);
5915
Chris Lattnerece04092012-02-07 00:39:47 +00005916 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005917 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005918 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005919 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005920 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005921 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005922
5923 // Add a boolean constant operand for "required" (true) or "hint" (false)
5924 // for implementing the work_group_size_hint attr later. Currently
5925 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005926 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005927 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5928 }
5929 }
5930 }
5931}
5932
5933}
John McCall943fae92010-05-27 06:19:26 +00005934
Tony Linthicum76329bf2011-12-12 21:14:55 +00005935//===----------------------------------------------------------------------===//
5936// Hexagon ABI Implementation
5937//===----------------------------------------------------------------------===//
5938
5939namespace {
5940
5941class HexagonABIInfo : public ABIInfo {
5942
5943
5944public:
5945 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5946
5947private:
5948
5949 ABIArgInfo classifyReturnType(QualType RetTy) const;
5950 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5951
Craig Topper4f12f102014-03-12 06:41:41 +00005952 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005953
Craig Topper4f12f102014-03-12 06:41:41 +00005954 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5955 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005956};
5957
5958class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5959public:
5960 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5961 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5962
Craig Topper4f12f102014-03-12 06:41:41 +00005963 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005964 return 29;
5965 }
5966};
5967
5968}
5969
5970void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005971 if (!getCXXABI().classifyReturnType(FI))
5972 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005973 for (auto &I : FI.arguments())
5974 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005975}
5976
5977ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5978 if (!isAggregateTypeForABI(Ty)) {
5979 // Treat an enum type as its underlying type.
5980 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5981 Ty = EnumTy->getDecl()->getIntegerType();
5982
5983 return (Ty->isPromotableIntegerType() ?
5984 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5985 }
5986
5987 // Ignore empty records.
5988 if (isEmptyRecord(getContext(), Ty, true))
5989 return ABIArgInfo::getIgnore();
5990
Mark Lacey3825e832013-10-06 01:33:34 +00005991 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005992 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005993
5994 uint64_t Size = getContext().getTypeSize(Ty);
5995 if (Size > 64)
5996 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5997 // Pass in the smallest viable integer type.
5998 else if (Size > 32)
5999 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6000 else if (Size > 16)
6001 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6002 else if (Size > 8)
6003 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6004 else
6005 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6006}
6007
6008ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6009 if (RetTy->isVoidType())
6010 return ABIArgInfo::getIgnore();
6011
6012 // Large vector types should be returned via memory.
6013 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6014 return ABIArgInfo::getIndirect(0);
6015
6016 if (!isAggregateTypeForABI(RetTy)) {
6017 // Treat an enum type as its underlying type.
6018 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6019 RetTy = EnumTy->getDecl()->getIntegerType();
6020
6021 return (RetTy->isPromotableIntegerType() ?
6022 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6023 }
6024
Tony Linthicum76329bf2011-12-12 21:14:55 +00006025 if (isEmptyRecord(getContext(), RetTy, true))
6026 return ABIArgInfo::getIgnore();
6027
6028 // Aggregates <= 8 bytes are returned in r0; other aggregates
6029 // are returned indirectly.
6030 uint64_t Size = getContext().getTypeSize(RetTy);
6031 if (Size <= 64) {
6032 // Return in the smallest viable integer type.
6033 if (Size <= 8)
6034 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6035 if (Size <= 16)
6036 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6037 if (Size <= 32)
6038 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6039 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6040 }
6041
6042 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6043}
6044
6045llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006046 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006047 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006048 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006049
6050 CGBuilderTy &Builder = CGF.Builder;
6051 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6052 "ap");
6053 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6054 llvm::Type *PTy =
6055 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6056 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6057
6058 uint64_t Offset =
6059 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6060 llvm::Value *NextAddr =
6061 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6062 "ap.next");
6063 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6064
6065 return AddrTyped;
6066}
6067
6068
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006069//===----------------------------------------------------------------------===//
6070// SPARC v9 ABI Implementation.
6071// Based on the SPARC Compliance Definition version 2.4.1.
6072//
6073// Function arguments a mapped to a nominal "parameter array" and promoted to
6074// registers depending on their type. Each argument occupies 8 or 16 bytes in
6075// the array, structs larger than 16 bytes are passed indirectly.
6076//
6077// One case requires special care:
6078//
6079// struct mixed {
6080// int i;
6081// float f;
6082// };
6083//
6084// When a struct mixed is passed by value, it only occupies 8 bytes in the
6085// parameter array, but the int is passed in an integer register, and the float
6086// is passed in a floating point register. This is represented as two arguments
6087// with the LLVM IR inreg attribute:
6088//
6089// declare void f(i32 inreg %i, float inreg %f)
6090//
6091// The code generator will only allocate 4 bytes from the parameter array for
6092// the inreg arguments. All other arguments are allocated a multiple of 8
6093// bytes.
6094//
6095namespace {
6096class SparcV9ABIInfo : public ABIInfo {
6097public:
6098 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6099
6100private:
6101 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006102 void computeInfo(CGFunctionInfo &FI) const override;
6103 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6104 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006105
6106 // Coercion type builder for structs passed in registers. The coercion type
6107 // serves two purposes:
6108 //
6109 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6110 // in registers.
6111 // 2. Expose aligned floating point elements as first-level elements, so the
6112 // code generator knows to pass them in floating point registers.
6113 //
6114 // We also compute the InReg flag which indicates that the struct contains
6115 // aligned 32-bit floats.
6116 //
6117 struct CoerceBuilder {
6118 llvm::LLVMContext &Context;
6119 const llvm::DataLayout &DL;
6120 SmallVector<llvm::Type*, 8> Elems;
6121 uint64_t Size;
6122 bool InReg;
6123
6124 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6125 : Context(c), DL(dl), Size(0), InReg(false) {}
6126
6127 // Pad Elems with integers until Size is ToSize.
6128 void pad(uint64_t ToSize) {
6129 assert(ToSize >= Size && "Cannot remove elements");
6130 if (ToSize == Size)
6131 return;
6132
6133 // Finish the current 64-bit word.
6134 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6135 if (Aligned > Size && Aligned <= ToSize) {
6136 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6137 Size = Aligned;
6138 }
6139
6140 // Add whole 64-bit words.
6141 while (Size + 64 <= ToSize) {
6142 Elems.push_back(llvm::Type::getInt64Ty(Context));
6143 Size += 64;
6144 }
6145
6146 // Final in-word padding.
6147 if (Size < ToSize) {
6148 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6149 Size = ToSize;
6150 }
6151 }
6152
6153 // Add a floating point element at Offset.
6154 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6155 // Unaligned floats are treated as integers.
6156 if (Offset % Bits)
6157 return;
6158 // The InReg flag is only required if there are any floats < 64 bits.
6159 if (Bits < 64)
6160 InReg = true;
6161 pad(Offset);
6162 Elems.push_back(Ty);
6163 Size = Offset + Bits;
6164 }
6165
6166 // Add a struct type to the coercion type, starting at Offset (in bits).
6167 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6168 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6169 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6170 llvm::Type *ElemTy = StrTy->getElementType(i);
6171 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6172 switch (ElemTy->getTypeID()) {
6173 case llvm::Type::StructTyID:
6174 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6175 break;
6176 case llvm::Type::FloatTyID:
6177 addFloat(ElemOffset, ElemTy, 32);
6178 break;
6179 case llvm::Type::DoubleTyID:
6180 addFloat(ElemOffset, ElemTy, 64);
6181 break;
6182 case llvm::Type::FP128TyID:
6183 addFloat(ElemOffset, ElemTy, 128);
6184 break;
6185 case llvm::Type::PointerTyID:
6186 if (ElemOffset % 64 == 0) {
6187 pad(ElemOffset);
6188 Elems.push_back(ElemTy);
6189 Size += 64;
6190 }
6191 break;
6192 default:
6193 break;
6194 }
6195 }
6196 }
6197
6198 // Check if Ty is a usable substitute for the coercion type.
6199 bool isUsableType(llvm::StructType *Ty) const {
6200 if (Ty->getNumElements() != Elems.size())
6201 return false;
6202 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6203 if (Elems[i] != Ty->getElementType(i))
6204 return false;
6205 return true;
6206 }
6207
6208 // Get the coercion type as a literal struct type.
6209 llvm::Type *getType() const {
6210 if (Elems.size() == 1)
6211 return Elems.front();
6212 else
6213 return llvm::StructType::get(Context, Elems);
6214 }
6215 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006216};
6217} // end anonymous namespace
6218
6219ABIArgInfo
6220SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6221 if (Ty->isVoidType())
6222 return ABIArgInfo::getIgnore();
6223
6224 uint64_t Size = getContext().getTypeSize(Ty);
6225
6226 // Anything too big to fit in registers is passed with an explicit indirect
6227 // pointer / sret pointer.
6228 if (Size > SizeLimit)
6229 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6230
6231 // Treat an enum type as its underlying type.
6232 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6233 Ty = EnumTy->getDecl()->getIntegerType();
6234
6235 // Integer types smaller than a register are extended.
6236 if (Size < 64 && Ty->isIntegerType())
6237 return ABIArgInfo::getExtend();
6238
6239 // Other non-aggregates go in registers.
6240 if (!isAggregateTypeForABI(Ty))
6241 return ABIArgInfo::getDirect();
6242
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006243 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6244 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6245 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6246 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6247
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006248 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006249 // Build a coercion type from the LLVM struct type.
6250 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6251 if (!StrTy)
6252 return ABIArgInfo::getDirect();
6253
6254 CoerceBuilder CB(getVMContext(), getDataLayout());
6255 CB.addStruct(0, StrTy);
6256 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6257
6258 // Try to use the original type for coercion.
6259 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6260
6261 if (CB.InReg)
6262 return ABIArgInfo::getDirectInReg(CoerceTy);
6263 else
6264 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006265}
6266
6267llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6268 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006269 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6270 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6271 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6272 AI.setCoerceToType(ArgTy);
6273
6274 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6275 CGBuilderTy &Builder = CGF.Builder;
6276 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6277 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6278 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6279 llvm::Value *ArgAddr;
6280 unsigned Stride;
6281
6282 switch (AI.getKind()) {
6283 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006284 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006285 llvm_unreachable("Unsupported ABI kind for va_arg");
6286
6287 case ABIArgInfo::Extend:
6288 Stride = 8;
6289 ArgAddr = Builder
6290 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6291 "extend");
6292 break;
6293
6294 case ABIArgInfo::Direct:
6295 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6296 ArgAddr = Addr;
6297 break;
6298
6299 case ABIArgInfo::Indirect:
6300 Stride = 8;
6301 ArgAddr = Builder.CreateBitCast(Addr,
6302 llvm::PointerType::getUnqual(ArgPtrTy),
6303 "indirect");
6304 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6305 break;
6306
6307 case ABIArgInfo::Ignore:
6308 return llvm::UndefValue::get(ArgPtrTy);
6309 }
6310
6311 // Update VAList.
6312 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6313 Builder.CreateStore(Addr, VAListAddrAsBPP);
6314
6315 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006316}
6317
6318void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6319 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006320 for (auto &I : FI.arguments())
6321 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006322}
6323
6324namespace {
6325class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6326public:
6327 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6328 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006329
Craig Topper4f12f102014-03-12 06:41:41 +00006330 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006331 return 14;
6332 }
6333
6334 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006335 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006336};
6337} // end anonymous namespace
6338
Roman Divackyf02c9942014-02-24 18:46:27 +00006339bool
6340SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6341 llvm::Value *Address) const {
6342 // This is calculated from the LLVM and GCC tables and verified
6343 // against gcc output. AFAIK all ABIs use the same encoding.
6344
6345 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6346
6347 llvm::IntegerType *i8 = CGF.Int8Ty;
6348 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6349 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6350
6351 // 0-31: the 8-byte general-purpose registers
6352 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6353
6354 // 32-63: f0-31, the 4-byte floating-point registers
6355 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6356
6357 // Y = 64
6358 // PSR = 65
6359 // WIM = 66
6360 // TBR = 67
6361 // PC = 68
6362 // NPC = 69
6363 // FSR = 70
6364 // CSR = 71
6365 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6366
6367 // 72-87: d0-15, the 8-byte floating-point registers
6368 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6369
6370 return false;
6371}
6372
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006373
Robert Lytton0e076492013-08-13 09:43:10 +00006374//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006375// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006376//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006377
Robert Lytton0e076492013-08-13 09:43:10 +00006378namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006379
6380/// A SmallStringEnc instance is used to build up the TypeString by passing
6381/// it by reference between functions that append to it.
6382typedef llvm::SmallString<128> SmallStringEnc;
6383
6384/// TypeStringCache caches the meta encodings of Types.
6385///
6386/// The reason for caching TypeStrings is two fold:
6387/// 1. To cache a type's encoding for later uses;
6388/// 2. As a means to break recursive member type inclusion.
6389///
6390/// A cache Entry can have a Status of:
6391/// NonRecursive: The type encoding is not recursive;
6392/// Recursive: The type encoding is recursive;
6393/// Incomplete: An incomplete TypeString;
6394/// IncompleteUsed: An incomplete TypeString that has been used in a
6395/// Recursive type encoding.
6396///
6397/// A NonRecursive entry will have all of its sub-members expanded as fully
6398/// as possible. Whilst it may contain types which are recursive, the type
6399/// itself is not recursive and thus its encoding may be safely used whenever
6400/// the type is encountered.
6401///
6402/// A Recursive entry will have all of its sub-members expanded as fully as
6403/// possible. The type itself is recursive and it may contain other types which
6404/// are recursive. The Recursive encoding must not be used during the expansion
6405/// of a recursive type's recursive branch. For simplicity the code uses
6406/// IncompleteCount to reject all usage of Recursive encodings for member types.
6407///
6408/// An Incomplete entry is always a RecordType and only encodes its
6409/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6410/// are placed into the cache during type expansion as a means to identify and
6411/// handle recursive inclusion of types as sub-members. If there is recursion
6412/// the entry becomes IncompleteUsed.
6413///
6414/// During the expansion of a RecordType's members:
6415///
6416/// If the cache contains a NonRecursive encoding for the member type, the
6417/// cached encoding is used;
6418///
6419/// If the cache contains a Recursive encoding for the member type, the
6420/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6421///
6422/// If the member is a RecordType, an Incomplete encoding is placed into the
6423/// cache to break potential recursive inclusion of itself as a sub-member;
6424///
6425/// Once a member RecordType has been expanded, its temporary incomplete
6426/// entry is removed from the cache. If a Recursive encoding was swapped out
6427/// it is swapped back in;
6428///
6429/// If an incomplete entry is used to expand a sub-member, the incomplete
6430/// entry is marked as IncompleteUsed. The cache keeps count of how many
6431/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6432///
6433/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6434/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6435/// Else the member is part of a recursive type and thus the recursion has
6436/// been exited too soon for the encoding to be correct for the member.
6437///
6438class TypeStringCache {
6439 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6440 struct Entry {
6441 std::string Str; // The encoded TypeString for the type.
6442 enum Status State; // Information about the encoding in 'Str'.
6443 std::string Swapped; // A temporary place holder for a Recursive encoding
6444 // during the expansion of RecordType's members.
6445 };
6446 std::map<const IdentifierInfo *, struct Entry> Map;
6447 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6448 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6449public:
Robert Lyttond263f142014-05-06 09:38:54 +00006450 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006451 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6452 bool removeIncomplete(const IdentifierInfo *ID);
6453 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6454 bool IsRecursive);
6455 StringRef lookupStr(const IdentifierInfo *ID);
6456};
6457
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006458/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006459/// FieldEncoding is a helper for this ordering process.
6460class FieldEncoding {
6461 bool HasName;
6462 std::string Enc;
6463public:
6464 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6465 StringRef str() {return Enc.c_str();};
6466 bool operator<(const FieldEncoding &rhs) const {
6467 if (HasName != rhs.HasName) return HasName;
6468 return Enc < rhs.Enc;
6469 }
6470};
6471
Robert Lytton7d1db152013-08-19 09:46:39 +00006472class XCoreABIInfo : public DefaultABIInfo {
6473public:
6474 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006475 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6476 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006477};
6478
Robert Lyttond21e2d72014-03-03 13:45:29 +00006479class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006480 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006481public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006482 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006483 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006484 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6485 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006486};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006487
Robert Lytton2d196952013-10-11 10:29:34 +00006488} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006489
Robert Lytton7d1db152013-08-19 09:46:39 +00006490llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6491 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006492 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006493
Robert Lytton2d196952013-10-11 10:29:34 +00006494 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006495 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6496 CGF.Int8PtrPtrTy);
6497 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006498
Robert Lytton2d196952013-10-11 10:29:34 +00006499 // Handle the argument.
6500 ABIArgInfo AI = classifyArgumentType(Ty);
6501 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6502 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6503 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006504 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006505 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006506 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006507 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006508 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006509 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006510 llvm_unreachable("Unsupported ABI kind for va_arg");
6511 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006512 Val = llvm::UndefValue::get(ArgPtrTy);
6513 ArgSize = 0;
6514 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006515 case ABIArgInfo::Extend:
6516 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006517 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6518 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6519 if (ArgSize < 4)
6520 ArgSize = 4;
6521 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006522 case ABIArgInfo::Indirect:
6523 llvm::Value *ArgAddr;
6524 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6525 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006526 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6527 ArgSize = 4;
6528 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006529 }
Robert Lytton2d196952013-10-11 10:29:34 +00006530
6531 // Increment the VAList.
6532 if (ArgSize) {
6533 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6534 Builder.CreateStore(APN, VAListAddrAsBPP);
6535 }
6536 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006537}
Robert Lytton0e076492013-08-13 09:43:10 +00006538
Robert Lytton844aeeb2014-05-02 09:33:20 +00006539/// During the expansion of a RecordType, an incomplete TypeString is placed
6540/// into the cache as a means to identify and break recursion.
6541/// If there is a Recursive encoding in the cache, it is swapped out and will
6542/// be reinserted by removeIncomplete().
6543/// All other types of encoding should have been used rather than arriving here.
6544void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6545 std::string StubEnc) {
6546 if (!ID)
6547 return;
6548 Entry &E = Map[ID];
6549 assert( (E.Str.empty() || E.State == Recursive) &&
6550 "Incorrectly use of addIncomplete");
6551 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6552 E.Swapped.swap(E.Str); // swap out the Recursive
6553 E.Str.swap(StubEnc);
6554 E.State = Incomplete;
6555 ++IncompleteCount;
6556}
6557
6558/// Once the RecordType has been expanded, the temporary incomplete TypeString
6559/// must be removed from the cache.
6560/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6561/// Returns true if the RecordType was defined recursively.
6562bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6563 if (!ID)
6564 return false;
6565 auto I = Map.find(ID);
6566 assert(I != Map.end() && "Entry not present");
6567 Entry &E = I->second;
6568 assert( (E.State == Incomplete ||
6569 E.State == IncompleteUsed) &&
6570 "Entry must be an incomplete type");
6571 bool IsRecursive = false;
6572 if (E.State == IncompleteUsed) {
6573 // We made use of our Incomplete encoding, thus we are recursive.
6574 IsRecursive = true;
6575 --IncompleteUsedCount;
6576 }
6577 if (E.Swapped.empty())
6578 Map.erase(I);
6579 else {
6580 // Swap the Recursive back.
6581 E.Swapped.swap(E.Str);
6582 E.Swapped.clear();
6583 E.State = Recursive;
6584 }
6585 --IncompleteCount;
6586 return IsRecursive;
6587}
6588
6589/// Add the encoded TypeString to the cache only if it is NonRecursive or
6590/// Recursive (viz: all sub-members were expanded as fully as possible).
6591void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6592 bool IsRecursive) {
6593 if (!ID || IncompleteUsedCount)
6594 return; // No key or it is is an incomplete sub-type so don't add.
6595 Entry &E = Map[ID];
6596 if (IsRecursive && !E.Str.empty()) {
6597 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6598 "This is not the same Recursive entry");
6599 // The parent container was not recursive after all, so we could have used
6600 // this Recursive sub-member entry after all, but we assumed the worse when
6601 // we started viz: IncompleteCount!=0.
6602 return;
6603 }
6604 assert(E.Str.empty() && "Entry already present");
6605 E.Str = Str.str();
6606 E.State = IsRecursive? Recursive : NonRecursive;
6607}
6608
6609/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6610/// are recursively expanding a type (IncompleteCount != 0) and the cached
6611/// encoding is Recursive, return an empty StringRef.
6612StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6613 if (!ID)
6614 return StringRef(); // We have no key.
6615 auto I = Map.find(ID);
6616 if (I == Map.end())
6617 return StringRef(); // We have no encoding.
6618 Entry &E = I->second;
6619 if (E.State == Recursive && IncompleteCount)
6620 return StringRef(); // We don't use Recursive encodings for member types.
6621
6622 if (E.State == Incomplete) {
6623 // The incomplete type is being used to break out of recursion.
6624 E.State = IncompleteUsed;
6625 ++IncompleteUsedCount;
6626 }
6627 return E.Str.c_str();
6628}
6629
6630/// The XCore ABI includes a type information section that communicates symbol
6631/// type information to the linker. The linker uses this information to verify
6632/// safety/correctness of things such as array bound and pointers et al.
6633/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6634/// This type information (TypeString) is emitted into meta data for all global
6635/// symbols: definitions, declarations, functions & variables.
6636///
6637/// The TypeString carries type, qualifier, name, size & value details.
6638/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6639/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6640/// The output is tested by test/CodeGen/xcore-stringtype.c.
6641///
6642static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6643 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6644
6645/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6646void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6647 CodeGen::CodeGenModule &CGM) const {
6648 SmallStringEnc Enc;
6649 if (getTypeString(Enc, D, CGM, TSC)) {
6650 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6651 llvm::SmallVector<llvm::Value *, 2> MDVals;
6652 MDVals.push_back(GV);
6653 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6654 llvm::NamedMDNode *MD =
6655 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6656 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6657 }
6658}
6659
6660static bool appendType(SmallStringEnc &Enc, QualType QType,
6661 const CodeGen::CodeGenModule &CGM,
6662 TypeStringCache &TSC);
6663
6664/// Helper function for appendRecordType().
6665/// Builds a SmallVector containing the encoded field types in declaration order.
6666static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6667 const RecordDecl *RD,
6668 const CodeGen::CodeGenModule &CGM,
6669 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006670 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006671 SmallStringEnc Enc;
6672 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006673 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006674 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006675 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006676 Enc += "b(";
6677 llvm::raw_svector_ostream OS(Enc);
6678 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006679 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006680 OS.flush();
6681 Enc += ':';
6682 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006683 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006684 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006685 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006686 Enc += ')';
6687 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006688 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006689 }
6690 return true;
6691}
6692
6693/// Appends structure and union types to Enc and adds encoding to cache.
6694/// Recursively calls appendType (via extractFieldType) for each field.
6695/// Union types have their fields ordered according to the ABI.
6696static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6697 const CodeGen::CodeGenModule &CGM,
6698 TypeStringCache &TSC, const IdentifierInfo *ID) {
6699 // Append the cached TypeString if we have one.
6700 StringRef TypeString = TSC.lookupStr(ID);
6701 if (!TypeString.empty()) {
6702 Enc += TypeString;
6703 return true;
6704 }
6705
6706 // Start to emit an incomplete TypeString.
6707 size_t Start = Enc.size();
6708 Enc += (RT->isUnionType()? 'u' : 's');
6709 Enc += '(';
6710 if (ID)
6711 Enc += ID->getName();
6712 Enc += "){";
6713
6714 // We collect all encoded fields and order as necessary.
6715 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006716 const RecordDecl *RD = RT->getDecl()->getDefinition();
6717 if (RD && !RD->field_empty()) {
6718 // An incomplete TypeString stub is placed in the cache for this RecordType
6719 // so that recursive calls to this RecordType will use it whilst building a
6720 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006721 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006722 std::string StubEnc(Enc.substr(Start).str());
6723 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6724 TSC.addIncomplete(ID, std::move(StubEnc));
6725 if (!extractFieldType(FE, RD, CGM, TSC)) {
6726 (void) TSC.removeIncomplete(ID);
6727 return false;
6728 }
6729 IsRecursive = TSC.removeIncomplete(ID);
6730 // The ABI requires unions to be sorted but not structures.
6731 // See FieldEncoding::operator< for sort algorithm.
6732 if (RT->isUnionType())
6733 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006734 // We can now complete the TypeString.
6735 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006736 for (unsigned I = 0; I != E; ++I) {
6737 if (I)
6738 Enc += ',';
6739 Enc += FE[I].str();
6740 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006741 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006742 Enc += '}';
6743 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6744 return true;
6745}
6746
6747/// Appends enum types to Enc and adds the encoding to the cache.
6748static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6749 TypeStringCache &TSC,
6750 const IdentifierInfo *ID) {
6751 // Append the cached TypeString if we have one.
6752 StringRef TypeString = TSC.lookupStr(ID);
6753 if (!TypeString.empty()) {
6754 Enc += TypeString;
6755 return true;
6756 }
6757
6758 size_t Start = Enc.size();
6759 Enc += "e(";
6760 if (ID)
6761 Enc += ID->getName();
6762 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006763
6764 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006765 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006766 SmallVector<FieldEncoding, 16> FE;
6767 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6768 ++I) {
6769 SmallStringEnc EnumEnc;
6770 EnumEnc += "m(";
6771 EnumEnc += I->getName();
6772 EnumEnc += "){";
6773 I->getInitVal().toString(EnumEnc);
6774 EnumEnc += '}';
6775 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6776 }
6777 std::sort(FE.begin(), FE.end());
6778 unsigned E = FE.size();
6779 for (unsigned I = 0; I != E; ++I) {
6780 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006781 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006782 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006783 }
6784 }
6785 Enc += '}';
6786 TSC.addIfComplete(ID, Enc.substr(Start), false);
6787 return true;
6788}
6789
6790/// Appends type's qualifier to Enc.
6791/// This is done prior to appending the type's encoding.
6792static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6793 // Qualifiers are emitted in alphabetical order.
6794 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6795 int Lookup = 0;
6796 if (QT.isConstQualified())
6797 Lookup += 1<<0;
6798 if (QT.isRestrictQualified())
6799 Lookup += 1<<1;
6800 if (QT.isVolatileQualified())
6801 Lookup += 1<<2;
6802 Enc += Table[Lookup];
6803}
6804
6805/// Appends built-in types to Enc.
6806static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6807 const char *EncType;
6808 switch (BT->getKind()) {
6809 case BuiltinType::Void:
6810 EncType = "0";
6811 break;
6812 case BuiltinType::Bool:
6813 EncType = "b";
6814 break;
6815 case BuiltinType::Char_U:
6816 EncType = "uc";
6817 break;
6818 case BuiltinType::UChar:
6819 EncType = "uc";
6820 break;
6821 case BuiltinType::SChar:
6822 EncType = "sc";
6823 break;
6824 case BuiltinType::UShort:
6825 EncType = "us";
6826 break;
6827 case BuiltinType::Short:
6828 EncType = "ss";
6829 break;
6830 case BuiltinType::UInt:
6831 EncType = "ui";
6832 break;
6833 case BuiltinType::Int:
6834 EncType = "si";
6835 break;
6836 case BuiltinType::ULong:
6837 EncType = "ul";
6838 break;
6839 case BuiltinType::Long:
6840 EncType = "sl";
6841 break;
6842 case BuiltinType::ULongLong:
6843 EncType = "ull";
6844 break;
6845 case BuiltinType::LongLong:
6846 EncType = "sll";
6847 break;
6848 case BuiltinType::Float:
6849 EncType = "ft";
6850 break;
6851 case BuiltinType::Double:
6852 EncType = "d";
6853 break;
6854 case BuiltinType::LongDouble:
6855 EncType = "ld";
6856 break;
6857 default:
6858 return false;
6859 }
6860 Enc += EncType;
6861 return true;
6862}
6863
6864/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6865static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6866 const CodeGen::CodeGenModule &CGM,
6867 TypeStringCache &TSC) {
6868 Enc += "p(";
6869 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6870 return false;
6871 Enc += ')';
6872 return true;
6873}
6874
6875/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006876static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6877 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006878 const CodeGen::CodeGenModule &CGM,
6879 TypeStringCache &TSC, StringRef NoSizeEnc) {
6880 if (AT->getSizeModifier() != ArrayType::Normal)
6881 return false;
6882 Enc += "a(";
6883 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6884 CAT->getSize().toStringUnsigned(Enc);
6885 else
6886 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6887 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006888 // The Qualifiers should be attached to the type rather than the array.
6889 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006890 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6891 return false;
6892 Enc += ')';
6893 return true;
6894}
6895
6896/// Appends a function encoding to Enc, calling appendType for the return type
6897/// and the arguments.
6898static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6899 const CodeGen::CodeGenModule &CGM,
6900 TypeStringCache &TSC) {
6901 Enc += "f{";
6902 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6903 return false;
6904 Enc += "}(";
6905 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6906 // N.B. we are only interested in the adjusted param types.
6907 auto I = FPT->param_type_begin();
6908 auto E = FPT->param_type_end();
6909 if (I != E) {
6910 do {
6911 if (!appendType(Enc, *I, CGM, TSC))
6912 return false;
6913 ++I;
6914 if (I != E)
6915 Enc += ',';
6916 } while (I != E);
6917 if (FPT->isVariadic())
6918 Enc += ",va";
6919 } else {
6920 if (FPT->isVariadic())
6921 Enc += "va";
6922 else
6923 Enc += '0';
6924 }
6925 }
6926 Enc += ')';
6927 return true;
6928}
6929
6930/// Handles the type's qualifier before dispatching a call to handle specific
6931/// type encodings.
6932static bool appendType(SmallStringEnc &Enc, QualType QType,
6933 const CodeGen::CodeGenModule &CGM,
6934 TypeStringCache &TSC) {
6935
6936 QualType QT = QType.getCanonicalType();
6937
Robert Lytton6adb20f2014-06-05 09:06:21 +00006938 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6939 // The Qualifiers should be attached to the type rather than the array.
6940 // Thus we don't call appendQualifier() here.
6941 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6942
Robert Lytton844aeeb2014-05-02 09:33:20 +00006943 appendQualifier(Enc, QT);
6944
6945 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6946 return appendBuiltinType(Enc, BT);
6947
Robert Lytton844aeeb2014-05-02 09:33:20 +00006948 if (const PointerType *PT = QT->getAs<PointerType>())
6949 return appendPointerType(Enc, PT, CGM, TSC);
6950
6951 if (const EnumType *ET = QT->getAs<EnumType>())
6952 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6953
6954 if (const RecordType *RT = QT->getAsStructureType())
6955 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6956
6957 if (const RecordType *RT = QT->getAsUnionType())
6958 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6959
6960 if (const FunctionType *FT = QT->getAs<FunctionType>())
6961 return appendFunctionType(Enc, FT, CGM, TSC);
6962
6963 return false;
6964}
6965
6966static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6967 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6968 if (!D)
6969 return false;
6970
6971 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6972 if (FD->getLanguageLinkage() != CLanguageLinkage)
6973 return false;
6974 return appendType(Enc, FD->getType(), CGM, TSC);
6975 }
6976
6977 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6978 if (VD->getLanguageLinkage() != CLanguageLinkage)
6979 return false;
6980 QualType QT = VD->getType().getCanonicalType();
6981 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6982 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006983 // The Qualifiers should be attached to the type rather than the array.
6984 // Thus we don't call appendQualifier() here.
6985 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00006986 }
6987 return appendType(Enc, QT, CGM, TSC);
6988 }
6989 return false;
6990}
6991
6992
Robert Lytton0e076492013-08-13 09:43:10 +00006993//===----------------------------------------------------------------------===//
6994// Driver code
6995//===----------------------------------------------------------------------===//
6996
Rafael Espindola9f834732014-09-19 01:54:22 +00006997const llvm::Triple &CodeGenModule::getTriple() const {
6998 return getTarget().getTriple();
6999}
7000
7001bool CodeGenModule::supportsCOMDAT() const {
7002 return !getTriple().isOSBinFormatMachO();
7003}
7004
Chris Lattner2b037972010-07-29 02:01:43 +00007005const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007006 if (TheTargetCodeGenInfo)
7007 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007008
John McCallc8e01702013-04-16 22:48:15 +00007009 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007010 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007011 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007012 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007013
Derek Schuff09338a22012-09-06 17:37:28 +00007014 case llvm::Triple::le32:
7015 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007016 case llvm::Triple::mips:
7017 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007018 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7019
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007020 case llvm::Triple::mips64:
7021 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007022 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7023
Tim Northover25e8a672014-05-24 12:51:25 +00007024 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007025 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007026 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007027 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007028 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007029
Tim Northover573cbee2014-05-24 12:52:07 +00007030 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007031 }
7032
Daniel Dunbard59655c2009-09-12 00:59:49 +00007033 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007034 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007035 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007036 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007037 {
7038 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007039 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007040 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007041 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007042 (CodeGenOpts.FloatABI != "soft" &&
7043 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007044 Kind = ARMABIInfo::AAPCS_VFP;
7045
Derek Schuffa2020962012-10-16 22:30:41 +00007046 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00007047 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00007048 return *(TheTargetCodeGenInfo =
7049 new NaClARMTargetCodeGenInfo(Types, Kind));
7050 default:
7051 return *(TheTargetCodeGenInfo =
7052 new ARMTargetCodeGenInfo(Types, Kind));
7053 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007054 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007055
John McCallea8d8bb2010-03-11 00:10:12 +00007056 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007057 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007058 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007059 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007060 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007061 if (getTarget().getABI() == "elfv2")
7062 Kind = PPC64_SVR4_ABIInfo::ELFv2;
7063
Ulrich Weigandb7122372014-07-21 00:48:09 +00007064 return *(TheTargetCodeGenInfo =
7065 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7066 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007067 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007068 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007069 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007070 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007071 if (getTarget().getABI() == "elfv1")
7072 Kind = PPC64_SVR4_ABIInfo::ELFv1;
7073
Ulrich Weigandb7122372014-07-21 00:48:09 +00007074 return *(TheTargetCodeGenInfo =
7075 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7076 }
John McCallea8d8bb2010-03-11 00:10:12 +00007077
Peter Collingbournec947aae2012-05-20 23:28:41 +00007078 case llvm::Triple::nvptx:
7079 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007080 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007081
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007082 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007083 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007084
Ulrich Weigand47445072013-05-06 16:26:41 +00007085 case llvm::Triple::systemz:
7086 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
7087
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007088 case llvm::Triple::tce:
7089 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7090
Eli Friedman33465822011-07-08 23:31:17 +00007091 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007092 bool IsDarwinVectorABI = Triple.isOSDarwin();
7093 bool IsSmallStructInRegABI =
7094 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00007095 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007096
John McCall1fe2a8c2013-06-18 02:46:29 +00007097 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007098 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007099 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007100 IsDarwinVectorABI, IsSmallStructInRegABI,
7101 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007102 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007103 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007104 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007105 new X86_32TargetCodeGenInfo(Types,
7106 IsDarwinVectorABI, IsSmallStructInRegABI,
7107 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007108 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007109 }
Eli Friedman33465822011-07-08 23:31:17 +00007110 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007111
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007112 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007113 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007114
Chris Lattner04dc9572010-08-31 16:44:54 +00007115 switch (Triple.getOS()) {
7116 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007117 return *(TheTargetCodeGenInfo =
7118 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Eli Benderskyd7c92032012-12-04 18:38:10 +00007119 case llvm::Triple::NaCl:
Alexander Musman09184fe2014-09-30 05:29:28 +00007120 return *(TheTargetCodeGenInfo =
7121 new NaClX86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007122 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007123 return *(TheTargetCodeGenInfo =
7124 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007125 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007126 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007127 case llvm::Triple::hexagon:
7128 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007129 case llvm::Triple::sparcv9:
7130 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007131 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007132 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007133 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007134}