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