blob: 3b09d4b93f44caee4d2ca9cda652fdf26e568008 [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"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000023#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000027#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000028#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) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000040 llvm::Value *Cell =
41 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall943fae92010-05-27 06:19:26 +000042 Builder.CreateStore(Value, Cell);
43 }
44}
45
John McCalla1dee5302010-08-22 10:59:02 +000046static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000047 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000048 T->isMemberFunctionPointerType();
49}
50
Anton Korobeynikov244360d2009-06-05 22:08:42 +000051ABIInfo::~ABIInfo() {}
52
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000053static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000054 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000055 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
56 if (!RD)
57 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000058 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000059}
60
61static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000062 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000063 const RecordType *RT = T->getAs<RecordType>();
64 if (!RT)
65 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000066 return getRecordArgABI(RT, CXXABI);
67}
68
Reid Klecknerb1be6832014-11-15 01:41:41 +000069/// Pass transparent unions as if they were the type of the first element. Sema
70/// should ensure that all elements of the union have the same "machine type".
71static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
72 if (const RecordType *UT = Ty->getAsUnionType()) {
73 const RecordDecl *UD = UT->getDecl();
74 if (UD->hasAttr<TransparentUnionAttr>()) {
75 assert(!UD->field_empty() && "sema created an empty transparent union");
76 return UD->field_begin()->getType();
77 }
78 }
79 return Ty;
80}
81
Mark Lacey3825e832013-10-06 01:33:34 +000082CGCXXABI &ABIInfo::getCXXABI() const {
83 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000084}
85
Chris Lattner2b037972010-07-29 02:01:43 +000086ASTContext &ABIInfo::getContext() const {
87 return CGT.getContext();
88}
89
90llvm::LLVMContext &ABIInfo::getVMContext() const {
91 return CGT.getLLVMContext();
92}
93
Micah Villmowdd31ca12012-10-08 16:25:52 +000094const llvm::DataLayout &ABIInfo::getDataLayout() const {
95 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000096}
97
John McCallc8e01702013-04-16 22:48:15 +000098const TargetInfo &ABIInfo::getTarget() const {
99 return CGT.getTarget();
100}
Chris Lattner2b037972010-07-29 02:01:43 +0000101
Reid Klecknere9f6a712014-10-31 17:10:41 +0000102bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
103 return false;
104}
105
106bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
107 uint64_t Members) const {
108 return false;
109}
110
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000111void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000112 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000113 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000114 switch (TheKind) {
115 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000116 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000117 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000118 Ty->print(OS);
119 else
120 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000121 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000122 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000123 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000124 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000125 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000128 case InAlloca:
129 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
130 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000131 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000132 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000133 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000134 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000135 break;
136 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000137 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000138 break;
139 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000140 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000141}
142
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000143TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
144
John McCall3480ef22011-08-30 01:42:09 +0000145// If someone can figure out a general rule for this, that would be great.
146// It's probably just doomed to be platform-dependent, though.
147unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
148 // Verified for:
149 // x86-64 FreeBSD, Linux, Darwin
150 // x86-32 FreeBSD, Linux, Darwin
151 // PowerPC Linux, Darwin
152 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000153 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000154 return 32;
155}
156
John McCalla729c622012-02-17 03:33:10 +0000157bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
158 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000159 // The following conventions are known to require this to be false:
160 // x86_stdcall
161 // MIPS
162 // For everything else, we just prefer false unless we opt out.
163 return false;
164}
165
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000166void
167TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
168 llvm::SmallString<24> &Opt) const {
169 // This assumes the user is passing a library name like "rt" instead of a
170 // filename like "librt.a/so", and that they don't care whether it's static or
171 // dynamic.
172 Opt = "-l";
173 Opt += Lib;
174}
175
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000176static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000177
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000178/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000179/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000180static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
181 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000182 if (FD->isUnnamedBitfield())
183 return true;
184
185 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000186
Eli Friedman0b3f2012011-11-18 03:47:20 +0000187 // Constant arrays of empty records count as empty, strip them off.
188 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000189 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000190 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
191 if (AT->getSize() == 0)
192 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000194 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000195
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000196 const RecordType *RT = FT->getAs<RecordType>();
197 if (!RT)
198 return false;
199
200 // C++ record fields are never empty, at least in the Itanium ABI.
201 //
202 // FIXME: We should use a predicate for whether this behavior is true in the
203 // current ABI.
204 if (isa<CXXRecordDecl>(RT->getDecl()))
205 return false;
206
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000207 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000208}
209
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000210/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000211/// fields. Note that a structure with a flexible array member is not
212/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000213static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000214 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215 if (!RT)
216 return 0;
217 const RecordDecl *RD = RT->getDecl();
218 if (RD->hasFlexibleArrayMember())
219 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000220
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000221 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000222 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000223 for (const auto &I : CXXRD->bases())
224 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000225 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000226
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000227 for (const auto *I : RD->fields())
228 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000229 return false;
230 return true;
231}
232
233/// isSingleElementStruct - Determine if a structure is a "single
234/// element struct", i.e. it has exactly one non-empty field or
235/// exactly one field which is itself a single element
236/// struct. Structures with flexible array members are never
237/// considered single element structs.
238///
239/// \return The field declaration for the single non-empty field, if
240/// it exists.
241static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000242 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000243 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000244 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000245
246 const RecordDecl *RD = RT->getDecl();
247 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000248 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000249
Craig Topper8a13c412014-05-21 05:09:00 +0000250 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000251
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000252 // If this is a C++ record, check the bases first.
253 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000254 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000255 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000256 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000257 continue;
258
259 // If we already found an element then this isn't a single-element struct.
260 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000261 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000262
263 // If this is non-empty and not a single element struct, the composite
264 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000265 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000266 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000267 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000268 }
269 }
270
271 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000272 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000273 QualType FT = FD->getType();
274
275 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000276 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000277 continue;
278
279 // If we already found an element then this isn't a single-element
280 // struct.
281 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000282 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000283
284 // Treat single element arrays as the element.
285 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
286 if (AT->getSize().getZExtValue() != 1)
287 break;
288 FT = AT->getElementType();
289 }
290
John McCalla1dee5302010-08-22 10:59:02 +0000291 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000292 Found = FT.getTypePtr();
293 } else {
294 Found = isSingleElementStruct(FT, Context);
295 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000296 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000297 }
298 }
299
Eli Friedmanee945342011-11-18 01:25:50 +0000300 // We don't consider a struct a single-element struct if it has
301 // padding beyond the element type.
302 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000303 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000304
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000305 return Found;
306}
307
308static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000309 // Treat complex types as the element type.
310 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
311 Ty = CTy->getElementType();
312
313 // Check for a type which we know has a simple scalar argument-passing
314 // convention without any padding. (We're specifically looking for 32
315 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000316 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000317 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000318 return false;
319
320 uint64_t Size = Context.getTypeSize(Ty);
321 return Size == 32 || Size == 64;
322}
323
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000324/// canExpandIndirectArgument - Test whether an argument type which is to be
325/// passed indirectly (on the stack) would have the equivalent layout if it was
326/// expanded into separate arguments. If so, we prefer to do the latter to avoid
327/// inhibiting optimizations.
328///
329// FIXME: This predicate is missing many cases, currently it just follows
330// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
331// should probably make this smarter, or better yet make the LLVM backend
332// capable of handling it.
333static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
334 // We can only expand structure types.
335 const RecordType *RT = Ty->getAs<RecordType>();
336 if (!RT)
337 return false;
338
339 // We can only expand (C) structures.
340 //
341 // FIXME: This needs to be generalized to handle classes as well.
342 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000343 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000344 return false;
345
Manman Ren27382782015-04-03 18:10:29 +0000346 // We try to expand CLike CXXRecordDecl.
347 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
348 if (!CXXRD->isCLike())
349 return false;
350 }
351
Eli Friedmane5c85622011-11-18 01:32:26 +0000352 uint64_t Size = 0;
353
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000354 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000355 if (!is32Or64BitBasicType(FD->getType(), Context))
356 return false;
357
358 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
359 // how to expand them yet, and the predicate for telling if a bitfield still
360 // counts as "basic" is more complicated than what we were doing previously.
361 if (FD->isBitField())
362 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000363
364 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000365 }
366
Eli Friedmane5c85622011-11-18 01:32:26 +0000367 // Make sure there are not any holes in the struct.
368 if (Size != Context.getTypeSize(Ty))
369 return false;
370
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000371 return true;
372}
373
374namespace {
375/// DefaultABIInfo - The default implementation for ABI specific
376/// details. This implementation provides information which results in
377/// self-consistent and sensible LLVM IR generation, but does not
378/// conform to any particular ABI.
379class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000380public:
381 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000382
Chris Lattner458b2aa2010-07-29 02:16:43 +0000383 ABIArgInfo classifyReturnType(QualType RetTy) const;
384 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000385
Craig Topper4f12f102014-03-12 06:41:41 +0000386 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000387 if (!getCXXABI().classifyReturnType(FI))
388 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000389 for (auto &I : FI.arguments())
390 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000391 }
392
Craig Topper4f12f102014-03-12 06:41:41 +0000393 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
394 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000395};
396
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000397class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
398public:
Chris Lattner2b037972010-07-29 02:01:43 +0000399 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
400 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000401};
402
403llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
404 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000405 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000406}
407
Chris Lattner458b2aa2010-07-29 02:16:43 +0000408ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000409 Ty = useFirstFieldIfTransparentUnion(Ty);
410
411 if (isAggregateTypeForABI(Ty)) {
412 // Records with non-trivial destructors/copy-constructors should not be
413 // passed by value.
414 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
415 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
416
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000417 return ABIArgInfo::getIndirect(0);
Reid Klecknerac385062015-05-18 22:46:30 +0000418 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000419
Chris Lattner9723d6c2010-03-11 18:19:55 +0000420 // Treat an enum type as its underlying type.
421 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
422 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000423
Chris Lattner9723d6c2010-03-11 18:19:55 +0000424 return (Ty->isPromotableIntegerType() ?
425 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000426}
427
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000428ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
429 if (RetTy->isVoidType())
430 return ABIArgInfo::getIgnore();
431
432 if (isAggregateTypeForABI(RetTy))
433 return ABIArgInfo::getIndirect(0);
434
435 // Treat an enum type as its underlying type.
436 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
437 RetTy = EnumTy->getDecl()->getIntegerType();
438
439 return (RetTy->isPromotableIntegerType() ?
440 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
441}
442
Derek Schuff09338a22012-09-06 17:37:28 +0000443//===----------------------------------------------------------------------===//
444// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000445//
446// This is a simplified version of the x86_32 ABI. Arguments and return values
447// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000448//===----------------------------------------------------------------------===//
449
450class PNaClABIInfo : public ABIInfo {
451 public:
452 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
453
454 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000455 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000456
Craig Topper4f12f102014-03-12 06:41:41 +0000457 void computeInfo(CGFunctionInfo &FI) const override;
458 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
459 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000460};
461
462class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
463 public:
464 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
465 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
466};
467
468void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000469 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000470 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
471
Reid Kleckner40ca9132014-05-13 22:05:45 +0000472 for (auto &I : FI.arguments())
473 I.info = classifyArgumentType(I.type);
474}
Derek Schuff09338a22012-09-06 17:37:28 +0000475
476llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
477 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000478 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000479}
480
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000481/// \brief Classify argument of given type \p Ty.
482ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000483 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000484 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000485 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000486 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000487 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
488 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000489 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000490 } else if (Ty->isFloatingType()) {
491 // Floating-point types don't go inreg.
492 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000493 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000494
495 return (Ty->isPromotableIntegerType() ?
496 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000497}
498
499ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
500 if (RetTy->isVoidType())
501 return ABIArgInfo::getIgnore();
502
Eli Benderskye20dad62013-04-04 22:49:35 +0000503 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000504 if (isAggregateTypeForABI(RetTy))
505 return ABIArgInfo::getIndirect(0);
506
507 // Treat an enum type as its underlying type.
508 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
509 RetTy = EnumTy->getDecl()->getIntegerType();
510
511 return (RetTy->isPromotableIntegerType() ?
512 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
513}
514
Chad Rosier651c1832013-03-25 21:00:27 +0000515/// IsX86_MMXType - Return true if this is an MMX type.
516bool IsX86_MMXType(llvm::Type *IRType) {
517 // 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 +0000518 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
519 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
520 IRType->getScalarSizeInBits() != 64;
521}
522
Jay Foad7c57be32011-07-11 09:56:20 +0000523static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000524 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000525 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000526 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
527 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
528 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000529 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000530 }
531
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000532 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000533 }
534
535 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000536 return Ty;
537}
538
Reid Kleckner80944df2014-10-31 22:00:51 +0000539/// Returns true if this type can be passed in SSE registers with the
540/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
541static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
542 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
543 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
544 return true;
545 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
546 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
547 // registers specially.
548 unsigned VecSize = Context.getTypeSize(VT);
549 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
550 return true;
551 }
552 return false;
553}
554
555/// Returns true if this aggregate is small enough to be passed in SSE registers
556/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
557static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
558 return NumMembers <= 4;
559}
560
Chris Lattner0cf24192010-06-28 20:05:43 +0000561//===----------------------------------------------------------------------===//
562// X86-32 ABI Implementation
563//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000564
Reid Kleckner661f35b2014-01-18 01:12:41 +0000565/// \brief Similar to llvm::CCState, but for Clang.
566struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000567 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000568
569 unsigned CC;
570 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000571 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000572};
573
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000574/// X86_32ABIInfo - The X86-32 ABI information.
575class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000576 enum Class {
577 Integer,
578 Float
579 };
580
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000581 static const unsigned MinABIStackAlignInBytes = 4;
582
David Chisnallde3a0692009-08-17 23:08:21 +0000583 bool IsDarwinVectorABI;
584 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000585 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000586 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000587
588 static bool isRegisterSize(unsigned Size) {
589 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
590 }
591
Reid Kleckner80944df2014-10-31 22:00:51 +0000592 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
593 // FIXME: Assumes vectorcall is in use.
594 return isX86VectorTypeForVectorCall(getContext(), Ty);
595 }
596
597 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
598 uint64_t NumMembers) const override {
599 // FIXME: Assumes vectorcall is in use.
600 return isX86VectorCallAggregateSmallEnough(NumMembers);
601 }
602
Reid Kleckner40ca9132014-05-13 22:05:45 +0000603 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000604
Daniel Dunbar557893d2010-04-21 19:10:51 +0000605 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
606 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000607 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
608
609 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000610
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000611 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000612 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000613
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000614 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000615 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000616 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
617 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000618
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000619 /// \brief Rewrite the function info so that all memory arguments use
620 /// inalloca.
621 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
622
623 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
624 unsigned &StackOffset, ABIArgInfo &Info,
625 QualType Type) const;
626
Rafael Espindola75419dc2012-07-23 23:30:29 +0000627public:
628
Craig Topper4f12f102014-03-12 06:41:41 +0000629 void computeInfo(CGFunctionInfo &FI) const override;
630 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
631 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000632
Chad Rosier651c1832013-03-25 21:00:27 +0000633 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000634 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000635 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000636 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000637};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000638
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000639class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
640public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000641 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000642 bool d, bool p, bool w, unsigned r)
643 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000644
John McCall1fe2a8c2013-06-18 02:46:29 +0000645 static bool isStructReturnInRegABI(
646 const llvm::Triple &Triple, const CodeGenOptions &Opts);
647
Charles Davis4ea31ab2010-02-13 15:54:06 +0000648 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000649 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000650
Craig Topper4f12f102014-03-12 06:41:41 +0000651 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000652 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000653 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000654 return 4;
655 }
656
657 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000658 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000659
Jay Foad7c57be32011-07-11 09:56:20 +0000660 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000661 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000662 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000663 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
664 }
665
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000666 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
667 std::string &Constraints,
668 std::vector<llvm::Type *> &ResultRegTypes,
669 std::vector<llvm::Type *> &ResultTruncRegTypes,
670 std::vector<LValue> &ResultRegDests,
671 std::string &AsmString,
672 unsigned NumOutputs) const override;
673
Craig Topper4f12f102014-03-12 06:41:41 +0000674 llvm::Constant *
675 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000676 unsigned Sig = (0xeb << 0) | // jmp rel8
677 (0x06 << 8) | // .+0x08
678 ('F' << 16) |
679 ('T' << 24);
680 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
681 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000682};
683
684}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000685
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000686/// Rewrite input constraint references after adding some output constraints.
687/// In the case where there is one output and one input and we add one output,
688/// we need to replace all operand references greater than or equal to 1:
689/// mov $0, $1
690/// mov eax, $1
691/// The result will be:
692/// mov $0, $2
693/// mov eax, $2
694static void rewriteInputConstraintReferences(unsigned FirstIn,
695 unsigned NumNewOuts,
696 std::string &AsmString) {
697 std::string Buf;
698 llvm::raw_string_ostream OS(Buf);
699 size_t Pos = 0;
700 while (Pos < AsmString.size()) {
701 size_t DollarStart = AsmString.find('$', Pos);
702 if (DollarStart == std::string::npos)
703 DollarStart = AsmString.size();
704 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
705 if (DollarEnd == std::string::npos)
706 DollarEnd = AsmString.size();
707 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
708 Pos = DollarEnd;
709 size_t NumDollars = DollarEnd - DollarStart;
710 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
711 // We have an operand reference.
712 size_t DigitStart = Pos;
713 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
714 if (DigitEnd == std::string::npos)
715 DigitEnd = AsmString.size();
716 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
717 unsigned OperandIndex;
718 if (!OperandStr.getAsInteger(10, OperandIndex)) {
719 if (OperandIndex >= FirstIn)
720 OperandIndex += NumNewOuts;
721 OS << OperandIndex;
722 } else {
723 OS << OperandStr;
724 }
725 Pos = DigitEnd;
726 }
727 }
728 AsmString = std::move(OS.str());
729}
730
731/// Add output constraints for EAX:EDX because they are return registers.
732void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
733 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
734 std::vector<llvm::Type *> &ResultRegTypes,
735 std::vector<llvm::Type *> &ResultTruncRegTypes,
736 std::vector<LValue> &ResultRegDests, std::string &AsmString,
737 unsigned NumOutputs) const {
738 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
739
740 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
741 // larger.
742 if (!Constraints.empty())
743 Constraints += ',';
744 if (RetWidth <= 32) {
745 Constraints += "={eax}";
746 ResultRegTypes.push_back(CGF.Int32Ty);
747 } else {
748 // Use the 'A' constraint for EAX:EDX.
749 Constraints += "=A";
750 ResultRegTypes.push_back(CGF.Int64Ty);
751 }
752
753 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
754 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
755 ResultTruncRegTypes.push_back(CoerceTy);
756
757 // Coerce the integer by bitcasting the return slot pointer.
758 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
759 CoerceTy->getPointerTo()));
760 ResultRegDests.push_back(ReturnSlot);
761
762 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
763}
764
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000765/// shouldReturnTypeInRegister - Determine if the given type should be
766/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000767bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
768 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000769 uint64_t Size = Context.getTypeSize(Ty);
770
771 // Type must be register sized.
772 if (!isRegisterSize(Size))
773 return false;
774
775 if (Ty->isVectorType()) {
776 // 64- and 128- bit vectors inside structures are not returned in
777 // registers.
778 if (Size == 64 || Size == 128)
779 return false;
780
781 return true;
782 }
783
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000784 // If this is a builtin, pointer, enum, complex type, member pointer, or
785 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000786 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000787 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000788 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000789 return true;
790
791 // Arrays are treated like records.
792 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000793 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000794
795 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000796 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000797 if (!RT) return false;
798
Anders Carlsson40446e82010-01-27 03:25:19 +0000799 // FIXME: Traverse bases here too.
800
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000801 // Structure types are passed in register if all fields would be
802 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000803 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000804 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000805 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000806 continue;
807
808 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000809 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000810 return false;
811 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000812 return true;
813}
814
Reid Kleckner661f35b2014-01-18 01:12:41 +0000815ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
816 // If the return value is indirect, then the hidden argument is consuming one
817 // integer register.
818 if (State.FreeRegs) {
819 --State.FreeRegs;
820 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
821 }
822 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
823}
824
Reid Kleckner40ca9132014-05-13 22:05:45 +0000825ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000826 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000827 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000828
Reid Kleckner80944df2014-10-31 22:00:51 +0000829 const Type *Base = nullptr;
830 uint64_t NumElts = 0;
831 if (State.CC == llvm::CallingConv::X86_VectorCall &&
832 isHomogeneousAggregate(RetTy, Base, NumElts)) {
833 // The LLVM struct type for such an aggregate should lower properly.
834 return ABIArgInfo::getDirect();
835 }
836
Chris Lattner458b2aa2010-07-29 02:16:43 +0000837 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000838 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000839 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000840 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000841
842 // 128-bit vectors are a special case; they are returned in
843 // registers and we need to make sure to pick a type the LLVM
844 // backend will like.
845 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000846 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000847 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000848
849 // Always return in register if it fits in a general purpose
850 // register, or if it is 64 bits and has a single element.
851 if ((Size == 8 || Size == 16 || Size == 32) ||
852 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000853 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000854 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000855
Reid Kleckner661f35b2014-01-18 01:12:41 +0000856 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000857 }
858
859 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000860 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000861
John McCalla1dee5302010-08-22 10:59:02 +0000862 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000863 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000864 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000865 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000866 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000867 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000868
David Chisnallde3a0692009-08-17 23:08:21 +0000869 // If specified, structs and unions are always indirect.
870 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000871 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000872
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000873 // Small structures which are register sized are generally returned
874 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000875 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000876 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000877
878 // As a special-case, if the struct is a "single-element" struct, and
879 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000880 // floating-point register. (MSVC does not apply this special case.)
881 // We apply a similar transformation for pointer types to improve the
882 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000883 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000884 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000885 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000886 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
887
888 // FIXME: We should be able to narrow this integer in cases with dead
889 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000890 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000891 }
892
Reid Kleckner661f35b2014-01-18 01:12:41 +0000893 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000894 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000895
Chris Lattner458b2aa2010-07-29 02:16:43 +0000896 // Treat an enum type as its underlying type.
897 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
898 RetTy = EnumTy->getDecl()->getIntegerType();
899
900 return (RetTy->isPromotableIntegerType() ?
901 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000902}
903
Eli Friedman7919bea2012-06-05 19:40:46 +0000904static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
905 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
906}
907
Daniel Dunbared23de32010-09-16 20:42:00 +0000908static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
909 const RecordType *RT = Ty->getAs<RecordType>();
910 if (!RT)
911 return 0;
912 const RecordDecl *RD = RT->getDecl();
913
914 // If this is a C++ record, check the bases first.
915 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000916 for (const auto &I : CXXRD->bases())
917 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000918 return false;
919
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000920 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000921 QualType FT = i->getType();
922
Eli Friedman7919bea2012-06-05 19:40:46 +0000923 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000924 return true;
925
926 if (isRecordWithSSEVectorType(Context, FT))
927 return true;
928 }
929
930 return false;
931}
932
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000933unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
934 unsigned Align) const {
935 // Otherwise, if the alignment is less than or equal to the minimum ABI
936 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000937 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000938 return 0; // Use default alignment.
939
940 // On non-Darwin, the stack type alignment is always 4.
941 if (!IsDarwinVectorABI) {
942 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000943 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000944 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000945
Daniel Dunbared23de32010-09-16 20:42:00 +0000946 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000947 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
948 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000949 return 16;
950
951 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000952}
953
Rafael Espindola703c47f2012-10-19 05:04:37 +0000954ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000955 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000956 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000957 if (State.FreeRegs) {
958 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000959 return ABIArgInfo::getIndirectInReg(0, false);
960 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000961 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000962 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000963
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000964 // Compute the byval alignment.
965 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
966 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
967 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000968 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000969
970 // If the stack alignment is less than the type alignment, realign the
971 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000972 bool Realign = TypeAlign > StackAlign;
973 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000974}
975
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000976X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
977 const Type *T = isSingleElementStruct(Ty, getContext());
978 if (!T)
979 T = Ty.getTypePtr();
980
981 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
982 BuiltinType::Kind K = BT->getKind();
983 if (K == BuiltinType::Float || K == BuiltinType::Double)
984 return Float;
985 }
986 return Integer;
987}
988
Reid Kleckner661f35b2014-01-18 01:12:41 +0000989bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
990 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000991 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000992 Class C = classify(Ty);
993 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000994 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000995
Rafael Espindola077dd592012-10-24 01:58:58 +0000996 unsigned Size = getContext().getTypeSize(Ty);
997 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000998
999 if (SizeInRegs == 0)
1000 return false;
1001
Reid Kleckner661f35b2014-01-18 01:12:41 +00001002 if (SizeInRegs > State.FreeRegs) {
1003 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001004 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001005 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001006
Reid Kleckner661f35b2014-01-18 01:12:41 +00001007 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001008
Reid Kleckner80944df2014-10-31 22:00:51 +00001009 if (State.CC == llvm::CallingConv::X86_FastCall ||
1010 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001011 if (Size > 32)
1012 return false;
1013
1014 if (Ty->isIntegralOrEnumerationType())
1015 return true;
1016
1017 if (Ty->isPointerType())
1018 return true;
1019
1020 if (Ty->isReferenceType())
1021 return true;
1022
Reid Kleckner661f35b2014-01-18 01:12:41 +00001023 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001024 NeedsPadding = true;
1025
Rafael Espindola077dd592012-10-24 01:58:58 +00001026 return false;
1027 }
1028
Rafael Espindola703c47f2012-10-19 05:04:37 +00001029 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001030}
1031
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001032ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1033 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001034 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001035
Reid Klecknerb1be6832014-11-15 01:41:41 +00001036 Ty = useFirstFieldIfTransparentUnion(Ty);
1037
Reid Kleckner80944df2014-10-31 22:00:51 +00001038 // Check with the C++ ABI first.
1039 const RecordType *RT = Ty->getAs<RecordType>();
1040 if (RT) {
1041 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1042 if (RAA == CGCXXABI::RAA_Indirect) {
1043 return getIndirectResult(Ty, false, State);
1044 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1045 // The field index doesn't matter, we'll fix it up later.
1046 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1047 }
1048 }
1049
1050 // vectorcall adds the concept of a homogenous vector aggregate, similar
1051 // to other targets.
1052 const Type *Base = nullptr;
1053 uint64_t NumElts = 0;
1054 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1055 isHomogeneousAggregate(Ty, Base, NumElts)) {
1056 if (State.FreeSSERegs >= NumElts) {
1057 State.FreeSSERegs -= NumElts;
1058 if (Ty->isBuiltinType() || Ty->isVectorType())
1059 return ABIArgInfo::getDirect();
1060 return ABIArgInfo::getExpand();
1061 }
1062 return getIndirectResult(Ty, /*ByVal=*/false, State);
1063 }
1064
1065 if (isAggregateTypeForABI(Ty)) {
1066 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001067 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001068 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001069 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001070
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001071 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001072 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001073 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001074 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001075
Eli Friedman9f061a32011-11-18 00:28:11 +00001076 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001077 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001078 return ABIArgInfo::getIgnore();
1079
Rafael Espindolafad28de2012-10-24 01:59:00 +00001080 llvm::LLVMContext &LLVMContext = getVMContext();
1081 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1082 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001083 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001084 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001085 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001086 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1087 return ABIArgInfo::getDirectInReg(Result);
1088 }
Craig Topper8a13c412014-05-21 05:09:00 +00001089 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001090
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001091 // Expand small (<= 128-bit) record types when we know that the stack layout
1092 // of those arguments will match the struct. This is important because the
1093 // LLVM backend isn't smart enough to remove byval, which inhibits many
1094 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001095 if (getContext().getTypeSize(Ty) <= 4*32 &&
1096 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001097 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001098 State.CC == llvm::CallingConv::X86_FastCall ||
1099 State.CC == llvm::CallingConv::X86_VectorCall,
1100 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101
Reid Kleckner661f35b2014-01-18 01:12:41 +00001102 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001103 }
1104
Chris Lattnerd774ae92010-08-26 20:05:13 +00001105 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001106 // On Darwin, some vectors are passed in memory, we handle this by passing
1107 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001108 if (IsDarwinVectorABI) {
1109 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001110 if ((Size == 8 || Size == 16 || Size == 32) ||
1111 (Size == 64 && VT->getNumElements() == 1))
1112 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1113 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001114 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001115
Chad Rosier651c1832013-03-25 21:00:27 +00001116 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1117 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001118
Chris Lattnerd774ae92010-08-26 20:05:13 +00001119 return ABIArgInfo::getDirect();
1120 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001121
1122
Chris Lattner458b2aa2010-07-29 02:16:43 +00001123 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1124 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001125
Rafael Espindolafad28de2012-10-24 01:59:00 +00001126 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001127 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001128
1129 if (Ty->isPromotableIntegerType()) {
1130 if (InReg)
1131 return ABIArgInfo::getExtendInReg();
1132 return ABIArgInfo::getExtend();
1133 }
1134 if (InReg)
1135 return ABIArgInfo::getDirectInReg();
1136 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001137}
1138
Rafael Espindolaa6472962012-07-24 00:01:07 +00001139void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001140 CCState State(FI.getCallingConvention());
1141 if (State.CC == llvm::CallingConv::X86_FastCall)
1142 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001143 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1144 State.FreeRegs = 2;
1145 State.FreeSSERegs = 6;
1146 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001147 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001148 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001149 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001150
Reid Kleckner677539d2014-07-10 01:58:55 +00001151 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001152 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001153 } else if (FI.getReturnInfo().isIndirect()) {
1154 // The C++ ABI is not aware of register usage, so we have to check if the
1155 // return value was sret and put it in a register ourselves if appropriate.
1156 if (State.FreeRegs) {
1157 --State.FreeRegs; // The sret parameter consumes a register.
1158 FI.getReturnInfo().setInReg(true);
1159 }
1160 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001161
Peter Collingbournef7706832014-12-12 23:41:25 +00001162 // The chain argument effectively gives us another free register.
1163 if (FI.isChainCall())
1164 ++State.FreeRegs;
1165
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001166 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001167 for (auto &I : FI.arguments()) {
1168 I.info = classifyArgumentType(I.type, State);
1169 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001170 }
1171
1172 // If we needed to use inalloca for any argument, do a second pass and rewrite
1173 // all the memory arguments to use inalloca.
1174 if (UsedInAlloca)
1175 rewriteWithInAlloca(FI);
1176}
1177
1178void
1179X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1180 unsigned &StackOffset,
1181 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001182 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1183 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1184 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1185 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1186
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001187 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1188 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001189 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001190 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001191 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001192 unsigned NumBytes = StackOffset - OldOffset;
1193 assert(NumBytes);
1194 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1195 Ty = llvm::ArrayType::get(Ty, NumBytes);
1196 FrameFields.push_back(Ty);
1197 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001198}
1199
Reid Kleckner852361d2014-07-26 00:12:26 +00001200static bool isArgInAlloca(const ABIArgInfo &Info) {
1201 // Leave ignored and inreg arguments alone.
1202 switch (Info.getKind()) {
1203 case ABIArgInfo::InAlloca:
1204 return true;
1205 case ABIArgInfo::Indirect:
1206 assert(Info.getIndirectByVal());
1207 return true;
1208 case ABIArgInfo::Ignore:
1209 return false;
1210 case ABIArgInfo::Direct:
1211 case ABIArgInfo::Extend:
1212 case ABIArgInfo::Expand:
1213 if (Info.getInReg())
1214 return false;
1215 return true;
1216 }
1217 llvm_unreachable("invalid enum");
1218}
1219
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001220void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1221 assert(IsWin32StructABI && "inalloca only supported on win32");
1222
1223 // Build a packed struct type for all of the arguments in memory.
1224 SmallVector<llvm::Type *, 6> FrameFields;
1225
1226 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001227 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1228
1229 // Put 'this' into the struct before 'sret', if necessary.
1230 bool IsThisCall =
1231 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1232 ABIArgInfo &Ret = FI.getReturnInfo();
1233 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1234 isArgInAlloca(I->info)) {
1235 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1236 ++I;
1237 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001238
1239 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001240 if (Ret.isIndirect() && !Ret.getInReg()) {
1241 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1242 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001243 // On Windows, the hidden sret parameter is always returned in eax.
1244 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001245 }
1246
1247 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001248 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001249 ++I;
1250
1251 // Put arguments passed in memory into the struct.
1252 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001253 if (isArgInAlloca(I->info))
1254 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001255 }
1256
1257 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1258 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001259}
1260
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001261llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1262 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001263 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001264
1265 CGBuilderTy &Builder = CGF.Builder;
1266 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1267 "ap");
1268 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001269
1270 // Compute if the address needs to be aligned
1271 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1272 Align = getTypeStackAlignInBytes(Ty, Align);
1273 Align = std::max(Align, 4U);
1274 if (Align > 4) {
1275 // addr = (addr + align - 1) & -align;
1276 llvm::Value *Offset =
1277 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1278 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1279 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1280 CGF.Int32Ty);
1281 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1282 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1283 Addr->getType(),
1284 "ap.cur.aligned");
1285 }
1286
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001287 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001288 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001289 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1290
1291 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001292 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001293 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001294 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001295 "ap.next");
1296 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1297
1298 return AddrTyped;
1299}
1300
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001301bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1302 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1303 assert(Triple.getArch() == llvm::Triple::x86);
1304
1305 switch (Opts.getStructReturnConvention()) {
1306 case CodeGenOptions::SRCK_Default:
1307 break;
1308 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1309 return false;
1310 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1311 return true;
1312 }
1313
1314 if (Triple.isOSDarwin())
1315 return true;
1316
1317 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001318 case llvm::Triple::DragonFly:
1319 case llvm::Triple::FreeBSD:
1320 case llvm::Triple::OpenBSD:
1321 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001322 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001323 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001324 default:
1325 return false;
1326 }
1327}
1328
Charles Davis4ea31ab2010-02-13 15:54:06 +00001329void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1330 llvm::GlobalValue *GV,
1331 CodeGen::CodeGenModule &CGM) const {
1332 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1333 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1334 // Get the LLVM function.
1335 llvm::Function *Fn = cast<llvm::Function>(GV);
1336
1337 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001338 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001339 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001340 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1341 llvm::AttributeSet::get(CGM.getLLVMContext(),
1342 llvm::AttributeSet::FunctionIndex,
1343 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001344 }
1345 }
1346}
1347
John McCallbeec5a02010-03-06 00:35:14 +00001348bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1349 CodeGen::CodeGenFunction &CGF,
1350 llvm::Value *Address) const {
1351 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001352
Chris Lattnerece04092012-02-07 00:39:47 +00001353 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001354
John McCallbeec5a02010-03-06 00:35:14 +00001355 // 0-7 are the eight integer registers; the order is different
1356 // on Darwin (for EH), but the range is the same.
1357 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001358 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001359
John McCallc8e01702013-04-16 22:48:15 +00001360 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001361 // 12-16 are st(0..4). Not sure why we stop at 4.
1362 // These have size 16, which is sizeof(long double) on
1363 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001364 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001365 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001366
John McCallbeec5a02010-03-06 00:35:14 +00001367 } else {
1368 // 9 is %eflags, which doesn't get a size on Darwin for some
1369 // reason.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001370 Builder.CreateStore(
1371 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9));
John McCallbeec5a02010-03-06 00:35:14 +00001372
1373 // 11-16 are st(0..5). Not sure why we stop at 5.
1374 // These have size 12, which is sizeof(long double) on
1375 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001376 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001377 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1378 }
John McCallbeec5a02010-03-06 00:35:14 +00001379
1380 return false;
1381}
1382
Chris Lattner0cf24192010-06-28 20:05:43 +00001383//===----------------------------------------------------------------------===//
1384// X86-64 ABI Implementation
1385//===----------------------------------------------------------------------===//
1386
1387
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001388namespace {
1389/// X86_64ABIInfo - The X86_64 ABI information.
1390class X86_64ABIInfo : public ABIInfo {
1391 enum Class {
1392 Integer = 0,
1393 SSE,
1394 SSEUp,
1395 X87,
1396 X87Up,
1397 ComplexX87,
1398 NoClass,
1399 Memory
1400 };
1401
1402 /// merge - Implement the X86_64 ABI merging algorithm.
1403 ///
1404 /// Merge an accumulating classification \arg Accum with a field
1405 /// classification \arg Field.
1406 ///
1407 /// \param Accum - The accumulating classification. This should
1408 /// always be either NoClass or the result of a previous merge
1409 /// call. In addition, this should never be Memory (the caller
1410 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001411 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001412
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001413 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1414 ///
1415 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1416 /// final MEMORY or SSE classes when necessary.
1417 ///
1418 /// \param AggregateSize - The size of the current aggregate in
1419 /// the classification process.
1420 ///
1421 /// \param Lo - The classification for the parts of the type
1422 /// residing in the low word of the containing object.
1423 ///
1424 /// \param Hi - The classification for the parts of the type
1425 /// residing in the higher words of the containing object.
1426 ///
1427 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1428
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001429 /// classify - Determine the x86_64 register classes in which the
1430 /// given type T should be passed.
1431 ///
1432 /// \param Lo - The classification for the parts of the type
1433 /// residing in the low word of the containing object.
1434 ///
1435 /// \param Hi - The classification for the parts of the type
1436 /// residing in the high word of the containing object.
1437 ///
1438 /// \param OffsetBase - The bit offset of this type in the
1439 /// containing object. Some parameters are classified different
1440 /// depending on whether they straddle an eightbyte boundary.
1441 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001442 /// \param isNamedArg - Whether the argument in question is a "named"
1443 /// argument, as used in AMD64-ABI 3.5.7.
1444 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001445 /// If a word is unused its result will be NoClass; if a type should
1446 /// be passed in Memory then at least the classification of \arg Lo
1447 /// will be Memory.
1448 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001449 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001450 ///
1451 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1452 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001453 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1454 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001455
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001456 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001457 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1458 unsigned IROffset, QualType SourceTy,
1459 unsigned SourceOffset) const;
1460 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1461 unsigned IROffset, QualType SourceTy,
1462 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001463
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001464 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001465 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001466 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001467
1468 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001469 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001470 ///
1471 /// \param freeIntRegs - The number of free integer registers remaining
1472 /// available.
1473 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001474
Chris Lattner458b2aa2010-07-29 02:16:43 +00001475 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001476
Bill Wendling5cd41c42010-10-18 03:41:31 +00001477 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001478 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001479 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001480 unsigned &neededSSE,
1481 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001482
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001483 bool IsIllegalVectorType(QualType Ty) const;
1484
John McCalle0fda732011-04-21 01:20:55 +00001485 /// The 0.98 ABI revision clarified a lot of ambiguities,
1486 /// unfortunately in ways that were not always consistent with
1487 /// certain previous compilers. In particular, platforms which
1488 /// required strict binary compatibility with older versions of GCC
1489 /// may need to exempt themselves.
1490 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001491 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001492 }
1493
Derek Schuffc7dd7222012-10-11 15:52:22 +00001494 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1495 // 64-bit hardware.
1496 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001497
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001498public:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001499 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT) :
1500 ABIInfo(CGT),
Derek Schuff8a872f32012-10-11 18:21:13 +00001501 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001502 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001503
John McCalla729c622012-02-17 03:33:10 +00001504 bool isPassedUsingAVXType(QualType type) const {
1505 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001506 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001507 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1508 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001509 if (info.isDirect()) {
1510 llvm::Type *ty = info.getCoerceToType();
1511 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1512 return (vectorTy->getBitWidth() > 128);
1513 }
1514 return false;
1515 }
1516
Craig Topper4f12f102014-03-12 06:41:41 +00001517 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001518
Craig Topper4f12f102014-03-12 06:41:41 +00001519 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1520 CodeGenFunction &CGF) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001521
1522 bool has64BitPointers() const {
1523 return Has64BitPointers;
1524 }
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001525
1526 bool hasAVX() const {
1527 return getTarget().getABI() == "avx";
1528 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001529};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001530
Chris Lattner04dc9572010-08-31 16:44:54 +00001531/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001532class WinX86_64ABIInfo : public ABIInfo {
1533
Reid Kleckner80944df2014-10-31 22:00:51 +00001534 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1535 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001536
Chris Lattner04dc9572010-08-31 16:44:54 +00001537public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001538 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1539
Craig Topper4f12f102014-03-12 06:41:41 +00001540 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001541
Craig Topper4f12f102014-03-12 06:41:41 +00001542 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1543 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001544
1545 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1546 // FIXME: Assumes vectorcall is in use.
1547 return isX86VectorTypeForVectorCall(getContext(), Ty);
1548 }
1549
1550 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1551 uint64_t NumMembers) const override {
1552 // FIXME: Assumes vectorcall is in use.
1553 return isX86VectorCallAggregateSmallEnough(NumMembers);
1554 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001555};
1556
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001557class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1558public:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001559 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1560 : TargetCodeGenInfo(new X86_64ABIInfo(CGT)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001561
John McCalla729c622012-02-17 03:33:10 +00001562 const X86_64ABIInfo &getABIInfo() const {
1563 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1564 }
1565
Craig Topper4f12f102014-03-12 06:41:41 +00001566 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001567 return 7;
1568 }
1569
1570 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001571 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001572 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001573
John McCall943fae92010-05-27 06:19:26 +00001574 // 0-15 are the 16 integer registers.
1575 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001576 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001577 return false;
1578 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001579
Jay Foad7c57be32011-07-11 09:56:20 +00001580 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001581 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001582 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001583 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1584 }
1585
John McCalla729c622012-02-17 03:33:10 +00001586 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001587 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001588 // The default CC on x86-64 sets %al to the number of SSA
1589 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001590 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001591 // that when AVX types are involved: the ABI explicitly states it is
1592 // undefined, and it doesn't work in practice because of how the ABI
1593 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001594 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001595 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001596 for (CallArgList::const_iterator
1597 it = args.begin(), ie = args.end(); it != ie; ++it) {
1598 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1599 HasAVXType = true;
1600 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001601 }
1602 }
John McCalla729c622012-02-17 03:33:10 +00001603
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001604 if (!HasAVXType)
1605 return true;
1606 }
John McCallcbc038a2011-09-21 08:08:30 +00001607
John McCalla729c622012-02-17 03:33:10 +00001608 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001609 }
1610
Craig Topper4f12f102014-03-12 06:41:41 +00001611 llvm::Constant *
1612 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001613 unsigned Sig;
1614 if (getABIInfo().has64BitPointers())
1615 Sig = (0xeb << 0) | // jmp rel8
1616 (0x0a << 8) | // .+0x0c
1617 ('F' << 16) |
1618 ('T' << 24);
1619 else
1620 Sig = (0xeb << 0) | // jmp rel8
1621 (0x06 << 8) | // .+0x08
1622 ('F' << 16) |
1623 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001624 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1625 }
1626
Alexander Musman09184fe2014-09-30 05:29:28 +00001627 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001628 return getABIInfo().hasAVX() ? 32 : 16;
Alexander Musman09184fe2014-09-30 05:29:28 +00001629 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001630};
1631
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001632class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1633public:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001634 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1635 : X86_64TargetCodeGenInfo(CGT) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001636
1637 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001638 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001639 Opt = "\01";
1640 Opt += Lib;
1641 }
1642};
1643
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001644static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001645 // If the argument does not end in .lib, automatically add the suffix.
1646 // If the argument contains a space, enclose it in quotes.
1647 // This matches the behavior of MSVC.
1648 bool Quote = (Lib.find(" ") != StringRef::npos);
1649 std::string ArgStr = Quote ? "\"" : "";
1650 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001651 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001652 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001653 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001654 return ArgStr;
1655}
1656
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001657class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1658public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001659 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1660 bool d, bool p, bool w, unsigned RegParms)
1661 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001662
Hans Wennborg77dc2362015-01-20 19:45:50 +00001663 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1664 CodeGen::CodeGenModule &CGM) const override;
1665
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001666 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001667 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001668 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001669 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001670 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001671
1672 void getDetectMismatchOption(llvm::StringRef Name,
1673 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001674 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001675 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001676 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001677};
1678
Hans Wennborg77dc2362015-01-20 19:45:50 +00001679static void addStackProbeSizeTargetAttribute(const Decl *D,
1680 llvm::GlobalValue *GV,
1681 CodeGen::CodeGenModule &CGM) {
1682 if (isa<FunctionDecl>(D)) {
1683 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1684 llvm::Function *Fn = cast<llvm::Function>(GV);
1685
1686 Fn->addFnAttr("stack-probe-size", llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
1687 }
1688 }
1689}
1690
1691void WinX86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1692 llvm::GlobalValue *GV,
1693 CodeGen::CodeGenModule &CGM) const {
1694 X86_32TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1695
1696 addStackProbeSizeTargetAttribute(D, GV, CGM);
1697}
1698
Chris Lattner04dc9572010-08-31 16:44:54 +00001699class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001700 bool hasAVX() const { return getABIInfo().getTarget().getABI() == "avx"; }
1701
Chris Lattner04dc9572010-08-31 16:44:54 +00001702public:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001703 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1704 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001705
Hans Wennborg77dc2362015-01-20 19:45:50 +00001706 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1707 CodeGen::CodeGenModule &CGM) const override;
1708
Craig Topper4f12f102014-03-12 06:41:41 +00001709 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001710 return 7;
1711 }
1712
1713 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001714 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001715 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001716
Chris Lattner04dc9572010-08-31 16:44:54 +00001717 // 0-15 are the 16 integer registers.
1718 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001719 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001720 return false;
1721 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001722
1723 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001724 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001725 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001726 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001727 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001728
1729 void getDetectMismatchOption(llvm::StringRef Name,
1730 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001731 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001732 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001733 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001734
1735 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001736 return hasAVX() ? 32 : 16;
Alexander Musman09184fe2014-09-30 05:29:28 +00001737 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001738};
1739
Hans Wennborg77dc2362015-01-20 19:45:50 +00001740void WinX86_64TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1741 llvm::GlobalValue *GV,
1742 CodeGen::CodeGenModule &CGM) const {
1743 TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1744
1745 addStackProbeSizeTargetAttribute(D, GV, CGM);
1746}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001747}
1748
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001749void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1750 Class &Hi) const {
1751 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1752 //
1753 // (a) If one of the classes is Memory, the whole argument is passed in
1754 // memory.
1755 //
1756 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1757 // memory.
1758 //
1759 // (c) If the size of the aggregate exceeds two eightbytes and the first
1760 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1761 // argument is passed in memory. NOTE: This is necessary to keep the
1762 // ABI working for processors that don't support the __m256 type.
1763 //
1764 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1765 //
1766 // Some of these are enforced by the merging logic. Others can arise
1767 // only with unions; for example:
1768 // union { _Complex double; unsigned; }
1769 //
1770 // Note that clauses (b) and (c) were added in 0.98.
1771 //
1772 if (Hi == Memory)
1773 Lo = Memory;
1774 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1775 Lo = Memory;
1776 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1777 Lo = Memory;
1778 if (Hi == SSEUp && Lo != SSE)
1779 Hi = SSE;
1780}
1781
Chris Lattnerd776fb12010-06-28 21:43:59 +00001782X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001783 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1784 // classified recursively so that always two fields are
1785 // considered. The resulting class is calculated according to
1786 // the classes of the fields in the eightbyte:
1787 //
1788 // (a) If both classes are equal, this is the resulting class.
1789 //
1790 // (b) If one of the classes is NO_CLASS, the resulting class is
1791 // the other class.
1792 //
1793 // (c) If one of the classes is MEMORY, the result is the MEMORY
1794 // class.
1795 //
1796 // (d) If one of the classes is INTEGER, the result is the
1797 // INTEGER.
1798 //
1799 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1800 // MEMORY is used as class.
1801 //
1802 // (f) Otherwise class SSE is used.
1803
1804 // Accum should never be memory (we should have returned) or
1805 // ComplexX87 (because this cannot be passed in a structure).
1806 assert((Accum != Memory && Accum != ComplexX87) &&
1807 "Invalid accumulated classification during merge.");
1808 if (Accum == Field || Field == NoClass)
1809 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001810 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001811 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001812 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001813 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001814 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001815 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001816 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1817 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001818 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001819 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001820}
1821
Chris Lattner5c740f12010-06-30 19:14:05 +00001822void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001823 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001824 // FIXME: This code can be simplified by introducing a simple value class for
1825 // Class pairs with appropriate constructor methods for the various
1826 // situations.
1827
1828 // FIXME: Some of the split computations are wrong; unaligned vectors
1829 // shouldn't be passed in registers for example, so there is no chance they
1830 // can straddle an eightbyte. Verify & simplify.
1831
1832 Lo = Hi = NoClass;
1833
1834 Class &Current = OffsetBase < 64 ? Lo : Hi;
1835 Current = Memory;
1836
John McCall9dd450b2009-09-21 23:43:11 +00001837 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001838 BuiltinType::Kind k = BT->getKind();
1839
1840 if (k == BuiltinType::Void) {
1841 Current = NoClass;
1842 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1843 Lo = Integer;
1844 Hi = Integer;
1845 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1846 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001847 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1848 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001849 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001850 Current = SSE;
1851 } else if (k == BuiltinType::LongDouble) {
1852 Lo = X87;
1853 Hi = X87Up;
1854 }
1855 // FIXME: _Decimal32 and _Decimal64 are SSE.
1856 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001857 return;
1858 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001859
Chris Lattnerd776fb12010-06-28 21:43:59 +00001860 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001861 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001862 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001863 return;
1864 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001865
Chris Lattnerd776fb12010-06-28 21:43:59 +00001866 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001867 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001868 return;
1869 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001870
Chris Lattnerd776fb12010-06-28 21:43:59 +00001871 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001872 if (Ty->isMemberFunctionPointerType()) {
1873 if (Has64BitPointers) {
1874 // If Has64BitPointers, this is an {i64, i64}, so classify both
1875 // Lo and Hi now.
1876 Lo = Hi = Integer;
1877 } else {
1878 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1879 // straddles an eightbyte boundary, Hi should be classified as well.
1880 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1881 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1882 if (EB_FuncPtr != EB_ThisAdj) {
1883 Lo = Hi = Integer;
1884 } else {
1885 Current = Integer;
1886 }
1887 }
1888 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001889 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001890 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001891 return;
1892 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001893
Chris Lattnerd776fb12010-06-28 21:43:59 +00001894 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001895 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001896 if (Size == 32) {
1897 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1898 // float> as integer.
1899 Current = Integer;
1900
1901 // If this type crosses an eightbyte boundary, it should be
1902 // split.
1903 uint64_t EB_Real = (OffsetBase) / 64;
1904 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1905 if (EB_Real != EB_Imag)
1906 Hi = Lo;
1907 } else if (Size == 64) {
1908 // gcc passes <1 x double> in memory. :(
1909 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1910 return;
1911
1912 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001913 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001914 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1915 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1916 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001917 Current = Integer;
1918 else
1919 Current = SSE;
1920
1921 // If this type crosses an eightbyte boundary, it should be
1922 // split.
1923 if (OffsetBase && OffsetBase != 64)
1924 Hi = Lo;
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001925 } else if (Size == 128 || (hasAVX() && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001926 // Arguments of 256-bits are split into four eightbyte chunks. The
1927 // least significant one belongs to class SSE and all the others to class
1928 // SSEUP. The original Lo and Hi design considers that types can't be
1929 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1930 // This design isn't correct for 256-bits, but since there're no cases
1931 // where the upper parts would need to be inspected, avoid adding
1932 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001933 //
1934 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1935 // registers if they are "named", i.e. not part of the "..." of a
1936 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001937 Lo = SSE;
1938 Hi = SSEUp;
1939 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001940 return;
1941 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001942
Chris Lattnerd776fb12010-06-28 21:43:59 +00001943 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001944 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001945
Chris Lattner2b037972010-07-29 02:01:43 +00001946 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001947 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001948 if (Size <= 64)
1949 Current = Integer;
1950 else if (Size <= 128)
1951 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001952 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001953 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001954 else if (ET == getContext().DoubleTy ||
1955 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001956 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001957 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001958 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001959 Current = ComplexX87;
1960
1961 // If this complex type crosses an eightbyte boundary then it
1962 // should be split.
1963 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001964 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001965 if (Hi == NoClass && EB_Real != EB_Imag)
1966 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001967
Chris Lattnerd776fb12010-06-28 21:43:59 +00001968 return;
1969 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001970
Chris Lattner2b037972010-07-29 02:01:43 +00001971 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001972 // Arrays are treated like structures.
1973
Chris Lattner2b037972010-07-29 02:01:43 +00001974 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001975
1976 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001977 // than four eightbytes, ..., it has class MEMORY.
1978 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001979 return;
1980
1981 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1982 // fields, it has class MEMORY.
1983 //
1984 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001985 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001986 return;
1987
1988 // Otherwise implement simplified merge. We could be smarter about
1989 // this, but it isn't worth it and would be harder to verify.
1990 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001991 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001992 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001993
1994 // The only case a 256-bit wide vector could be used is when the array
1995 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1996 // to work for sizes wider than 128, early check and fallback to memory.
1997 if (Size > 128 && EltSize != 256)
1998 return;
1999
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002000 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2001 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002002 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002003 Lo = merge(Lo, FieldLo);
2004 Hi = merge(Hi, FieldHi);
2005 if (Lo == Memory || Hi == Memory)
2006 break;
2007 }
2008
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002009 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002010 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002011 return;
2012 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002013
Chris Lattnerd776fb12010-06-28 21:43:59 +00002014 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002015 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002016
2017 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002018 // than four eightbytes, ..., it has class MEMORY.
2019 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002020 return;
2021
Anders Carlsson20759ad2009-09-16 15:53:40 +00002022 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2023 // copy constructor or a non-trivial destructor, it is passed by invisible
2024 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002025 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002026 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002027
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002028 const RecordDecl *RD = RT->getDecl();
2029
2030 // Assume variable sized types are passed in memory.
2031 if (RD->hasFlexibleArrayMember())
2032 return;
2033
Chris Lattner2b037972010-07-29 02:01:43 +00002034 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002035
2036 // Reset Lo class, this will be recomputed.
2037 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002038
2039 // If this is a C++ record, classify the bases first.
2040 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002041 for (const auto &I : CXXRD->bases()) {
2042 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002043 "Unexpected base class!");
2044 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002045 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002046
2047 // Classify this field.
2048 //
2049 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2050 // single eightbyte, each is classified separately. Each eightbyte gets
2051 // initialized to class NO_CLASS.
2052 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002053 uint64_t Offset =
2054 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002055 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002056 Lo = merge(Lo, FieldLo);
2057 Hi = merge(Hi, FieldHi);
2058 if (Lo == Memory || Hi == Memory)
2059 break;
2060 }
2061 }
2062
2063 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002064 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002065 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002066 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002067 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2068 bool BitField = i->isBitField();
2069
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002070 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2071 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002072 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002073 // The only case a 256-bit wide vector could be used is when the struct
2074 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2075 // to work for sizes wider than 128, early check and fallback to memory.
2076 //
2077 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2078 Lo = Memory;
2079 return;
2080 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002081 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002082 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002083 Lo = Memory;
2084 return;
2085 }
2086
2087 // Classify this field.
2088 //
2089 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2090 // exceeds a single eightbyte, each is classified
2091 // separately. Each eightbyte gets initialized to class
2092 // NO_CLASS.
2093 Class FieldLo, FieldHi;
2094
2095 // Bit-fields require special handling, they do not force the
2096 // structure to be passed in memory even if unaligned, and
2097 // therefore they can straddle an eightbyte.
2098 if (BitField) {
2099 // Ignore padding bit-fields.
2100 if (i->isUnnamedBitfield())
2101 continue;
2102
2103 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002104 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002105
2106 uint64_t EB_Lo = Offset / 64;
2107 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002108
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002109 if (EB_Lo) {
2110 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2111 FieldLo = NoClass;
2112 FieldHi = Integer;
2113 } else {
2114 FieldLo = Integer;
2115 FieldHi = EB_Hi ? Integer : NoClass;
2116 }
2117 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002118 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002119 Lo = merge(Lo, FieldLo);
2120 Hi = merge(Hi, FieldHi);
2121 if (Lo == Memory || Hi == Memory)
2122 break;
2123 }
2124
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002125 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002126 }
2127}
2128
Chris Lattner22a931e2010-06-29 06:01:59 +00002129ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002130 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2131 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002132 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002133 // Treat an enum type as its underlying type.
2134 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2135 Ty = EnumTy->getDecl()->getIntegerType();
2136
2137 return (Ty->isPromotableIntegerType() ?
2138 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2139 }
2140
2141 return ABIArgInfo::getIndirect(0);
2142}
2143
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002144bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2145 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2146 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00002147 unsigned LargestVector = hasAVX() ? 256 : 128;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002148 if (Size <= 64 || Size > LargestVector)
2149 return true;
2150 }
2151
2152 return false;
2153}
2154
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002155ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2156 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002157 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2158 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002159 //
2160 // This assumption is optimistic, as there could be free registers available
2161 // when we need to pass this argument in memory, and LLVM could try to pass
2162 // the argument in the free register. This does not seem to happen currently,
2163 // but this code would be much safer if we could mark the argument with
2164 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002165 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002166 // Treat an enum type as its underlying type.
2167 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2168 Ty = EnumTy->getDecl()->getIntegerType();
2169
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002170 return (Ty->isPromotableIntegerType() ?
2171 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002172 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002173
Mark Lacey3825e832013-10-06 01:33:34 +00002174 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002175 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002176
Chris Lattner44c2b902011-05-22 23:21:23 +00002177 // Compute the byval alignment. We specify the alignment of the byval in all
2178 // cases so that the mid-level optimizer knows the alignment of the byval.
2179 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002180
2181 // Attempt to avoid passing indirect results using byval when possible. This
2182 // is important for good codegen.
2183 //
2184 // We do this by coercing the value into a scalar type which the backend can
2185 // handle naturally (i.e., without using byval).
2186 //
2187 // For simplicity, we currently only do this when we have exhausted all of the
2188 // free integer registers. Doing this when there are free integer registers
2189 // would require more care, as we would have to ensure that the coerced value
2190 // did not claim the unused register. That would require either reording the
2191 // arguments to the function (so that any subsequent inreg values came first),
2192 // or only doing this optimization when there were no following arguments that
2193 // might be inreg.
2194 //
2195 // We currently expect it to be rare (particularly in well written code) for
2196 // arguments to be passed on the stack when there are still free integer
2197 // registers available (this would typically imply large structs being passed
2198 // by value), so this seems like a fair tradeoff for now.
2199 //
2200 // We can revisit this if the backend grows support for 'onstack' parameter
2201 // attributes. See PR12193.
2202 if (freeIntRegs == 0) {
2203 uint64_t Size = getContext().getTypeSize(Ty);
2204
2205 // If this type fits in an eightbyte, coerce it into the matching integral
2206 // type, which will end up on the stack (with alignment 8).
2207 if (Align == 8 && Size <= 64)
2208 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2209 Size));
2210 }
2211
Chris Lattner44c2b902011-05-22 23:21:23 +00002212 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002213}
2214
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002215/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2216/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002217llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002218 // Wrapper structs/arrays that only contain vectors are passed just like
2219 // vectors; strip them off if present.
2220 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2221 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002222
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002223 llvm::Type *IRType = CGT.ConvertType(Ty);
Benjamin Kramer83b1bf32015-03-02 16:09:24 +00002224 assert(isa<llvm::VectorType>(IRType) &&
2225 "Trying to return a non-vector type in a vector register!");
2226 return IRType;
Chris Lattner4200fe42010-07-29 04:56:46 +00002227}
2228
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002229/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2230/// is known to either be off the end of the specified type or being in
2231/// alignment padding. The user type specified is known to be at most 128 bits
2232/// in size, and have passed through X86_64ABIInfo::classify with a successful
2233/// classification that put one of the two halves in the INTEGER class.
2234///
2235/// It is conservatively correct to return false.
2236static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2237 unsigned EndBit, ASTContext &Context) {
2238 // If the bytes being queried are off the end of the type, there is no user
2239 // data hiding here. This handles analysis of builtins, vectors and other
2240 // types that don't contain interesting padding.
2241 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2242 if (TySize <= StartBit)
2243 return true;
2244
Chris Lattner98076a22010-07-29 07:43:55 +00002245 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2246 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2247 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2248
2249 // Check each element to see if the element overlaps with the queried range.
2250 for (unsigned i = 0; i != NumElts; ++i) {
2251 // If the element is after the span we care about, then we're done..
2252 unsigned EltOffset = i*EltSize;
2253 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002254
Chris Lattner98076a22010-07-29 07:43:55 +00002255 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2256 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2257 EndBit-EltOffset, Context))
2258 return false;
2259 }
2260 // If it overlaps no elements, then it is safe to process as padding.
2261 return true;
2262 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002263
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002264 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2265 const RecordDecl *RD = RT->getDecl();
2266 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002267
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002268 // If this is a C++ record, check the bases first.
2269 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002270 for (const auto &I : CXXRD->bases()) {
2271 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002272 "Unexpected base class!");
2273 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002274 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002275
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002276 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002277 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002278 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002279
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002280 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002281 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002282 EndBit-BaseOffset, Context))
2283 return false;
2284 }
2285 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002286
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002287 // Verify that no field has data that overlaps the region of interest. Yes
2288 // this could be sped up a lot by being smarter about queried fields,
2289 // however we're only looking at structs up to 16 bytes, so we don't care
2290 // much.
2291 unsigned idx = 0;
2292 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2293 i != e; ++i, ++idx) {
2294 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002295
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002296 // If we found a field after the region we care about, then we're done.
2297 if (FieldOffset >= EndBit) break;
2298
2299 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2300 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2301 Context))
2302 return false;
2303 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002304
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002305 // If nothing in this record overlapped the area of interest, then we're
2306 // clean.
2307 return true;
2308 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002309
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002310 return false;
2311}
2312
Chris Lattnere556a712010-07-29 18:39:32 +00002313/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2314/// float member at the specified offset. For example, {int,{float}} has a
2315/// float at offset 4. It is conservatively correct for this routine to return
2316/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002317static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002318 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002319 // Base case if we find a float.
2320 if (IROffset == 0 && IRType->isFloatTy())
2321 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002322
Chris Lattnere556a712010-07-29 18:39:32 +00002323 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002324 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002325 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2326 unsigned Elt = SL->getElementContainingOffset(IROffset);
2327 IROffset -= SL->getElementOffset(Elt);
2328 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2329 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002330
Chris Lattnere556a712010-07-29 18:39:32 +00002331 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002332 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2333 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002334 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2335 IROffset -= IROffset/EltSize*EltSize;
2336 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2337 }
2338
2339 return false;
2340}
2341
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002342
2343/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2344/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002345llvm::Type *X86_64ABIInfo::
2346GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002347 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002348 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002349 // pass as float if the last 4 bytes is just padding. This happens for
2350 // structs that contain 3 floats.
2351 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2352 SourceOffset*8+64, getContext()))
2353 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002354
Chris Lattnere556a712010-07-29 18:39:32 +00002355 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2356 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2357 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002358 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2359 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002360 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002361
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002362 return llvm::Type::getDoubleTy(getVMContext());
2363}
2364
2365
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002366/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2367/// an 8-byte GPR. This means that we either have a scalar or we are talking
2368/// about the high or low part of an up-to-16-byte struct. This routine picks
2369/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002370/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2371/// etc).
2372///
2373/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2374/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2375/// the 8-byte value references. PrefType may be null.
2376///
Alp Toker9907f082014-07-09 14:06:35 +00002377/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002378/// an offset into this that we're processing (which is always either 0 or 8).
2379///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002380llvm::Type *X86_64ABIInfo::
2381GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002382 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002383 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2384 // returning an 8-byte unit starting with it. See if we can safely use it.
2385 if (IROffset == 0) {
2386 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002387 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2388 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002389 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002390
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002391 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2392 // goodness in the source type is just tail padding. This is allowed to
2393 // kick in for struct {double,int} on the int, but not on
2394 // struct{double,int,int} because we wouldn't return the second int. We
2395 // have to do this analysis on the source type because we can't depend on
2396 // unions being lowered a specific way etc.
2397 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002398 IRType->isIntegerTy(32) ||
2399 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2400 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2401 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002402
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002403 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2404 SourceOffset*8+64, getContext()))
2405 return IRType;
2406 }
2407 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002408
Chris Lattner2192fe52011-07-18 04:24:23 +00002409 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002410 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002411 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002412 if (IROffset < SL->getSizeInBytes()) {
2413 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2414 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002415
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002416 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2417 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002418 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002419 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002420
Chris Lattner2192fe52011-07-18 04:24:23 +00002421 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002422 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002423 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002424 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002425 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2426 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002427 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002428
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002429 // Okay, we don't have any better idea of what to pass, so we pass this in an
2430 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002431 unsigned TySizeInBytes =
2432 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002433
Chris Lattner3f763422010-07-29 17:34:39 +00002434 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002435
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002436 // It is always safe to classify this as an integer type up to i64 that
2437 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002438 return llvm::IntegerType::get(getVMContext(),
2439 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002440}
2441
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002442
2443/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2444/// be used as elements of a two register pair to pass or return, return a
2445/// first class aggregate to represent them. For example, if the low part of
2446/// a by-value argument should be passed as i32* and the high part as float,
2447/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002448static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002449GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002450 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002451 // In order to correctly satisfy the ABI, we need to the high part to start
2452 // at offset 8. If the high and low parts we inferred are both 4-byte types
2453 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2454 // the second element at offset 8. Check for this:
2455 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2456 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002457 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002458 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002459
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002460 // To handle this, we have to increase the size of the low part so that the
2461 // second element will start at an 8 byte offset. We can't increase the size
2462 // of the second element because it might make us access off the end of the
2463 // struct.
2464 if (HiStart != 8) {
2465 // There are only two sorts of types the ABI generation code can produce for
2466 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2467 // Promote these to a larger type.
2468 if (Lo->isFloatTy())
2469 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2470 else {
2471 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2472 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2473 }
2474 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002475
Reid Kleckneree7cf842014-12-01 22:02:27 +00002476 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002477
2478
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002479 // Verify that the second element is at an 8-byte offset.
2480 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2481 "Invalid x86-64 argument pair!");
2482 return Result;
2483}
2484
Chris Lattner31faff52010-07-28 23:06:14 +00002485ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002486classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002487 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2488 // classification algorithm.
2489 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002490 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002491
2492 // Check some invariants.
2493 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002494 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2495
Craig Topper8a13c412014-05-21 05:09:00 +00002496 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002497 switch (Lo) {
2498 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002499 if (Hi == NoClass)
2500 return ABIArgInfo::getIgnore();
2501 // If the low part is just padding, it takes no register, leave ResType
2502 // null.
2503 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2504 "Unknown missing lo part");
2505 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002506
2507 case SSEUp:
2508 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002509 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002510
2511 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2512 // hidden argument.
2513 case Memory:
2514 return getIndirectReturnResult(RetTy);
2515
2516 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2517 // available register of the sequence %rax, %rdx is used.
2518 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002519 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002520
Chris Lattner1f3a0632010-07-29 21:42:50 +00002521 // If we have a sign or zero extended integer, make sure to return Extend
2522 // so that the parameter gets the right LLVM IR attributes.
2523 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2524 // Treat an enum type as its underlying type.
2525 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2526 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002527
Chris Lattner1f3a0632010-07-29 21:42:50 +00002528 if (RetTy->isIntegralOrEnumerationType() &&
2529 RetTy->isPromotableIntegerType())
2530 return ABIArgInfo::getExtend();
2531 }
Chris Lattner31faff52010-07-28 23:06:14 +00002532 break;
2533
2534 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2535 // available SSE register of the sequence %xmm0, %xmm1 is used.
2536 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002537 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002538 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002539
2540 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2541 // returned on the X87 stack in %st0 as 80-bit x87 number.
2542 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002543 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002544 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002545
2546 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2547 // part of the value is returned in %st0 and the imaginary part in
2548 // %st1.
2549 case ComplexX87:
2550 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002551 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002552 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002553 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002554 break;
2555 }
2556
Craig Topper8a13c412014-05-21 05:09:00 +00002557 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002558 switch (Hi) {
2559 // Memory was handled previously and X87 should
2560 // never occur as a hi class.
2561 case Memory:
2562 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002563 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002564
2565 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002566 case NoClass:
2567 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002568
Chris Lattner52b3c132010-09-01 00:20:33 +00002569 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002570 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002571 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2572 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002573 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002574 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002575 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002576 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2577 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002578 break;
2579
2580 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002581 // is passed in the next available eightbyte chunk if the last used
2582 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002583 //
Chris Lattner57540c52011-04-15 05:22:18 +00002584 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002585 case SSEUp:
2586 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002587 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002588 break;
2589
2590 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2591 // returned together with the previous X87 value in %st0.
2592 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002593 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002594 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002595 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002596 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002597 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002598 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002599 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2600 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002601 }
Chris Lattner31faff52010-07-28 23:06:14 +00002602 break;
2603 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002604
Chris Lattner52b3c132010-09-01 00:20:33 +00002605 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002606 // known to pass in the high eightbyte of the result. We do this by forming a
2607 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002608 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002609 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002610
Chris Lattner1f3a0632010-07-29 21:42:50 +00002611 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002612}
2613
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002614ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002615 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2616 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002617 const
2618{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002619 Ty = useFirstFieldIfTransparentUnion(Ty);
2620
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002621 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002622 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002623
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002624 // Check some invariants.
2625 // FIXME: Enforce these by construction.
2626 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002627 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2628
2629 neededInt = 0;
2630 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002631 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002632 switch (Lo) {
2633 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002634 if (Hi == NoClass)
2635 return ABIArgInfo::getIgnore();
2636 // If the low part is just padding, it takes no register, leave ResType
2637 // null.
2638 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2639 "Unknown missing lo part");
2640 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002641
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002642 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2643 // on the stack.
2644 case Memory:
2645
2646 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2647 // COMPLEX_X87, it is passed in memory.
2648 case X87:
2649 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002650 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002651 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002652 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002653
2654 case SSEUp:
2655 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002656 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002657
2658 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2659 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2660 // and %r9 is used.
2661 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002662 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002663
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002664 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002665 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002666
2667 // If we have a sign or zero extended integer, make sure to return Extend
2668 // so that the parameter gets the right LLVM IR attributes.
2669 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2670 // Treat an enum type as its underlying type.
2671 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2672 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002673
Chris Lattner1f3a0632010-07-29 21:42:50 +00002674 if (Ty->isIntegralOrEnumerationType() &&
2675 Ty->isPromotableIntegerType())
2676 return ABIArgInfo::getExtend();
2677 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002678
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002679 break;
2680
2681 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2682 // available SSE register is used, the registers are taken in the
2683 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002684 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002685 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002686 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002687 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002688 break;
2689 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002690 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002691
Craig Topper8a13c412014-05-21 05:09:00 +00002692 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002693 switch (Hi) {
2694 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002695 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002696 // which is passed in memory.
2697 case Memory:
2698 case X87:
2699 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002700 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002701
2702 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002703
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002704 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002705 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002706 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002707 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002708
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002709 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2710 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002711 break;
2712
2713 // X87Up generally doesn't occur here (long double is passed in
2714 // memory), except in situations involving unions.
2715 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002716 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002717 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002718
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002719 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2720 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002721
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002722 ++neededSSE;
2723 break;
2724
2725 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2726 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002727 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002728 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002729 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002730 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002731 break;
2732 }
2733
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002734 // If a high part was specified, merge it together with the low part. It is
2735 // known to pass in the high eightbyte of the result. We do this by forming a
2736 // first class struct aggregate with the high and low part: {low, high}
2737 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002738 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002739
Chris Lattner1f3a0632010-07-29 21:42:50 +00002740 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002741}
2742
Chris Lattner22326a12010-07-29 02:31:05 +00002743void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002744
Reid Kleckner40ca9132014-05-13 22:05:45 +00002745 if (!getCXXABI().classifyReturnType(FI))
2746 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002747
2748 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002749 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002750
2751 // If the return value is indirect, then the hidden argument is consuming one
2752 // integer register.
2753 if (FI.getReturnInfo().isIndirect())
2754 --freeIntRegs;
2755
Peter Collingbournef7706832014-12-12 23:41:25 +00002756 // The chain argument effectively gives us another free register.
2757 if (FI.isChainCall())
2758 ++freeIntRegs;
2759
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002760 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002761 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2762 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002763 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002764 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002765 it != ie; ++it, ++ArgNo) {
2766 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002767
Bill Wendling9987c0e2010-10-18 23:51:38 +00002768 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002769 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002770 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002771
2772 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2773 // eightbyte of an argument, the whole argument is passed on the
2774 // stack. If registers have already been assigned for some
2775 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002776 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002777 freeIntRegs -= neededInt;
2778 freeSSERegs -= neededSSE;
2779 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002780 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002781 }
2782 }
2783}
2784
2785static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2786 QualType Ty,
2787 CodeGenFunction &CGF) {
David Blaikie2e804282015-04-05 22:47:07 +00002788 llvm::Value *overflow_arg_area_p = CGF.Builder.CreateStructGEP(
2789 nullptr, VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002790 llvm::Value *overflow_arg_area =
2791 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2792
2793 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2794 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002795 // It isn't stated explicitly in the standard, but in practice we use
2796 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002797 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2798 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002799 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002800 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002801 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002802 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2803 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002804 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002805 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002806 overflow_arg_area =
2807 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2808 overflow_arg_area->getType(),
2809 "overflow_arg_area.align");
2810 }
2811
2812 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002813 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002814 llvm::Value *Res =
2815 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002816 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002817
2818 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2819 // l->overflow_arg_area + sizeof(type).
2820 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2821 // an 8 byte boundary.
2822
2823 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002824 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002825 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002826 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2827 "overflow_arg_area.next");
2828 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2829
2830 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2831 return Res;
2832}
2833
2834llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2835 CodeGenFunction &CGF) const {
2836 // Assume that va_list type is correct; should be pointer to LLVM type:
2837 // struct {
2838 // i32 gp_offset;
2839 // i32 fp_offset;
2840 // i8* overflow_arg_area;
2841 // i8* reg_save_area;
2842 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002843 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002844
Chris Lattner9723d6c2010-03-11 18:19:55 +00002845 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002846 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2847 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002848
2849 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2850 // in the registers. If not go to step 7.
2851 if (!neededInt && !neededSSE)
2852 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2853
2854 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2855 // general purpose registers needed to pass type and num_fp to hold
2856 // the number of floating point registers needed.
2857
2858 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2859 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2860 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2861 //
2862 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2863 // register save space).
2864
Craig Topper8a13c412014-05-21 05:09:00 +00002865 llvm::Value *InRegs = nullptr;
2866 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2867 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002868 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002869 gp_offset_p =
2870 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002871 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002872 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2873 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002874 }
2875
2876 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002877 fp_offset_p =
2878 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002879 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2880 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002881 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2882 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002883 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2884 }
2885
2886 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2887 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2888 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2889 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2890
2891 // Emit code to load the value if it was passed in registers.
2892
2893 CGF.EmitBlock(InRegBlock);
2894
2895 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2896 // an offset of l->gp_offset and/or l->fp_offset. This may require
2897 // copying to a temporary location in case the parameter is passed
2898 // in different register classes or requires an alignment greater
2899 // than 8 for general purpose registers and 16 for XMM registers.
2900 //
2901 // FIXME: This really results in shameful code when we end up needing to
2902 // collect arguments from different places; often what should result in a
2903 // simple assembling of a structure from scattered addresses has many more
2904 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002905 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
David Blaikie1ed728c2015-04-05 22:45:47 +00002906 llvm::Value *RegAddr = CGF.Builder.CreateLoad(
2907 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3), "reg_save_area");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002908 if (neededInt && neededSSE) {
2909 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002910 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002911 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002912 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2913 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002914 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002915 llvm::Type *TyLo = ST->getElementType(0);
2916 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002917 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002918 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002919 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2920 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002921 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2922 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002923 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2924 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002925 llvm::Value *V =
2926 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
David Blaikie1ed728c2015-04-05 22:45:47 +00002927 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002928 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
David Blaikie1ed728c2015-04-05 22:45:47 +00002929 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002930
Owen Anderson170229f2009-07-14 23:10:40 +00002931 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002932 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002933 } else if (neededInt) {
2934 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2935 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002936 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002937
2938 // Copy to a temporary if necessary to ensure the appropriate alignment.
2939 std::pair<CharUnits, CharUnits> SizeAlign =
2940 CGF.getContext().getTypeInfoInChars(Ty);
2941 uint64_t TySize = SizeAlign.first.getQuantity();
2942 unsigned TyAlign = SizeAlign.second.getQuantity();
2943 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002944 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2945 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2946 RegAddr = Tmp;
2947 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002948 } else if (neededSSE == 1) {
2949 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2950 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2951 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002952 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002953 assert(neededSSE == 2 && "Invalid number of needed registers!");
2954 // SSE registers are spaced 16 bytes apart in the register save
2955 // area, we need to collect the two eightbytes together.
2956 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002957 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002958 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002959 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002960 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00002961 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002962 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2963 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002964 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2965 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002966 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Chris Lattner0cf24192010-06-28 20:05:43 +00002967 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2968 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002969 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Chris Lattner0cf24192010-06-28 20:05:43 +00002970 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2971 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002972 }
2973
2974 // AMD64-ABI 3.5.7p5: Step 5. Set:
2975 // l->gp_offset = l->gp_offset + num_gp * 8
2976 // l->fp_offset = l->fp_offset + num_fp * 16.
2977 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002978 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002979 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2980 gp_offset_p);
2981 }
2982 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002983 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002984 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2985 fp_offset_p);
2986 }
2987 CGF.EmitBranch(ContBlock);
2988
2989 // Emit code to load the value if it was passed in memory.
2990
2991 CGF.EmitBlock(InMemBlock);
2992 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2993
2994 // Return the appropriate result.
2995
2996 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002997 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002998 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002999 ResAddr->addIncoming(RegAddr, InRegBlock);
3000 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003001 return ResAddr;
3002}
3003
Reid Kleckner80944df2014-10-31 22:00:51 +00003004ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3005 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003006
3007 if (Ty->isVoidType())
3008 return ABIArgInfo::getIgnore();
3009
3010 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3011 Ty = EnumTy->getDecl()->getIntegerType();
3012
Reid Kleckner80944df2014-10-31 22:00:51 +00003013 TypeInfo Info = getContext().getTypeInfo(Ty);
3014 uint64_t Width = Info.Width;
3015 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003016
Reid Kleckner9005f412014-05-02 00:51:20 +00003017 const RecordType *RT = Ty->getAs<RecordType>();
3018 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003019 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003020 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003021 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3022 }
3023
3024 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003025 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3026
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003027 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003028 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003029 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003030 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003031 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003032
Reid Kleckner80944df2014-10-31 22:00:51 +00003033 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3034 // other targets.
3035 const Type *Base = nullptr;
3036 uint64_t NumElts = 0;
3037 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3038 if (FreeSSERegs >= NumElts) {
3039 FreeSSERegs -= NumElts;
3040 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3041 return ABIArgInfo::getDirect();
3042 return ABIArgInfo::getExpand();
3043 }
3044 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3045 }
3046
3047
Reid Klecknerec87fec2014-05-02 01:17:12 +00003048 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003049 // If the member pointer is represented by an LLVM int or ptr, pass it
3050 // directly.
3051 llvm::Type *LLTy = CGT.ConvertType(Ty);
3052 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3053 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003054 }
3055
Michael Kuperstein4f818702015-02-24 09:35:58 +00003056 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003057 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3058 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003059 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003060 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003061
Reid Kleckner9005f412014-05-02 00:51:20 +00003062 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003063 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003064 }
3065
Julien Lerouge10dcff82014-08-27 00:36:55 +00003066 // Bool type is always extended to the ABI, other builtin types are not
3067 // extended.
3068 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3069 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003070 return ABIArgInfo::getExtend();
3071
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003072 return ABIArgInfo::getDirect();
3073}
3074
3075void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003076 bool IsVectorCall =
3077 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003078
Reid Kleckner80944df2014-10-31 22:00:51 +00003079 // We can use up to 4 SSE return registers with vectorcall.
3080 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3081 if (!getCXXABI().classifyReturnType(FI))
3082 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3083
3084 // We can use up to 6 SSE register parameters with vectorcall.
3085 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003086 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003087 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003088}
3089
Chris Lattner04dc9572010-08-31 16:44:54 +00003090llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3091 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003092 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003093
Chris Lattner04dc9572010-08-31 16:44:54 +00003094 CGBuilderTy &Builder = CGF.Builder;
3095 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3096 "ap");
3097 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3098 llvm::Type *PTy =
3099 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3100 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3101
3102 uint64_t Offset =
3103 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3104 llvm::Value *NextAddr =
3105 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3106 "ap.next");
3107 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3108
3109 return AddrTyped;
3110}
Chris Lattner0cf24192010-06-28 20:05:43 +00003111
John McCallea8d8bb2010-03-11 00:10:12 +00003112// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003113namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003114/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3115class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003116public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003117 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3118
3119 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3120 CodeGenFunction &CGF) const override;
3121};
3122
3123class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3124public:
3125 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003126
Craig Topper4f12f102014-03-12 06:41:41 +00003127 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003128 // This is recovered from gcc output.
3129 return 1; // r1 is the dedicated stack pointer
3130 }
3131
3132 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003133 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003134
3135 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3136 return 16; // Natural alignment for Altivec vectors.
3137 }
John McCallea8d8bb2010-03-11 00:10:12 +00003138};
3139
3140}
3141
Roman Divacky8a12d842014-11-03 18:32:54 +00003142llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3143 QualType Ty,
3144 CodeGenFunction &CGF) const {
3145 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3146 // TODO: Implement this. For now ignore.
3147 (void)CTy;
3148 return nullptr;
3149 }
3150
3151 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3152 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3153 llvm::Type *CharPtr = CGF.Int8PtrTy;
3154 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3155
3156 CGBuilderTy &Builder = CGF.Builder;
3157 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3158 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3159 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3160 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3161 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3162 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3163 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3164 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3165 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3166 // Align GPR when TY is i64.
3167 if (isI64) {
3168 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3169 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3170 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3171 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3172 }
3173 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3174 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3175 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3176 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3177 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3178
3179 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3180 Builder.getInt8(8), "cond");
3181
3182 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3183 Builder.getInt8(isInt ? 4 : 8));
3184
3185 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3186
3187 if (Ty->isFloatingType())
3188 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3189
3190 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3191 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3192 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3193
3194 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3195
3196 CGF.EmitBlock(UsingRegs);
3197
3198 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3199 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3200 // Increase the GPR/FPR indexes.
3201 if (isInt) {
3202 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3203 Builder.CreateStore(GPR, GPRPtr);
3204 } else {
3205 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3206 Builder.CreateStore(FPR, FPRPtr);
3207 }
3208 CGF.EmitBranch(Cont);
3209
3210 CGF.EmitBlock(UsingOverflow);
3211
3212 // Increase the overflow area.
3213 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3214 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3215 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3216 CGF.EmitBranch(Cont);
3217
3218 CGF.EmitBlock(Cont);
3219
3220 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3221 Result->addIncoming(Result1, UsingRegs);
3222 Result->addIncoming(Result2, UsingOverflow);
3223
3224 if (Ty->isAggregateType()) {
3225 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3226 return Builder.CreateLoad(AGGPtr, false, "aggr");
3227 }
3228
3229 return Result;
3230}
3231
John McCallea8d8bb2010-03-11 00:10:12 +00003232bool
3233PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3234 llvm::Value *Address) const {
3235 // This is calculated from the LLVM and GCC tables and verified
3236 // against gcc output. AFAIK all ABIs use the same encoding.
3237
3238 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003239
Chris Lattnerece04092012-02-07 00:39:47 +00003240 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003241 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3242 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3243 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3244
3245 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003246 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003247
3248 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003249 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003250
3251 // 64-76 are various 4-byte special-purpose registers:
3252 // 64: mq
3253 // 65: lr
3254 // 66: ctr
3255 // 67: ap
3256 // 68-75 cr0-7
3257 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003258 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003259
3260 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003261 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003262
3263 // 109: vrsave
3264 // 110: vscr
3265 // 111: spe_acc
3266 // 112: spefscr
3267 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003268 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003269
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003270 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003271}
3272
Roman Divackyd966e722012-05-09 18:22:46 +00003273// PowerPC-64
3274
3275namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003276/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3277class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003278public:
3279 enum ABIKind {
3280 ELFv1 = 0,
3281 ELFv2
3282 };
3283
3284private:
3285 static const unsigned GPRBits = 64;
3286 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003287 bool HasQPX;
3288
3289 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3290 // will be passed in a QPX register.
3291 bool IsQPXVectorTy(const Type *Ty) const {
3292 if (!HasQPX)
3293 return false;
3294
3295 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3296 unsigned NumElements = VT->getNumElements();
3297 if (NumElements == 1)
3298 return false;
3299
3300 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3301 if (getContext().getTypeSize(Ty) <= 256)
3302 return true;
3303 } else if (VT->getElementType()->
3304 isSpecificBuiltinType(BuiltinType::Float)) {
3305 if (getContext().getTypeSize(Ty) <= 128)
3306 return true;
3307 }
3308 }
3309
3310 return false;
3311 }
3312
3313 bool IsQPXVectorTy(QualType Ty) const {
3314 return IsQPXVectorTy(Ty.getTypePtr());
3315 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003316
3317public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003318 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3319 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003320
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003321 bool isPromotableTypeForABI(QualType Ty) const;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003322 bool isAlignedParamType(QualType Ty, bool &Align32) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003323
3324 ABIArgInfo classifyReturnType(QualType RetTy) const;
3325 ABIArgInfo classifyArgumentType(QualType Ty) const;
3326
Reid Klecknere9f6a712014-10-31 17:10:41 +00003327 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3328 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3329 uint64_t Members) const override;
3330
Bill Schmidt84d37792012-10-12 19:26:17 +00003331 // TODO: We can add more logic to computeInfo to improve performance.
3332 // Example: For aggregate arguments that fit in a register, we could
3333 // use getDirectInReg (as is done below for structs containing a single
3334 // floating-point value) to avoid pushing them to memory on function
3335 // entry. This would require changing the logic in PPCISelLowering
3336 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003337 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003338 if (!getCXXABI().classifyReturnType(FI))
3339 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003340 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003341 // We rely on the default argument classification for the most part.
3342 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003343 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003344 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003345 if (T) {
3346 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003347 if (IsQPXVectorTy(T) ||
3348 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003349 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003350 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003351 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003352 continue;
3353 }
3354 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003355 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003356 }
3357 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003358
Craig Topper4f12f102014-03-12 06:41:41 +00003359 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3360 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003361};
3362
3363class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003364 bool HasQPX;
3365
Bill Schmidt25cb3492012-10-03 19:18:57 +00003366public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003367 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003368 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
3369 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)),
3370 HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003371
Craig Topper4f12f102014-03-12 06:41:41 +00003372 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003373 // This is recovered from gcc output.
3374 return 1; // r1 is the dedicated stack pointer
3375 }
3376
3377 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003378 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003379
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003380 unsigned getOpenMPSimdDefaultAlignment(QualType QT) const override {
3381 if (HasQPX)
3382 if (const PointerType *PT = QT->getAs<PointerType>())
3383 if (PT->getPointeeType()->isSpecificBuiltinType(BuiltinType::Double))
3384 return 32; // Natural alignment for QPX doubles.
3385
Hal Finkel92e31a52014-10-03 17:45:20 +00003386 return 16; // Natural alignment for Altivec and VSX vectors.
3387 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003388};
3389
Roman Divackyd966e722012-05-09 18:22:46 +00003390class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3391public:
3392 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3393
Craig Topper4f12f102014-03-12 06:41:41 +00003394 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003395 // This is recovered from gcc output.
3396 return 1; // r1 is the dedicated stack pointer
3397 }
3398
3399 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003400 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003401
3402 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3403 return 16; // Natural alignment for Altivec vectors.
3404 }
Roman Divackyd966e722012-05-09 18:22:46 +00003405};
3406
3407}
3408
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003409// Return true if the ABI requires Ty to be passed sign- or zero-
3410// extended to 64 bits.
3411bool
3412PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3413 // Treat an enum type as its underlying type.
3414 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3415 Ty = EnumTy->getDecl()->getIntegerType();
3416
3417 // Promotable integer types are required to be promoted by the ABI.
3418 if (Ty->isPromotableIntegerType())
3419 return true;
3420
3421 // In addition to the usual promotable integer types, we also need to
3422 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3423 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3424 switch (BT->getKind()) {
3425 case BuiltinType::Int:
3426 case BuiltinType::UInt:
3427 return true;
3428 default:
3429 break;
3430 }
3431
3432 return false;
3433}
3434
Ulrich Weigand581badc2014-07-10 17:20:07 +00003435/// isAlignedParamType - Determine whether a type requires 16-byte
3436/// alignment in the parameter area.
3437bool
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003438PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty, bool &Align32) const {
3439 Align32 = false;
3440
Ulrich Weigand581badc2014-07-10 17:20:07 +00003441 // Complex types are passed just like their elements.
3442 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3443 Ty = CTy->getElementType();
3444
3445 // Only vector types of size 16 bytes need alignment (larger types are
3446 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003447 if (IsQPXVectorTy(Ty)) {
3448 if (getContext().getTypeSize(Ty) > 128)
3449 Align32 = true;
3450
3451 return true;
3452 } else if (Ty->isVectorType()) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003453 return getContext().getTypeSize(Ty) == 128;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003454 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003455
3456 // For single-element float/vector structs, we consider the whole type
3457 // to have the same alignment requirements as its single element.
3458 const Type *AlignAsType = nullptr;
3459 const Type *EltType = isSingleElementStruct(Ty, getContext());
3460 if (EltType) {
3461 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003462 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003463 getContext().getTypeSize(EltType) == 128) ||
3464 (BT && BT->isFloatingPoint()))
3465 AlignAsType = EltType;
3466 }
3467
Ulrich Weigandb7122372014-07-21 00:48:09 +00003468 // Likewise for ELFv2 homogeneous aggregates.
3469 const Type *Base = nullptr;
3470 uint64_t Members = 0;
3471 if (!AlignAsType && Kind == ELFv2 &&
3472 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3473 AlignAsType = Base;
3474
Ulrich Weigand581badc2014-07-10 17:20:07 +00003475 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003476 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3477 if (getContext().getTypeSize(AlignAsType) > 128)
3478 Align32 = true;
3479
3480 return true;
3481 } else if (AlignAsType) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003482 return AlignAsType->isVectorType();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003483 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003484
3485 // Otherwise, we only need alignment for any aggregate type that
3486 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003487 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3488 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
3489 Align32 = true;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003490 return true;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003491 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003492
3493 return false;
3494}
3495
Ulrich Weigandb7122372014-07-21 00:48:09 +00003496/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3497/// aggregate. Base is set to the base element type, and Members is set
3498/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003499bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3500 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003501 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3502 uint64_t NElements = AT->getSize().getZExtValue();
3503 if (NElements == 0)
3504 return false;
3505 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3506 return false;
3507 Members *= NElements;
3508 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3509 const RecordDecl *RD = RT->getDecl();
3510 if (RD->hasFlexibleArrayMember())
3511 return false;
3512
3513 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003514
3515 // If this is a C++ record, check the bases first.
3516 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3517 for (const auto &I : CXXRD->bases()) {
3518 // Ignore empty records.
3519 if (isEmptyRecord(getContext(), I.getType(), true))
3520 continue;
3521
3522 uint64_t FldMembers;
3523 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3524 return false;
3525
3526 Members += FldMembers;
3527 }
3528 }
3529
Ulrich Weigandb7122372014-07-21 00:48:09 +00003530 for (const auto *FD : RD->fields()) {
3531 // Ignore (non-zero arrays of) empty records.
3532 QualType FT = FD->getType();
3533 while (const ConstantArrayType *AT =
3534 getContext().getAsConstantArrayType(FT)) {
3535 if (AT->getSize().getZExtValue() == 0)
3536 return false;
3537 FT = AT->getElementType();
3538 }
3539 if (isEmptyRecord(getContext(), FT, true))
3540 continue;
3541
3542 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3543 if (getContext().getLangOpts().CPlusPlus &&
3544 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3545 continue;
3546
3547 uint64_t FldMembers;
3548 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3549 return false;
3550
3551 Members = (RD->isUnion() ?
3552 std::max(Members, FldMembers) : Members + FldMembers);
3553 }
3554
3555 if (!Base)
3556 return false;
3557
3558 // Ensure there is no padding.
3559 if (getContext().getTypeSize(Base) * Members !=
3560 getContext().getTypeSize(Ty))
3561 return false;
3562 } else {
3563 Members = 1;
3564 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3565 Members = 2;
3566 Ty = CT->getElementType();
3567 }
3568
Reid Klecknere9f6a712014-10-31 17:10:41 +00003569 // Most ABIs only support float, double, and some vector type widths.
3570 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003571 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003572
3573 // The base type must be the same for all members. Types that
3574 // agree in both total size and mode (float vs. vector) are
3575 // treated as being equivalent here.
3576 const Type *TyPtr = Ty.getTypePtr();
3577 if (!Base)
3578 Base = TyPtr;
3579
3580 if (Base->isVectorType() != TyPtr->isVectorType() ||
3581 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3582 return false;
3583 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003584 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3585}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003586
Reid Klecknere9f6a712014-10-31 17:10:41 +00003587bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3588 // Homogeneous aggregates for ELFv2 must have base types of float,
3589 // double, long double, or 128-bit vectors.
3590 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3591 if (BT->getKind() == BuiltinType::Float ||
3592 BT->getKind() == BuiltinType::Double ||
3593 BT->getKind() == BuiltinType::LongDouble)
3594 return true;
3595 }
3596 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003597 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003598 return true;
3599 }
3600 return false;
3601}
3602
3603bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3604 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003605 // Vector types require one register, floating point types require one
3606 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003607 uint32_t NumRegs =
3608 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003609
3610 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003611 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003612}
3613
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003614ABIArgInfo
3615PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003616 Ty = useFirstFieldIfTransparentUnion(Ty);
3617
Bill Schmidt90b22c92012-11-27 02:46:43 +00003618 if (Ty->isAnyComplexType())
3619 return ABIArgInfo::getDirect();
3620
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003621 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3622 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003623 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003624 uint64_t Size = getContext().getTypeSize(Ty);
3625 if (Size > 128)
3626 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3627 else if (Size < 128) {
3628 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3629 return ABIArgInfo::getDirect(CoerceTy);
3630 }
3631 }
3632
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003633 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003634 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003635 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003636
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003637 bool Align32;
3638 uint64_t ABIAlign = isAlignedParamType(Ty, Align32) ?
3639 (Align32 ? 32 : 16) : 8;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003640 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003641
3642 // ELFv2 homogeneous aggregates are passed as array types.
3643 const Type *Base = nullptr;
3644 uint64_t Members = 0;
3645 if (Kind == ELFv2 &&
3646 isHomogeneousAggregate(Ty, Base, Members)) {
3647 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3648 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3649 return ABIArgInfo::getDirect(CoerceTy);
3650 }
3651
Ulrich Weigand601957f2014-07-21 00:56:36 +00003652 // If an aggregate may end up fully in registers, we do not
3653 // use the ByVal method, but pass the aggregate as array.
3654 // This is usually beneficial since we avoid forcing the
3655 // back-end to store the argument to memory.
3656 uint64_t Bits = getContext().getTypeSize(Ty);
3657 if (Bits > 0 && Bits <= 8 * GPRBits) {
3658 llvm::Type *CoerceTy;
3659
3660 // Types up to 8 bytes are passed as integer type (which will be
3661 // properly aligned in the argument save area doubleword).
3662 if (Bits <= GPRBits)
3663 CoerceTy = llvm::IntegerType::get(getVMContext(),
3664 llvm::RoundUpToAlignment(Bits, 8));
3665 // Larger types are passed as arrays, with the base type selected
3666 // according to the required alignment in the save area.
3667 else {
3668 uint64_t RegBits = ABIAlign * 8;
3669 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3670 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3671 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3672 }
3673
3674 return ABIArgInfo::getDirect(CoerceTy);
3675 }
3676
Ulrich Weigandb7122372014-07-21 00:48:09 +00003677 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003678 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3679 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003680 }
3681
3682 return (isPromotableTypeForABI(Ty) ?
3683 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3684}
3685
3686ABIArgInfo
3687PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3688 if (RetTy->isVoidType())
3689 return ABIArgInfo::getIgnore();
3690
Bill Schmidta3d121c2012-12-17 04:20:17 +00003691 if (RetTy->isAnyComplexType())
3692 return ABIArgInfo::getDirect();
3693
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003694 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3695 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003696 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003697 uint64_t Size = getContext().getTypeSize(RetTy);
3698 if (Size > 128)
3699 return ABIArgInfo::getIndirect(0);
3700 else if (Size < 128) {
3701 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3702 return ABIArgInfo::getDirect(CoerceTy);
3703 }
3704 }
3705
Ulrich Weigandb7122372014-07-21 00:48:09 +00003706 if (isAggregateTypeForABI(RetTy)) {
3707 // ELFv2 homogeneous aggregates are returned as array types.
3708 const Type *Base = nullptr;
3709 uint64_t Members = 0;
3710 if (Kind == ELFv2 &&
3711 isHomogeneousAggregate(RetTy, Base, Members)) {
3712 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3713 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3714 return ABIArgInfo::getDirect(CoerceTy);
3715 }
3716
3717 // ELFv2 small aggregates are returned in up to two registers.
3718 uint64_t Bits = getContext().getTypeSize(RetTy);
3719 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3720 if (Bits == 0)
3721 return ABIArgInfo::getIgnore();
3722
3723 llvm::Type *CoerceTy;
3724 if (Bits > GPRBits) {
3725 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003726 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003727 } else
3728 CoerceTy = llvm::IntegerType::get(getVMContext(),
3729 llvm::RoundUpToAlignment(Bits, 8));
3730 return ABIArgInfo::getDirect(CoerceTy);
3731 }
3732
3733 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003734 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003735 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003736
3737 return (isPromotableTypeForABI(RetTy) ?
3738 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3739}
3740
Bill Schmidt25cb3492012-10-03 19:18:57 +00003741// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3742llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3743 QualType Ty,
3744 CodeGenFunction &CGF) const {
3745 llvm::Type *BP = CGF.Int8PtrTy;
3746 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3747
3748 CGBuilderTy &Builder = CGF.Builder;
3749 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3750 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3751
Ulrich Weigand581badc2014-07-10 17:20:07 +00003752 // Handle types that require 16-byte alignment in the parameter save area.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003753 bool Align32;
3754 if (isAlignedParamType(Ty, Align32)) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003755 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003756 AddrAsInt = Builder.CreateAdd(AddrAsInt,
3757 Builder.getInt64(Align32 ? 31 : 15));
3758 AddrAsInt = Builder.CreateAnd(AddrAsInt,
3759 Builder.getInt64(Align32 ? -32 : -16));
Ulrich Weigand581badc2014-07-10 17:20:07 +00003760 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3761 }
3762
Bill Schmidt924c4782013-01-14 17:45:36 +00003763 // Update the va_list pointer. The pointer should be bumped by the
3764 // size of the object. We can trust getTypeSize() except for a complex
3765 // type whose base type is smaller than a doubleword. For these, the
3766 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003767 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003768 QualType BaseTy;
3769 unsigned CplxBaseSize = 0;
3770
3771 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3772 BaseTy = CTy->getElementType();
3773 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3774 if (CplxBaseSize < 8)
3775 SizeInBytes = 16;
3776 }
3777
Bill Schmidt25cb3492012-10-03 19:18:57 +00003778 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3779 llvm::Value *NextAddr =
3780 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3781 "ap.next");
3782 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3783
Bill Schmidt924c4782013-01-14 17:45:36 +00003784 // If we have a complex type and the base type is smaller than 8 bytes,
3785 // the ABI calls for the real and imaginary parts to be right-adjusted
3786 // in separate doublewords. However, Clang expects us to produce a
3787 // pointer to a structure with the two parts packed tightly. So generate
3788 // loads of the real and imaginary parts relative to the va_list pointer,
3789 // and store them to a temporary structure.
3790 if (CplxBaseSize && CplxBaseSize < 8) {
3791 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3792 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003793 if (CGF.CGM.getDataLayout().isBigEndian()) {
3794 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3795 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3796 } else {
3797 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3798 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003799 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3800 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3801 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3802 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3803 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
David Blaikie2e804282015-04-05 22:47:07 +00003804 llvm::AllocaInst *Ptr =
3805 CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), "vacplx");
3806 llvm::Value *RealPtr =
3807 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 0, ".real");
3808 llvm::Value *ImagPtr =
3809 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 1, ".imag");
Bill Schmidt924c4782013-01-14 17:45:36 +00003810 Builder.CreateStore(Real, RealPtr, false);
3811 Builder.CreateStore(Imag, ImagPtr, false);
3812 return Ptr;
3813 }
3814
Bill Schmidt25cb3492012-10-03 19:18:57 +00003815 // If the argument is smaller than 8 bytes, it is right-adjusted in
3816 // its doubleword slot. Adjust the pointer to pick it up from the
3817 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003818 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003819 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3820 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3821 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3822 }
3823
3824 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3825 return Builder.CreateBitCast(Addr, PTy);
3826}
3827
3828static bool
3829PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3830 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003831 // This is calculated from the LLVM and GCC tables and verified
3832 // against gcc output. AFAIK all ABIs use the same encoding.
3833
3834 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3835
3836 llvm::IntegerType *i8 = CGF.Int8Ty;
3837 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3838 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3839 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3840
3841 // 0-31: r0-31, the 8-byte general-purpose registers
3842 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3843
3844 // 32-63: fp0-31, the 8-byte floating-point registers
3845 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3846
3847 // 64-76 are various 4-byte special-purpose registers:
3848 // 64: mq
3849 // 65: lr
3850 // 66: ctr
3851 // 67: ap
3852 // 68-75 cr0-7
3853 // 76: xer
3854 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3855
3856 // 77-108: v0-31, the 16-byte vector registers
3857 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3858
3859 // 109: vrsave
3860 // 110: vscr
3861 // 111: spe_acc
3862 // 112: spefscr
3863 // 113: sfp
3864 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3865
3866 return false;
3867}
John McCallea8d8bb2010-03-11 00:10:12 +00003868
Bill Schmidt25cb3492012-10-03 19:18:57 +00003869bool
3870PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3871 CodeGen::CodeGenFunction &CGF,
3872 llvm::Value *Address) const {
3873
3874 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3875}
3876
3877bool
3878PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3879 llvm::Value *Address) const {
3880
3881 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3882}
3883
Chris Lattner0cf24192010-06-28 20:05:43 +00003884//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003885// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003886//===----------------------------------------------------------------------===//
3887
3888namespace {
3889
Tim Northover573cbee2014-05-24 12:52:07 +00003890class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003891public:
3892 enum ABIKind {
3893 AAPCS = 0,
3894 DarwinPCS
3895 };
3896
3897private:
3898 ABIKind Kind;
3899
3900public:
Tim Northover573cbee2014-05-24 12:52:07 +00003901 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003902
3903private:
3904 ABIKind getABIKind() const { return Kind; }
3905 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3906
3907 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003908 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003909 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3910 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3911 uint64_t Members) const override;
3912
Tim Northovera2ee4332014-03-29 15:09:45 +00003913 bool isIllegalVectorType(QualType Ty) const;
3914
David Blaikie1cbb9712014-11-14 19:09:44 +00003915 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003916 if (!getCXXABI().classifyReturnType(FI))
3917 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003918
Tim Northoverb047bfa2014-11-27 21:02:49 +00003919 for (auto &it : FI.arguments())
3920 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003921 }
3922
3923 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3924 CodeGenFunction &CGF) const;
3925
3926 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3927 CodeGenFunction &CGF) const;
3928
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003929 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3930 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003931 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3932 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3933 }
3934};
3935
Tim Northover573cbee2014-05-24 12:52:07 +00003936class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003937public:
Tim Northover573cbee2014-05-24 12:52:07 +00003938 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3939 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003940
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003941 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003942 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3943 }
3944
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003945 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3946 return 31;
3947 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003948
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003949 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00003950};
3951}
3952
Tim Northoverb047bfa2014-11-27 21:02:49 +00003953ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003954 Ty = useFirstFieldIfTransparentUnion(Ty);
3955
Tim Northovera2ee4332014-03-29 15:09:45 +00003956 // Handle illegal vector types here.
3957 if (isIllegalVectorType(Ty)) {
3958 uint64_t Size = getContext().getTypeSize(Ty);
3959 if (Size <= 32) {
3960 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00003961 return ABIArgInfo::getDirect(ResType);
3962 }
3963 if (Size == 64) {
3964 llvm::Type *ResType =
3965 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00003966 return ABIArgInfo::getDirect(ResType);
3967 }
3968 if (Size == 128) {
3969 llvm::Type *ResType =
3970 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00003971 return ABIArgInfo::getDirect(ResType);
3972 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003973 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3974 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003975
3976 if (!isAggregateTypeForABI(Ty)) {
3977 // Treat an enum type as its underlying type.
3978 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3979 Ty = EnumTy->getDecl()->getIntegerType();
3980
Tim Northovera2ee4332014-03-29 15:09:45 +00003981 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3982 ? ABIArgInfo::getExtend()
3983 : ABIArgInfo::getDirect());
3984 }
3985
3986 // Structures with either a non-trivial destructor or a non-trivial
3987 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003988 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003989 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00003990 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003991 }
3992
3993 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3994 // elsewhere for GNU compatibility.
3995 if (isEmptyRecord(getContext(), Ty, true)) {
3996 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3997 return ABIArgInfo::getIgnore();
3998
Tim Northovera2ee4332014-03-29 15:09:45 +00003999 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4000 }
4001
4002 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004003 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004004 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004005 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004006 return ABIArgInfo::getDirect(
4007 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004008 }
4009
4010 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4011 uint64_t Size = getContext().getTypeSize(Ty);
4012 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004013 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004014 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004015
Tim Northovera2ee4332014-03-29 15:09:45 +00004016 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4017 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004018 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004019 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4020 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4021 }
4022 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4023 }
4024
Tim Northovera2ee4332014-03-29 15:09:45 +00004025 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4026}
4027
Tim Northover573cbee2014-05-24 12:52:07 +00004028ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004029 if (RetTy->isVoidType())
4030 return ABIArgInfo::getIgnore();
4031
4032 // Large vector types should be returned via memory.
4033 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4034 return ABIArgInfo::getIndirect(0);
4035
4036 if (!isAggregateTypeForABI(RetTy)) {
4037 // Treat an enum type as its underlying type.
4038 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4039 RetTy = EnumTy->getDecl()->getIntegerType();
4040
Tim Northover4dab6982014-04-18 13:46:08 +00004041 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4042 ? ABIArgInfo::getExtend()
4043 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004044 }
4045
Tim Northovera2ee4332014-03-29 15:09:45 +00004046 if (isEmptyRecord(getContext(), RetTy, true))
4047 return ABIArgInfo::getIgnore();
4048
Craig Topper8a13c412014-05-21 05:09:00 +00004049 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004050 uint64_t Members = 0;
4051 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004052 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4053 return ABIArgInfo::getDirect();
4054
4055 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4056 uint64_t Size = getContext().getTypeSize(RetTy);
4057 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004058 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004059 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004060
4061 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4062 // For aggregates with 16-byte alignment, we use i128.
4063 if (Alignment < 128 && Size == 128) {
4064 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4065 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4066 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004067 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4068 }
4069
4070 return ABIArgInfo::getIndirect(0);
4071}
4072
Tim Northover573cbee2014-05-24 12:52:07 +00004073/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4074bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004075 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4076 // Check whether VT is legal.
4077 unsigned NumElements = VT->getNumElements();
4078 uint64_t Size = getContext().getTypeSize(VT);
4079 // NumElements should be power of 2 between 1 and 16.
4080 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4081 return true;
4082 return Size != 64 && (Size != 128 || NumElements == 1);
4083 }
4084 return false;
4085}
4086
Reid Klecknere9f6a712014-10-31 17:10:41 +00004087bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4088 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4089 // point type or a short-vector type. This is the same as the 32-bit ABI,
4090 // but with the difference that any floating-point type is allowed,
4091 // including __fp16.
4092 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4093 if (BT->isFloatingPoint())
4094 return true;
4095 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4096 unsigned VecSize = getContext().getTypeSize(VT);
4097 if (VecSize == 64 || VecSize == 128)
4098 return true;
4099 }
4100 return false;
4101}
4102
4103bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4104 uint64_t Members) const {
4105 return Members <= 4;
4106}
4107
Tim Northoverb047bfa2014-11-27 21:02:49 +00004108llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4109 QualType Ty,
4110 CodeGenFunction &CGF) const {
4111 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004112 bool IsIndirect = AI.isIndirect();
4113
Tim Northoverb047bfa2014-11-27 21:02:49 +00004114 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4115 if (IsIndirect)
4116 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4117 else if (AI.getCoerceToType())
4118 BaseTy = AI.getCoerceToType();
4119
4120 unsigned NumRegs = 1;
4121 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4122 BaseTy = ArrTy->getElementType();
4123 NumRegs = ArrTy->getNumElements();
4124 }
4125 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4126
Tim Northovera2ee4332014-03-29 15:09:45 +00004127 // The AArch64 va_list type and handling is specified in the Procedure Call
4128 // Standard, section B.4:
4129 //
4130 // struct {
4131 // void *__stack;
4132 // void *__gr_top;
4133 // void *__vr_top;
4134 // int __gr_offs;
4135 // int __vr_offs;
4136 // };
4137
4138 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4139 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4140 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4141 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4142 auto &Ctx = CGF.getContext();
4143
Craig Topper8a13c412014-05-21 05:09:00 +00004144 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004145 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004146 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4147 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004148 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004149 reg_offs_p =
4150 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004151 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4152 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004153 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004154 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004155 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004156 reg_offs_p =
4157 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004158 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4159 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004160 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004161 }
4162
4163 //=======================================
4164 // Find out where argument was passed
4165 //=======================================
4166
4167 // If reg_offs >= 0 we're already using the stack for this type of
4168 // argument. We don't want to keep updating reg_offs (in case it overflows,
4169 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4170 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004171 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004172 UsingStack = CGF.Builder.CreateICmpSGE(
4173 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4174
4175 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4176
4177 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004178 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004179 CGF.EmitBlock(MaybeRegBlock);
4180
4181 // Integer arguments may need to correct register alignment (for example a
4182 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4183 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004184 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004185 int Align = Ctx.getTypeAlign(Ty) / 8;
4186
4187 reg_offs = CGF.Builder.CreateAdd(
4188 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4189 "align_regoffs");
4190 reg_offs = CGF.Builder.CreateAnd(
4191 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4192 "aligned_regoffs");
4193 }
4194
4195 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004196 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004197 NewOffset = CGF.Builder.CreateAdd(
4198 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4199 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4200
4201 // Now we're in a position to decide whether this argument really was in
4202 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004203 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004204 InRegs = CGF.Builder.CreateICmpSLE(
4205 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4206
4207 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4208
4209 //=======================================
4210 // Argument was in registers
4211 //=======================================
4212
4213 // Now we emit the code for if the argument was originally passed in
4214 // registers. First start the appropriate block:
4215 CGF.EmitBlock(InRegBlock);
4216
Craig Topper8a13c412014-05-21 05:09:00 +00004217 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
David Blaikie2e804282015-04-05 22:47:07 +00004218 reg_top_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, reg_top_index,
4219 "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004220 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4221 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004222 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004223 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4224
4225 if (IsIndirect) {
4226 // If it's been passed indirectly (actually a struct), whatever we find from
4227 // stored registers or on the stack will actually be a struct **.
4228 MemTy = llvm::PointerType::getUnqual(MemTy);
4229 }
4230
Craig Topper8a13c412014-05-21 05:09:00 +00004231 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004232 uint64_t NumMembers = 0;
4233 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004234 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004235 // Homogeneous aggregates passed in registers will have their elements split
4236 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4237 // qN+1, ...). We reload and store into a temporary local variable
4238 // contiguously.
4239 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4240 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4241 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
David Blaikie1ed728c2015-04-05 22:45:47 +00004242 llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(HFATy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004243 int Offset = 0;
4244
4245 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4246 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4247 for (unsigned i = 0; i < NumMembers; ++i) {
4248 llvm::Value *BaseOffset =
4249 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4250 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4251 LoadAddr = CGF.Builder.CreateBitCast(
4252 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
David Blaikie2e804282015-04-05 22:47:07 +00004253 llvm::Value *StoreAddr =
4254 CGF.Builder.CreateStructGEP(Tmp->getAllocatedType(), Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00004255
4256 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4257 CGF.Builder.CreateStore(Elem, StoreAddr);
4258 }
4259
4260 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4261 } else {
4262 // Otherwise the object is contiguous in memory
4263 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004264 if (CGF.CGM.getDataLayout().isBigEndian() &&
4265 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004266 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4267 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4268 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4269
4270 BaseAddr = CGF.Builder.CreateAdd(
4271 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4272
4273 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4274 }
4275
4276 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4277 }
4278
4279 CGF.EmitBranch(ContBlock);
4280
4281 //=======================================
4282 // Argument was on the stack
4283 //=======================================
4284 CGF.EmitBlock(OnStackBlock);
4285
Craig Topper8a13c412014-05-21 05:09:00 +00004286 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
David Blaikie1ed728c2015-04-05 22:45:47 +00004287 stack_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "stack_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004288 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4289
4290 // Again, stack arguments may need realigmnent. In this case both integer and
4291 // floating-point ones might be affected.
4292 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4293 int Align = Ctx.getTypeAlign(Ty) / 8;
4294
4295 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4296
4297 OnStackAddr = CGF.Builder.CreateAdd(
4298 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4299 "align_stack");
4300 OnStackAddr = CGF.Builder.CreateAnd(
4301 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4302 "align_stack");
4303
4304 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4305 }
4306
4307 uint64_t StackSize;
4308 if (IsIndirect)
4309 StackSize = 8;
4310 else
4311 StackSize = Ctx.getTypeSize(Ty) / 8;
4312
4313 // All stack slots are 8 bytes
4314 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4315
4316 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4317 llvm::Value *NewStack =
4318 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4319
4320 // Write the new value of __stack for the next call to va_arg
4321 CGF.Builder.CreateStore(NewStack, stack_p);
4322
4323 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4324 Ctx.getTypeSize(Ty) < 64) {
4325 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4326 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4327
4328 OnStackAddr = CGF.Builder.CreateAdd(
4329 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4330
4331 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4332 }
4333
4334 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4335
4336 CGF.EmitBranch(ContBlock);
4337
4338 //=======================================
4339 // Tidy up
4340 //=======================================
4341 CGF.EmitBlock(ContBlock);
4342
4343 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4344 ResAddr->addIncoming(RegAddr, InRegBlock);
4345 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4346
4347 if (IsIndirect)
4348 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4349
4350 return ResAddr;
4351}
4352
Tim Northover573cbee2014-05-24 12:52:07 +00004353llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004354 CodeGenFunction &CGF) const {
4355 // We do not support va_arg for aggregates or illegal vector types.
4356 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4357 // other cases.
4358 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004359 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004360
4361 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4362 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4363
Craig Topper8a13c412014-05-21 05:09:00 +00004364 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004365 uint64_t Members = 0;
4366 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004367
4368 bool isIndirect = false;
4369 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4370 // be passed indirectly.
4371 if (Size > 16 && !isHA) {
4372 isIndirect = true;
4373 Size = 8;
4374 Align = 8;
4375 }
4376
4377 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4378 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4379
4380 CGBuilderTy &Builder = CGF.Builder;
4381 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4382 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4383
4384 if (isEmptyRecord(getContext(), Ty, true)) {
4385 // These are ignored for parameter passing purposes.
4386 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4387 return Builder.CreateBitCast(Addr, PTy);
4388 }
4389
4390 const uint64_t MinABIAlign = 8;
4391 if (Align > MinABIAlign) {
4392 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4393 Addr = Builder.CreateGEP(Addr, Offset);
4394 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4395 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4396 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4397 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4398 }
4399
4400 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4401 llvm::Value *NextAddr = Builder.CreateGEP(
4402 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4403 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4404
4405 if (isIndirect)
4406 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4407 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4408 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4409
4410 return AddrTyped;
4411}
4412
4413//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004414// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004415//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004416
4417namespace {
4418
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004419class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004420public:
4421 enum ABIKind {
4422 APCS = 0,
4423 AAPCS = 1,
4424 AAPCS_VFP
4425 };
4426
4427private:
4428 ABIKind Kind;
4429
4430public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004431 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004432 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004433 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004434
John McCall3480ef22011-08-30 01:42:09 +00004435 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004436 switch (getTarget().getTriple().getEnvironment()) {
4437 case llvm::Triple::Android:
4438 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004439 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004440 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004441 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004442 return true;
4443 default:
4444 return false;
4445 }
John McCall3480ef22011-08-30 01:42:09 +00004446 }
4447
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004448 bool isEABIHF() const {
4449 switch (getTarget().getTriple().getEnvironment()) {
4450 case llvm::Triple::EABIHF:
4451 case llvm::Triple::GNUEABIHF:
4452 return true;
4453 default:
4454 return false;
4455 }
4456 }
4457
Daniel Dunbar020daa92009-09-12 01:00:39 +00004458 ABIKind getABIKind() const { return Kind; }
4459
Tim Northovera484bc02013-10-01 14:34:25 +00004460private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004461 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004462 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004463 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004464
Reid Klecknere9f6a712014-10-31 17:10:41 +00004465 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4466 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4467 uint64_t Members) const override;
4468
Craig Topper4f12f102014-03-12 06:41:41 +00004469 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004470
Craig Topper4f12f102014-03-12 06:41:41 +00004471 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4472 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004473
4474 llvm::CallingConv::ID getLLVMDefaultCC() const;
4475 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004476 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004477};
4478
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004479class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4480public:
Chris Lattner2b037972010-07-29 02:01:43 +00004481 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4482 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004483
John McCall3480ef22011-08-30 01:42:09 +00004484 const ARMABIInfo &getABIInfo() const {
4485 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4486 }
4487
Craig Topper4f12f102014-03-12 06:41:41 +00004488 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004489 return 13;
4490 }
Roman Divackyc1617352011-05-18 19:36:54 +00004491
Craig Topper4f12f102014-03-12 06:41:41 +00004492 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004493 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4494 }
4495
Roman Divackyc1617352011-05-18 19:36:54 +00004496 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004497 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004498 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004499
4500 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004501 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004502 return false;
4503 }
John McCall3480ef22011-08-30 01:42:09 +00004504
Craig Topper4f12f102014-03-12 06:41:41 +00004505 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004506 if (getABIInfo().isEABI()) return 88;
4507 return TargetCodeGenInfo::getSizeOfUnwindException();
4508 }
Tim Northovera484bc02013-10-01 14:34:25 +00004509
4510 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004511 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004512 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4513 if (!FD)
4514 return;
4515
4516 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4517 if (!Attr)
4518 return;
4519
4520 const char *Kind;
4521 switch (Attr->getInterrupt()) {
4522 case ARMInterruptAttr::Generic: Kind = ""; break;
4523 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4524 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4525 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4526 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4527 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4528 }
4529
4530 llvm::Function *Fn = cast<llvm::Function>(GV);
4531
4532 Fn->addFnAttr("interrupt", Kind);
4533
4534 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4535 return;
4536
4537 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4538 // however this is not necessarily true on taking any interrupt. Instruct
4539 // the backend to perform a realignment as part of the function prologue.
4540 llvm::AttrBuilder B;
4541 B.addStackAlignmentAttr(8);
4542 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4543 llvm::AttributeSet::get(CGM.getLLVMContext(),
4544 llvm::AttributeSet::FunctionIndex,
4545 B));
4546 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004547};
4548
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004549class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4550 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4551 CodeGen::CodeGenModule &CGM) const;
4552
4553public:
4554 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4555 : ARMTargetCodeGenInfo(CGT, K) {}
4556
4557 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4558 CodeGen::CodeGenModule &CGM) const override;
4559};
4560
4561void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4562 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4563 if (!isa<FunctionDecl>(D))
4564 return;
4565 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4566 return;
4567
4568 llvm::Function *F = cast<llvm::Function>(GV);
4569 F->addFnAttr("stack-probe-size",
4570 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4571}
4572
4573void WindowsARMTargetCodeGenInfo::SetTargetAttributes(
4574 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4575 ARMTargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
4576 addStackProbeSizeTargetAttribute(D, GV, CGM);
4577}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004578}
4579
Chris Lattner22326a12010-07-29 02:31:05 +00004580void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004581 if (!getCXXABI().classifyReturnType(FI))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004582 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004583
Tim Northoverbc784d12015-02-24 17:22:40 +00004584 for (auto &I : FI.arguments())
4585 I.info = classifyArgumentType(I.type, FI.isVariadic());
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)
Tim Northoverbc784d12015-02-24 17:22:40 +00004593 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004594}
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
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004618void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004619 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 Korobeynikovd90dd792014-12-02 16:04:58 +00004626
4627 BuiltinCC = (getABIKind() == APCS ?
4628 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004629}
4630
Tim Northoverbc784d12015-02-24 17:22:40 +00004631ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4632 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004633 // 6.1.2.1 The following argument types are VFP CPRCs:
4634 // A single-precision floating-point type (including promoted
4635 // half-precision types); A double-precision floating-point type;
4636 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4637 // with a Base Type of a single- or double-precision floating-point type,
4638 // 64-bit containerized vectors or 128-bit containerized vectors with one
4639 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004640 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004641
Reid Klecknerb1be6832014-11-15 01:41:41 +00004642 Ty = useFirstFieldIfTransparentUnion(Ty);
4643
Manman Renfef9e312012-10-16 19:18:39 +00004644 // Handle illegal vector types here.
4645 if (isIllegalVectorType(Ty)) {
4646 uint64_t Size = getContext().getTypeSize(Ty);
4647 if (Size <= 32) {
4648 llvm::Type *ResType =
4649 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004650 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004651 }
4652 if (Size == 64) {
4653 llvm::Type *ResType = llvm::VectorType::get(
4654 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004655 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004656 }
4657 if (Size == 128) {
4658 llvm::Type *ResType = llvm::VectorType::get(
4659 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004660 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004661 }
4662 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4663 }
4664
John McCalla1dee5302010-08-22 10:59:02 +00004665 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004666 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004667 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004668 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004669 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004670
Tim Northover5a1558e2014-11-07 22:30:50 +00004671 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4672 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004673 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004674
Oliver Stannard405bded2014-02-11 09:25:50 +00004675 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northover1060eae2013-06-21 22:49:34 +00004676 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004677 }
Tim Northover1060eae2013-06-21 22:49:34 +00004678
Daniel Dunbar09d33622009-09-14 21:54:03 +00004679 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004680 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004681 return ABIArgInfo::getIgnore();
4682
Tim Northover5a1558e2014-11-07 22:30:50 +00004683 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004684 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4685 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004686 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004687 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004688 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004689 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004690 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004691 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004692 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004693 }
4694
Manman Ren6c30e132012-08-13 21:23:55 +00004695 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004696 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4697 // most 8-byte. We realign the indirect argument if type alignment is bigger
4698 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004699 uint64_t ABIAlign = 4;
4700 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4701 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004702 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004703 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004704
Manman Ren8cd99812012-11-06 04:58:01 +00004705 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northoverd157e192015-03-09 21:40:42 +00004706 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004707 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004708 }
4709
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004710 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004711 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004712 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004713 // FIXME: Try to match the types of the arguments more accurately where
4714 // we can.
4715 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004716 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4717 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004718 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004719 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4720 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004721 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004722
Tim Northover5a1558e2014-11-07 22:30:50 +00004723 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004724}
4725
Chris Lattner458b2aa2010-07-29 02:16:43 +00004726static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004727 llvm::LLVMContext &VMContext) {
4728 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4729 // is called integer-like if its size is less than or equal to one word, and
4730 // the offset of each of its addressable sub-fields is zero.
4731
4732 uint64_t Size = Context.getTypeSize(Ty);
4733
4734 // Check that the type fits in a word.
4735 if (Size > 32)
4736 return false;
4737
4738 // FIXME: Handle vector types!
4739 if (Ty->isVectorType())
4740 return false;
4741
Daniel Dunbard53bac72009-09-14 02:20:34 +00004742 // Float types are never treated as "integer like".
4743 if (Ty->isRealFloatingType())
4744 return false;
4745
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004746 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004747 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004748 return true;
4749
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004750 // Small complex integer types are "integer like".
4751 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4752 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004753
4754 // Single element and zero sized arrays should be allowed, by the definition
4755 // above, but they are not.
4756
4757 // Otherwise, it must be a record type.
4758 const RecordType *RT = Ty->getAs<RecordType>();
4759 if (!RT) return false;
4760
4761 // Ignore records with flexible arrays.
4762 const RecordDecl *RD = RT->getDecl();
4763 if (RD->hasFlexibleArrayMember())
4764 return false;
4765
4766 // Check that all sub-fields are at offset 0, and are themselves "integer
4767 // like".
4768 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4769
4770 bool HadField = false;
4771 unsigned idx = 0;
4772 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4773 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004774 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004775
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004776 // Bit-fields are not addressable, we only need to verify they are "integer
4777 // like". We still have to disallow a subsequent non-bitfield, for example:
4778 // struct { int : 0; int x }
4779 // is non-integer like according to gcc.
4780 if (FD->isBitField()) {
4781 if (!RD->isUnion())
4782 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004783
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004784 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4785 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004786
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004787 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004788 }
4789
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004790 // Check if this field is at offset 0.
4791 if (Layout.getFieldOffset(idx) != 0)
4792 return false;
4793
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004794 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4795 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004796
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004797 // Only allow at most one field in a structure. This doesn't match the
4798 // wording above, but follows gcc in situations with a field following an
4799 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004800 if (!RD->isUnion()) {
4801 if (HadField)
4802 return false;
4803
4804 HadField = true;
4805 }
4806 }
4807
4808 return true;
4809}
4810
Oliver Stannard405bded2014-02-11 09:25:50 +00004811ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4812 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004813 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004814
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004815 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004816 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004817
Daniel Dunbar19964db2010-09-23 01:54:32 +00004818 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004819 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbar19964db2010-09-23 01:54:32 +00004820 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004821 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004822
John McCalla1dee5302010-08-22 10:59:02 +00004823 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004824 // Treat an enum type as its underlying type.
4825 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4826 RetTy = EnumTy->getDecl()->getIntegerType();
4827
Tim Northover5a1558e2014-11-07 22:30:50 +00004828 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4829 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004830 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004831
4832 // Are we following APCS?
4833 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004834 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004835 return ABIArgInfo::getIgnore();
4836
Daniel Dunbareedf1512010-02-01 23:31:19 +00004837 // Complex types are all returned as packed integers.
4838 //
4839 // FIXME: Consider using 2 x vector types if the back end handles them
4840 // correctly.
4841 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004842 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4843 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004844
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004845 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004846 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004847 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004848 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004849 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004850 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004851 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004852 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4853 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004854 }
4855
4856 // Otherwise return in memory.
4857 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004858 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004859
4860 // Otherwise this is an AAPCS variant.
4861
Chris Lattner458b2aa2010-07-29 02:16:43 +00004862 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004863 return ABIArgInfo::getIgnore();
4864
Bob Wilson1d9269a2011-11-02 04:51:36 +00004865 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004866 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004867 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004868 uint64_t Members;
4869 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004870 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004871 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004872 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004873 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004874 }
4875
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004876 // Aggregates <= 4 bytes are returned in r0; other aggregates
4877 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004878 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004879 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004880 if (getDataLayout().isBigEndian())
4881 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004882 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004883
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004884 // Return in the smallest viable integer type.
4885 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004886 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004887 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004888 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4889 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004890 }
4891
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004892 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004893}
4894
Manman Renfef9e312012-10-16 19:18:39 +00004895/// isIllegalVector - check whether Ty is an illegal vector type.
4896bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4897 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4898 // Check whether VT is legal.
4899 unsigned NumElements = VT->getNumElements();
4900 uint64_t Size = getContext().getTypeSize(VT);
4901 // NumElements should be power of 2.
4902 if ((NumElements & (NumElements - 1)) != 0)
4903 return true;
4904 // Size should be greater than 32 bits.
4905 return Size <= 32;
4906 }
4907 return false;
4908}
4909
Reid Klecknere9f6a712014-10-31 17:10:41 +00004910bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4911 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4912 // double, or 64-bit or 128-bit vectors.
4913 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4914 if (BT->getKind() == BuiltinType::Float ||
4915 BT->getKind() == BuiltinType::Double ||
4916 BT->getKind() == BuiltinType::LongDouble)
4917 return true;
4918 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4919 unsigned VecSize = getContext().getTypeSize(VT);
4920 if (VecSize == 64 || VecSize == 128)
4921 return true;
4922 }
4923 return false;
4924}
4925
4926bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4927 uint64_t Members) const {
4928 return Members <= 4;
4929}
4930
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004931llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004932 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004933 llvm::Type *BP = CGF.Int8PtrTy;
4934 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004935
4936 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004937 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004938 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004939
Tim Northover1711cc92013-06-21 23:05:33 +00004940 if (isEmptyRecord(getContext(), Ty, true)) {
4941 // These are ignored for parameter passing purposes.
4942 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4943 return Builder.CreateBitCast(Addr, PTy);
4944 }
4945
Manman Rencca54d02012-10-16 19:01:37 +00004946 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004947 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004948 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004949
4950 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4951 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004952 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4953 getABIKind() == ARMABIInfo::AAPCS)
4954 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4955 else
4956 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004957 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4958 if (isIllegalVectorType(Ty) && Size > 16) {
4959 IsIndirect = true;
4960 Size = 4;
4961 TyAlign = 4;
4962 }
Manman Rencca54d02012-10-16 19:01:37 +00004963
4964 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004965 if (TyAlign > 4) {
4966 assert((TyAlign & (TyAlign - 1)) == 0 &&
4967 "Alignment is not power of 2!");
4968 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4969 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4970 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004971 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004972 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004973
4974 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004975 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004976 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004977 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004978 "ap.next");
4979 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4980
Manman Renfef9e312012-10-16 19:18:39 +00004981 if (IsIndirect)
4982 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004983 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004984 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4985 // may not be correctly aligned for the vector type. We create an aligned
4986 // temporary space and copy the content over from ap.cur to the temporary
4987 // space. This is necessary if the natural alignment of the type is greater
4988 // than the ABI alignment.
4989 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4990 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4991 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4992 "var.align");
4993 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4994 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4995 Builder.CreateMemCpy(Dst, Src,
4996 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4997 TyAlign, false);
4998 Addr = AlignedTemp; //The content is in aligned location.
4999 }
5000 llvm::Type *PTy =
5001 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5002 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5003
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005004 return AddrTyped;
5005}
5006
Chris Lattner0cf24192010-06-28 20:05:43 +00005007//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005008// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005009//===----------------------------------------------------------------------===//
5010
5011namespace {
5012
Justin Holewinski83e96682012-05-24 17:43:12 +00005013class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005014public:
Justin Holewinski36837432013-03-30 14:38:24 +00005015 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005016
5017 ABIArgInfo classifyReturnType(QualType RetTy) const;
5018 ABIArgInfo classifyArgumentType(QualType Ty) const;
5019
Craig Topper4f12f102014-03-12 06:41:41 +00005020 void computeInfo(CGFunctionInfo &FI) const override;
5021 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5022 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005023};
5024
Justin Holewinski83e96682012-05-24 17:43:12 +00005025class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005026public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005027 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5028 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005029
5030 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5031 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005032private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005033 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5034 // resulting MDNode to the nvvm.annotations MDNode.
5035 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005036};
5037
Justin Holewinski83e96682012-05-24 17:43:12 +00005038ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005039 if (RetTy->isVoidType())
5040 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005041
5042 // note: this is different from default ABI
5043 if (!RetTy->isScalarType())
5044 return ABIArgInfo::getDirect();
5045
5046 // Treat an enum type as its underlying type.
5047 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5048 RetTy = EnumTy->getDecl()->getIntegerType();
5049
5050 return (RetTy->isPromotableIntegerType() ?
5051 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005052}
5053
Justin Holewinski83e96682012-05-24 17:43:12 +00005054ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005055 // Treat an enum type as its underlying type.
5056 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5057 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005058
Eli Bendersky95338a02014-10-29 13:43:21 +00005059 // Return aggregates type as indirect by value
5060 if (isAggregateTypeForABI(Ty))
5061 return ABIArgInfo::getIndirect(0, /* byval */ true);
5062
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005063 return (Ty->isPromotableIntegerType() ?
5064 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005065}
5066
Justin Holewinski83e96682012-05-24 17:43:12 +00005067void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005068 if (!getCXXABI().classifyReturnType(FI))
5069 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005070 for (auto &I : FI.arguments())
5071 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005072
5073 // Always honor user-specified calling convention.
5074 if (FI.getCallingConvention() != llvm::CallingConv::C)
5075 return;
5076
John McCall882987f2013-02-28 19:01:20 +00005077 FI.setEffectiveCallingConvention(getRuntimeCC());
5078}
5079
Justin Holewinski83e96682012-05-24 17:43:12 +00005080llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5081 CodeGenFunction &CFG) const {
5082 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005083}
5084
Justin Holewinski83e96682012-05-24 17:43:12 +00005085void NVPTXTargetCodeGenInfo::
5086SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5087 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005088 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5089 if (!FD) return;
5090
5091 llvm::Function *F = cast<llvm::Function>(GV);
5092
5093 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005094 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005095 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005096 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005097 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005098 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005099 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5100 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005101 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005102 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005103 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005104 }
Justin Holewinski38031972011-10-05 17:58:44 +00005105
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005106 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005107 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005108 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005109 // __global__ functions cannot be called from the device, we do not
5110 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005111 if (FD->hasAttr<CUDAGlobalAttr>()) {
5112 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5113 addNVVMMetadata(F, "kernel", 1);
5114 }
Artem Belevich7093e402015-04-21 22:55:54 +00005115 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005116 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005117 llvm::APSInt MaxThreads(32);
5118 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5119 if (MaxThreads > 0)
5120 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5121
5122 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5123 // not specified in __launch_bounds__ or if the user specified a 0 value,
5124 // we don't have to add a PTX directive.
5125 if (Attr->getMinBlocks()) {
5126 llvm::APSInt MinBlocks(32);
5127 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5128 if (MinBlocks > 0)
5129 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5130 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005131 }
5132 }
Justin Holewinski38031972011-10-05 17:58:44 +00005133 }
5134}
5135
Eli Benderskye06a2c42014-04-15 16:57:05 +00005136void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5137 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005138 llvm::Module *M = F->getParent();
5139 llvm::LLVMContext &Ctx = M->getContext();
5140
5141 // Get "nvvm.annotations" metadata node
5142 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5143
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005144 llvm::Metadata *MDVals[] = {
5145 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5146 llvm::ConstantAsMetadata::get(
5147 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005148 // Append metadata to nvvm.annotations
5149 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5150}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005151}
5152
5153//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005154// SystemZ ABI Implementation
5155//===----------------------------------------------------------------------===//
5156
5157namespace {
5158
5159class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005160 bool HasVector;
5161
Ulrich Weigand47445072013-05-06 16:26:41 +00005162public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005163 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5164 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005165
5166 bool isPromotableIntegerType(QualType Ty) const;
5167 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005168 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005169 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005170 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005171
5172 ABIArgInfo classifyReturnType(QualType RetTy) const;
5173 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5174
Craig Topper4f12f102014-03-12 06:41:41 +00005175 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005176 if (!getCXXABI().classifyReturnType(FI))
5177 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005178 for (auto &I : FI.arguments())
5179 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005180 }
5181
Craig Topper4f12f102014-03-12 06:41:41 +00005182 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5183 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005184};
5185
5186class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5187public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005188 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5189 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005190};
5191
5192}
5193
5194bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5195 // Treat an enum type as its underlying type.
5196 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5197 Ty = EnumTy->getDecl()->getIntegerType();
5198
5199 // Promotable integer types are required to be promoted by the ABI.
5200 if (Ty->isPromotableIntegerType())
5201 return true;
5202
5203 // 32-bit values must also be promoted.
5204 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5205 switch (BT->getKind()) {
5206 case BuiltinType::Int:
5207 case BuiltinType::UInt:
5208 return true;
5209 default:
5210 return false;
5211 }
5212 return false;
5213}
5214
5215bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005216 return (Ty->isAnyComplexType() ||
5217 Ty->isVectorType() ||
5218 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005219}
5220
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005221bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5222 return (HasVector &&
5223 Ty->isVectorType() &&
5224 getContext().getTypeSize(Ty) <= 128);
5225}
5226
Ulrich Weigand47445072013-05-06 16:26:41 +00005227bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5228 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5229 switch (BT->getKind()) {
5230 case BuiltinType::Float:
5231 case BuiltinType::Double:
5232 return true;
5233 default:
5234 return false;
5235 }
5236
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005237 return false;
5238}
5239
5240QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005241 if (const RecordType *RT = Ty->getAsStructureType()) {
5242 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005243 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005244
5245 // If this is a C++ record, check the bases first.
5246 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005247 for (const auto &I : CXXRD->bases()) {
5248 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005249
5250 // Empty bases don't affect things either way.
5251 if (isEmptyRecord(getContext(), Base, true))
5252 continue;
5253
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005254 if (!Found.isNull())
5255 return Ty;
5256 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005257 }
5258
5259 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005260 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005261 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005262 // Unlike isSingleElementStruct(), empty structure and array fields
5263 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005264 if (getContext().getLangOpts().CPlusPlus &&
5265 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5266 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005267
5268 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005269 // Nested structures still do though.
5270 if (!Found.isNull())
5271 return Ty;
5272 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005273 }
5274
5275 // Unlike isSingleElementStruct(), trailing padding is allowed.
5276 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005277 if (!Found.isNull())
5278 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005279 }
5280
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005281 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005282}
5283
5284llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5285 CodeGenFunction &CGF) const {
5286 // Assume that va_list type is correct; should be pointer to LLVM type:
5287 // struct {
5288 // i64 __gpr;
5289 // i64 __fpr;
5290 // i8 *__overflow_arg_area;
5291 // i8 *__reg_save_area;
5292 // };
5293
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005294 // Every non-vector argument occupies 8 bytes and is passed by preference
5295 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5296 // always passed on the stack.
Ulrich Weigand47445072013-05-06 16:26:41 +00005297 Ty = CGF.getContext().getCanonicalType(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005298 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
5299 llvm::Type *APTy = llvm::PointerType::getUnqual(ArgTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005300 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005301 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005302 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005303 bool IsVector = false;
Ulrich Weigand47445072013-05-06 16:26:41 +00005304 unsigned UnpaddedBitSize;
5305 if (IsIndirect) {
5306 APTy = llvm::PointerType::getUnqual(APTy);
5307 UnpaddedBitSize = 64;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005308 } else {
5309 if (AI.getCoerceToType())
5310 ArgTy = AI.getCoerceToType();
5311 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005312 IsVector = ArgTy->isVectorTy();
Ulrich Weigand47445072013-05-06 16:26:41 +00005313 UnpaddedBitSize = getContext().getTypeSize(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005314 }
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005315 unsigned PaddedBitSize = (IsVector && UnpaddedBitSize > 64) ? 128 : 64;
Ulrich Weigand47445072013-05-06 16:26:41 +00005316 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5317
5318 unsigned PaddedSize = PaddedBitSize / 8;
5319 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5320
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005321 llvm::Type *IndexTy = CGF.Int64Ty;
5322 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5323
5324 if (IsVector) {
5325 // Work out the address of a vector argument on the stack.
5326 // Vector arguments are always passed in the high bits of a
5327 // single (8 byte) or double (16 byte) stack slot.
5328 llvm::Value *OverflowArgAreaPtr =
5329 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 2,
5330 "overflow_arg_area_ptr");
5331 llvm::Value *OverflowArgArea =
5332 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5333 llvm::Value *MemAddr =
5334 CGF.Builder.CreateBitCast(OverflowArgArea, APTy, "mem_addr");
5335
5336 // Update overflow_arg_area_ptr pointer
5337 llvm::Value *NewOverflowArgArea =
5338 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5339 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5340
5341 return MemAddr;
5342 }
5343
Ulrich Weigand47445072013-05-06 16:26:41 +00005344 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5345 if (InFPRs) {
5346 MaxRegs = 4; // Maximum of 4 FPR arguments
5347 RegCountField = 1; // __fpr
5348 RegSaveIndex = 16; // save offset for f0
5349 RegPadding = 0; // floats are passed in the high bits of an FPR
5350 } else {
5351 MaxRegs = 5; // Maximum of 5 GPR arguments
5352 RegCountField = 0; // __gpr
5353 RegSaveIndex = 2; // save offset for r2
5354 RegPadding = Padding; // values are passed in the low bits of a GPR
5355 }
5356
David Blaikie2e804282015-04-05 22:47:07 +00005357 llvm::Value *RegCountPtr = CGF.Builder.CreateStructGEP(
5358 nullptr, VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005359 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005360 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5361 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005362 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005363
5364 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5365 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5366 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5367 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5368
5369 // Emit code to load the value if it was passed in registers.
5370 CGF.EmitBlock(InRegBlock);
5371
5372 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005373 llvm::Value *ScaledRegCount =
5374 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5375 llvm::Value *RegBase =
5376 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5377 llvm::Value *RegOffset =
5378 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5379 llvm::Value *RegSaveAreaPtr =
David Blaikie2e804282015-04-05 22:47:07 +00005380 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005381 llvm::Value *RegSaveArea =
5382 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5383 llvm::Value *RawRegAddr =
5384 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5385 llvm::Value *RegAddr =
5386 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5387
5388 // Update the register count
5389 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5390 llvm::Value *NewRegCount =
5391 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5392 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5393 CGF.EmitBranch(ContBlock);
5394
5395 // Emit code to load the value if it was passed in memory.
5396 CGF.EmitBlock(InMemBlock);
5397
5398 // Work out the address of a stack argument.
David Blaikie2e804282015-04-05 22:47:07 +00005399 llvm::Value *OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5400 nullptr, VAListAddr, 2, "overflow_arg_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005401 llvm::Value *OverflowArgArea =
5402 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5403 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5404 llvm::Value *RawMemAddr =
5405 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5406 llvm::Value *MemAddr =
5407 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5408
5409 // Update overflow_arg_area_ptr pointer
5410 llvm::Value *NewOverflowArgArea =
5411 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5412 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5413 CGF.EmitBranch(ContBlock);
5414
5415 // Return the appropriate result.
5416 CGF.EmitBlock(ContBlock);
5417 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5418 ResAddr->addIncoming(RegAddr, InRegBlock);
5419 ResAddr->addIncoming(MemAddr, InMemBlock);
5420
5421 if (IsIndirect)
5422 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5423
5424 return ResAddr;
5425}
5426
Ulrich Weigand47445072013-05-06 16:26:41 +00005427ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5428 if (RetTy->isVoidType())
5429 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005430 if (isVectorArgumentType(RetTy))
5431 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005432 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5433 return ABIArgInfo::getIndirect(0);
5434 return (isPromotableIntegerType(RetTy) ?
5435 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5436}
5437
5438ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5439 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005440 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005441 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5442
5443 // Integers and enums are extended to full register width.
5444 if (isPromotableIntegerType(Ty))
5445 return ABIArgInfo::getExtend();
5446
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005447 // Handle vector types and vector-like structure types. Note that
5448 // as opposed to float-like structure types, we do not allow any
5449 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005450 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005451 QualType SingleElementTy = GetSingleElementType(Ty);
5452 if (isVectorArgumentType(SingleElementTy) &&
5453 getContext().getTypeSize(SingleElementTy) == Size)
5454 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5455
5456 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005457 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005458 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005459
5460 // Handle small structures.
5461 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5462 // Structures with flexible arrays have variable length, so really
5463 // fail the size test above.
5464 const RecordDecl *RD = RT->getDecl();
5465 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005466 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005467
5468 // The structure is passed as an unextended integer, a float, or a double.
5469 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005470 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005471 assert(Size == 32 || Size == 64);
5472 if (Size == 32)
5473 PassTy = llvm::Type::getFloatTy(getVMContext());
5474 else
5475 PassTy = llvm::Type::getDoubleTy(getVMContext());
5476 } else
5477 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5478 return ABIArgInfo::getDirect(PassTy);
5479 }
5480
5481 // Non-structure compounds are passed indirectly.
5482 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005483 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005484
Craig Topper8a13c412014-05-21 05:09:00 +00005485 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005486}
5487
5488//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005489// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005490//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005491
5492namespace {
5493
5494class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5495public:
Chris Lattner2b037972010-07-29 02:01:43 +00005496 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5497 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005498 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005499 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005500};
5501
5502}
5503
5504void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5505 llvm::GlobalValue *GV,
5506 CodeGen::CodeGenModule &M) const {
5507 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5508 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5509 // Handle 'interrupt' attribute:
5510 llvm::Function *F = cast<llvm::Function>(GV);
5511
5512 // Step 1: Set ISR calling convention.
5513 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5514
5515 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005516 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005517
5518 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005519 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005520 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5521 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005522 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005523 }
5524}
5525
Chris Lattner0cf24192010-06-28 20:05:43 +00005526//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005527// MIPS ABI Implementation. This works for both little-endian and
5528// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005529//===----------------------------------------------------------------------===//
5530
John McCall943fae92010-05-27 06:19:26 +00005531namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005532class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005533 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005534 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5535 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005536 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005537 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005538 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005539 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005540public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005541 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005542 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005543 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005544
5545 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005546 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005547 void computeInfo(CGFunctionInfo &FI) const override;
5548 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5549 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005550};
5551
John McCall943fae92010-05-27 06:19:26 +00005552class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005553 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005554public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005555 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5556 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005557 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005558
Craig Topper4f12f102014-03-12 06:41:41 +00005559 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005560 return 29;
5561 }
5562
Reed Kotler373feca2013-01-16 17:10:28 +00005563 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005564 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005565 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5566 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005567 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005568 if (FD->hasAttr<Mips16Attr>()) {
5569 Fn->addFnAttr("mips16");
5570 }
5571 else if (FD->hasAttr<NoMips16Attr>()) {
5572 Fn->addFnAttr("nomips16");
5573 }
Reed Kotler373feca2013-01-16 17:10:28 +00005574 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005575
John McCall943fae92010-05-27 06:19:26 +00005576 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005577 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005578
Craig Topper4f12f102014-03-12 06:41:41 +00005579 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005580 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005581 }
John McCall943fae92010-05-27 06:19:26 +00005582};
5583}
5584
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005585void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005586 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005587 llvm::IntegerType *IntTy =
5588 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005589
5590 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5591 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5592 ArgList.push_back(IntTy);
5593
5594 // If necessary, add one more integer type to ArgList.
5595 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5596
5597 if (R)
5598 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005599}
5600
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005601// In N32/64, an aligned double precision floating point field is passed in
5602// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005603llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005604 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5605
5606 if (IsO32) {
5607 CoerceToIntArgs(TySize, ArgList);
5608 return llvm::StructType::get(getVMContext(), ArgList);
5609 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005610
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005611 if (Ty->isComplexType())
5612 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005613
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005614 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005615
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005616 // Unions/vectors are passed in integer registers.
5617 if (!RT || !RT->isStructureOrClassType()) {
5618 CoerceToIntArgs(TySize, ArgList);
5619 return llvm::StructType::get(getVMContext(), ArgList);
5620 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005621
5622 const RecordDecl *RD = RT->getDecl();
5623 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005624 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005625
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005626 uint64_t LastOffset = 0;
5627 unsigned idx = 0;
5628 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5629
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005630 // Iterate over fields in the struct/class and check if there are any aligned
5631 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005632 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5633 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005634 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005635 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5636
5637 if (!BT || BT->getKind() != BuiltinType::Double)
5638 continue;
5639
5640 uint64_t Offset = Layout.getFieldOffset(idx);
5641 if (Offset % 64) // Ignore doubles that are not aligned.
5642 continue;
5643
5644 // Add ((Offset - LastOffset) / 64) args of type i64.
5645 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5646 ArgList.push_back(I64);
5647
5648 // Add double type.
5649 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5650 LastOffset = Offset + 64;
5651 }
5652
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005653 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5654 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005655
5656 return llvm::StructType::get(getVMContext(), ArgList);
5657}
5658
Akira Hatanakaddd66342013-10-29 18:41:15 +00005659llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5660 uint64_t Offset) const {
5661 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005662 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005663
Akira Hatanakaddd66342013-10-29 18:41:15 +00005664 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005665}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005666
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005667ABIArgInfo
5668MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005669 Ty = useFirstFieldIfTransparentUnion(Ty);
5670
Akira Hatanaka1632af62012-01-09 19:31:25 +00005671 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005672 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005673 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005674
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005675 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5676 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005677 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5678 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005679
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005680 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005681 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005682 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005683 return ABIArgInfo::getIgnore();
5684
Mark Lacey3825e832013-10-06 01:33:34 +00005685 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005686 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005687 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005688 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005689
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005690 // If we have reached here, aggregates are passed directly by coercing to
5691 // another structure type. Padding is inserted if the offset of the
5692 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005693 ABIArgInfo ArgInfo =
5694 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5695 getPaddingType(OrigOffset, CurrOffset));
5696 ArgInfo.setInReg(true);
5697 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005698 }
5699
5700 // Treat an enum type as its underlying type.
5701 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5702 Ty = EnumTy->getDecl()->getIntegerType();
5703
Daniel Sanders5b445b32014-10-24 14:42:42 +00005704 // All integral types are promoted to the GPR width.
5705 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005706 return ABIArgInfo::getExtend();
5707
Akira Hatanakaddd66342013-10-29 18:41:15 +00005708 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005709 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005710}
5711
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005712llvm::Type*
5713MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005714 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005715 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005716
Akira Hatanakab6f74432012-02-09 18:49:26 +00005717 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005718 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005719 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5720 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005721
Akira Hatanakab6f74432012-02-09 18:49:26 +00005722 // N32/64 returns struct/classes in floating point registers if the
5723 // following conditions are met:
5724 // 1. The size of the struct/class is no larger than 128-bit.
5725 // 2. The struct/class has one or two fields all of which are floating
5726 // point types.
5727 // 3. The offset of the first field is zero (this follows what gcc does).
5728 //
5729 // Any other composite results are returned in integer registers.
5730 //
5731 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5732 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5733 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005734 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005735
Akira Hatanakab6f74432012-02-09 18:49:26 +00005736 if (!BT || !BT->isFloatingPoint())
5737 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005738
David Blaikie2d7c57e2012-04-30 02:36:29 +00005739 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005740 }
5741
5742 if (b == e)
5743 return llvm::StructType::get(getVMContext(), RTList,
5744 RD->hasAttr<PackedAttr>());
5745
5746 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005747 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005748 }
5749
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005750 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005751 return llvm::StructType::get(getVMContext(), RTList);
5752}
5753
Akira Hatanakab579fe52011-06-02 00:09:17 +00005754ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005755 uint64_t Size = getContext().getTypeSize(RetTy);
5756
Daniel Sandersed39f582014-09-04 13:28:14 +00005757 if (RetTy->isVoidType())
5758 return ABIArgInfo::getIgnore();
5759
5760 // O32 doesn't treat zero-sized structs differently from other structs.
5761 // However, N32/N64 ignores zero sized return values.
5762 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005763 return ABIArgInfo::getIgnore();
5764
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005765 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005766 if (Size <= 128) {
5767 if (RetTy->isAnyComplexType())
5768 return ABIArgInfo::getDirect();
5769
Daniel Sanderse5018b62014-09-04 15:05:39 +00005770 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005771 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005772 if (!IsO32 ||
5773 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5774 ABIArgInfo ArgInfo =
5775 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5776 ArgInfo.setInReg(true);
5777 return ArgInfo;
5778 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005779 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005780
5781 return ABIArgInfo::getIndirect(0);
5782 }
5783
5784 // Treat an enum type as its underlying type.
5785 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5786 RetTy = EnumTy->getDecl()->getIntegerType();
5787
5788 return (RetTy->isPromotableIntegerType() ?
5789 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5790}
5791
5792void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005793 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005794 if (!getCXXABI().classifyReturnType(FI))
5795 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005796
5797 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005798 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005799
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005800 for (auto &I : FI.arguments())
5801 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005802}
5803
5804llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5805 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005806 llvm::Type *BP = CGF.Int8PtrTy;
5807 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005808
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005809 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5810 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005811 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005812 unsigned PtrWidth = getTarget().getPointerWidth(0);
5813 if ((Ty->isIntegerType() &&
5814 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5815 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005816 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5817 Ty->isSignedIntegerType());
5818 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005819
5820 CGBuilderTy &Builder = CGF.Builder;
5821 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5822 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005823 int64_t TypeAlign =
5824 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005825 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5826 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005827 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5828
5829 if (TypeAlign > MinABIStackAlignInBytes) {
5830 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5831 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5832 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5833 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5834 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5835 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5836 }
5837 else
5838 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5839
5840 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5841 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005842 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5843 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005844 llvm::Value *NextAddr =
5845 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5846 "ap.next");
5847 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5848
5849 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005850}
5851
John McCall943fae92010-05-27 06:19:26 +00005852bool
5853MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5854 llvm::Value *Address) const {
5855 // This information comes from gcc's implementation, which seems to
5856 // as canonical as it gets.
5857
John McCall943fae92010-05-27 06:19:26 +00005858 // Everything on MIPS is 4 bytes. Double-precision FP registers
5859 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005860 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005861
5862 // 0-31 are the general purpose registers, $0 - $31.
5863 // 32-63 are the floating-point registers, $f0 - $f31.
5864 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5865 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005866 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005867
5868 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5869 // They are one bit wide and ignored here.
5870
5871 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5872 // (coprocessor 1 is the FP unit)
5873 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5874 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5875 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005876 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005877 return false;
5878}
5879
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005880//===----------------------------------------------------------------------===//
5881// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5882// Currently subclassed only to implement custom OpenCL C function attribute
5883// handling.
5884//===----------------------------------------------------------------------===//
5885
5886namespace {
5887
5888class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5889public:
5890 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5891 : DefaultTargetCodeGenInfo(CGT) {}
5892
Craig Topper4f12f102014-03-12 06:41:41 +00005893 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5894 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005895};
5896
5897void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5898 llvm::GlobalValue *GV,
5899 CodeGen::CodeGenModule &M) const {
5900 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5901 if (!FD) return;
5902
5903 llvm::Function *F = cast<llvm::Function>(GV);
5904
David Blaikiebbafb8a2012-03-11 07:00:24 +00005905 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005906 if (FD->hasAttr<OpenCLKernelAttr>()) {
5907 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005908 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005909 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5910 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005911 // Convert the reqd_work_group_size() attributes to metadata.
5912 llvm::LLVMContext &Context = F->getContext();
5913 llvm::NamedMDNode *OpenCLMetadata =
5914 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5915
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005916 SmallVector<llvm::Metadata *, 5> Operands;
5917 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005918
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005919 Operands.push_back(
5920 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5921 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5922 Operands.push_back(
5923 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5924 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5925 Operands.push_back(
5926 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5927 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005928
5929 // Add a boolean constant operand for "required" (true) or "hint" (false)
5930 // for implementing the work_group_size_hint attr later. Currently
5931 // always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005932 Operands.push_back(
5933 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005934 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5935 }
5936 }
5937 }
5938}
5939
5940}
John McCall943fae92010-05-27 06:19:26 +00005941
Tony Linthicum76329bf2011-12-12 21:14:55 +00005942//===----------------------------------------------------------------------===//
5943// Hexagon ABI Implementation
5944//===----------------------------------------------------------------------===//
5945
5946namespace {
5947
5948class HexagonABIInfo : public ABIInfo {
5949
5950
5951public:
5952 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5953
5954private:
5955
5956 ABIArgInfo classifyReturnType(QualType RetTy) const;
5957 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5958
Craig Topper4f12f102014-03-12 06:41:41 +00005959 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005960
Craig Topper4f12f102014-03-12 06:41:41 +00005961 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5962 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005963};
5964
5965class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5966public:
5967 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5968 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5969
Craig Topper4f12f102014-03-12 06:41:41 +00005970 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005971 return 29;
5972 }
5973};
5974
5975}
5976
5977void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005978 if (!getCXXABI().classifyReturnType(FI))
5979 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005980 for (auto &I : FI.arguments())
5981 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005982}
5983
5984ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5985 if (!isAggregateTypeForABI(Ty)) {
5986 // Treat an enum type as its underlying type.
5987 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5988 Ty = EnumTy->getDecl()->getIntegerType();
5989
5990 return (Ty->isPromotableIntegerType() ?
5991 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5992 }
5993
5994 // Ignore empty records.
5995 if (isEmptyRecord(getContext(), Ty, true))
5996 return ABIArgInfo::getIgnore();
5997
Mark Lacey3825e832013-10-06 01:33:34 +00005998 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005999 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006000
6001 uint64_t Size = getContext().getTypeSize(Ty);
6002 if (Size > 64)
6003 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6004 // Pass in the smallest viable integer type.
6005 else if (Size > 32)
6006 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6007 else if (Size > 16)
6008 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6009 else if (Size > 8)
6010 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6011 else
6012 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6013}
6014
6015ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6016 if (RetTy->isVoidType())
6017 return ABIArgInfo::getIgnore();
6018
6019 // Large vector types should be returned via memory.
6020 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6021 return ABIArgInfo::getIndirect(0);
6022
6023 if (!isAggregateTypeForABI(RetTy)) {
6024 // Treat an enum type as its underlying type.
6025 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6026 RetTy = EnumTy->getDecl()->getIntegerType();
6027
6028 return (RetTy->isPromotableIntegerType() ?
6029 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6030 }
6031
Tony Linthicum76329bf2011-12-12 21:14:55 +00006032 if (isEmptyRecord(getContext(), RetTy, true))
6033 return ABIArgInfo::getIgnore();
6034
6035 // Aggregates <= 8 bytes are returned in r0; other aggregates
6036 // are returned indirectly.
6037 uint64_t Size = getContext().getTypeSize(RetTy);
6038 if (Size <= 64) {
6039 // Return in the smallest viable integer type.
6040 if (Size <= 8)
6041 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6042 if (Size <= 16)
6043 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6044 if (Size <= 32)
6045 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6046 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6047 }
6048
6049 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6050}
6051
6052llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006053 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006054 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006055 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006056
6057 CGBuilderTy &Builder = CGF.Builder;
6058 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6059 "ap");
6060 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6061 llvm::Type *PTy =
6062 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6063 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6064
6065 uint64_t Offset =
6066 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6067 llvm::Value *NextAddr =
6068 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6069 "ap.next");
6070 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6071
6072 return AddrTyped;
6073}
6074
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006075//===----------------------------------------------------------------------===//
6076// AMDGPU ABI Implementation
6077//===----------------------------------------------------------------------===//
6078
6079namespace {
6080
6081class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6082public:
6083 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6084 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6085 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6086 CodeGen::CodeGenModule &M) const override;
6087};
6088
6089}
6090
6091void AMDGPUTargetCodeGenInfo::SetTargetAttributes(
6092 const Decl *D,
6093 llvm::GlobalValue *GV,
6094 CodeGen::CodeGenModule &M) const {
6095 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6096 if (!FD)
6097 return;
6098
6099 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6100 llvm::Function *F = cast<llvm::Function>(GV);
6101 uint32_t NumVGPR = Attr->getNumVGPR();
6102 if (NumVGPR != 0)
6103 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6104 }
6105
6106 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6107 llvm::Function *F = cast<llvm::Function>(GV);
6108 unsigned NumSGPR = Attr->getNumSGPR();
6109 if (NumSGPR != 0)
6110 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6111 }
6112}
6113
Tony Linthicum76329bf2011-12-12 21:14:55 +00006114
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006115//===----------------------------------------------------------------------===//
6116// SPARC v9 ABI Implementation.
6117// Based on the SPARC Compliance Definition version 2.4.1.
6118//
6119// Function arguments a mapped to a nominal "parameter array" and promoted to
6120// registers depending on their type. Each argument occupies 8 or 16 bytes in
6121// the array, structs larger than 16 bytes are passed indirectly.
6122//
6123// One case requires special care:
6124//
6125// struct mixed {
6126// int i;
6127// float f;
6128// };
6129//
6130// When a struct mixed is passed by value, it only occupies 8 bytes in the
6131// parameter array, but the int is passed in an integer register, and the float
6132// is passed in a floating point register. This is represented as two arguments
6133// with the LLVM IR inreg attribute:
6134//
6135// declare void f(i32 inreg %i, float inreg %f)
6136//
6137// The code generator will only allocate 4 bytes from the parameter array for
6138// the inreg arguments. All other arguments are allocated a multiple of 8
6139// bytes.
6140//
6141namespace {
6142class SparcV9ABIInfo : public ABIInfo {
6143public:
6144 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6145
6146private:
6147 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006148 void computeInfo(CGFunctionInfo &FI) const override;
6149 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6150 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006151
6152 // Coercion type builder for structs passed in registers. The coercion type
6153 // serves two purposes:
6154 //
6155 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6156 // in registers.
6157 // 2. Expose aligned floating point elements as first-level elements, so the
6158 // code generator knows to pass them in floating point registers.
6159 //
6160 // We also compute the InReg flag which indicates that the struct contains
6161 // aligned 32-bit floats.
6162 //
6163 struct CoerceBuilder {
6164 llvm::LLVMContext &Context;
6165 const llvm::DataLayout &DL;
6166 SmallVector<llvm::Type*, 8> Elems;
6167 uint64_t Size;
6168 bool InReg;
6169
6170 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6171 : Context(c), DL(dl), Size(0), InReg(false) {}
6172
6173 // Pad Elems with integers until Size is ToSize.
6174 void pad(uint64_t ToSize) {
6175 assert(ToSize >= Size && "Cannot remove elements");
6176 if (ToSize == Size)
6177 return;
6178
6179 // Finish the current 64-bit word.
6180 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6181 if (Aligned > Size && Aligned <= ToSize) {
6182 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6183 Size = Aligned;
6184 }
6185
6186 // Add whole 64-bit words.
6187 while (Size + 64 <= ToSize) {
6188 Elems.push_back(llvm::Type::getInt64Ty(Context));
6189 Size += 64;
6190 }
6191
6192 // Final in-word padding.
6193 if (Size < ToSize) {
6194 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6195 Size = ToSize;
6196 }
6197 }
6198
6199 // Add a floating point element at Offset.
6200 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6201 // Unaligned floats are treated as integers.
6202 if (Offset % Bits)
6203 return;
6204 // The InReg flag is only required if there are any floats < 64 bits.
6205 if (Bits < 64)
6206 InReg = true;
6207 pad(Offset);
6208 Elems.push_back(Ty);
6209 Size = Offset + Bits;
6210 }
6211
6212 // Add a struct type to the coercion type, starting at Offset (in bits).
6213 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6214 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6215 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6216 llvm::Type *ElemTy = StrTy->getElementType(i);
6217 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6218 switch (ElemTy->getTypeID()) {
6219 case llvm::Type::StructTyID:
6220 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6221 break;
6222 case llvm::Type::FloatTyID:
6223 addFloat(ElemOffset, ElemTy, 32);
6224 break;
6225 case llvm::Type::DoubleTyID:
6226 addFloat(ElemOffset, ElemTy, 64);
6227 break;
6228 case llvm::Type::FP128TyID:
6229 addFloat(ElemOffset, ElemTy, 128);
6230 break;
6231 case llvm::Type::PointerTyID:
6232 if (ElemOffset % 64 == 0) {
6233 pad(ElemOffset);
6234 Elems.push_back(ElemTy);
6235 Size += 64;
6236 }
6237 break;
6238 default:
6239 break;
6240 }
6241 }
6242 }
6243
6244 // Check if Ty is a usable substitute for the coercion type.
6245 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006246 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006247 }
6248
6249 // Get the coercion type as a literal struct type.
6250 llvm::Type *getType() const {
6251 if (Elems.size() == 1)
6252 return Elems.front();
6253 else
6254 return llvm::StructType::get(Context, Elems);
6255 }
6256 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006257};
6258} // end anonymous namespace
6259
6260ABIArgInfo
6261SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6262 if (Ty->isVoidType())
6263 return ABIArgInfo::getIgnore();
6264
6265 uint64_t Size = getContext().getTypeSize(Ty);
6266
6267 // Anything too big to fit in registers is passed with an explicit indirect
6268 // pointer / sret pointer.
6269 if (Size > SizeLimit)
6270 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6271
6272 // Treat an enum type as its underlying type.
6273 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6274 Ty = EnumTy->getDecl()->getIntegerType();
6275
6276 // Integer types smaller than a register are extended.
6277 if (Size < 64 && Ty->isIntegerType())
6278 return ABIArgInfo::getExtend();
6279
6280 // Other non-aggregates go in registers.
6281 if (!isAggregateTypeForABI(Ty))
6282 return ABIArgInfo::getDirect();
6283
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006284 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6285 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6286 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6287 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6288
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006289 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006290 // Build a coercion type from the LLVM struct type.
6291 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6292 if (!StrTy)
6293 return ABIArgInfo::getDirect();
6294
6295 CoerceBuilder CB(getVMContext(), getDataLayout());
6296 CB.addStruct(0, StrTy);
6297 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6298
6299 // Try to use the original type for coercion.
6300 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6301
6302 if (CB.InReg)
6303 return ABIArgInfo::getDirectInReg(CoerceTy);
6304 else
6305 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006306}
6307
6308llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6309 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006310 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6311 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6312 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6313 AI.setCoerceToType(ArgTy);
6314
6315 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6316 CGBuilderTy &Builder = CGF.Builder;
6317 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6318 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6319 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6320 llvm::Value *ArgAddr;
6321 unsigned Stride;
6322
6323 switch (AI.getKind()) {
6324 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006325 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006326 llvm_unreachable("Unsupported ABI kind for va_arg");
6327
6328 case ABIArgInfo::Extend:
6329 Stride = 8;
6330 ArgAddr = Builder
6331 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6332 "extend");
6333 break;
6334
6335 case ABIArgInfo::Direct:
6336 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6337 ArgAddr = Addr;
6338 break;
6339
6340 case ABIArgInfo::Indirect:
6341 Stride = 8;
6342 ArgAddr = Builder.CreateBitCast(Addr,
6343 llvm::PointerType::getUnqual(ArgPtrTy),
6344 "indirect");
6345 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6346 break;
6347
6348 case ABIArgInfo::Ignore:
6349 return llvm::UndefValue::get(ArgPtrTy);
6350 }
6351
6352 // Update VAList.
6353 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6354 Builder.CreateStore(Addr, VAListAddrAsBPP);
6355
6356 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006357}
6358
6359void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6360 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006361 for (auto &I : FI.arguments())
6362 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006363}
6364
6365namespace {
6366class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6367public:
6368 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6369 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006370
Craig Topper4f12f102014-03-12 06:41:41 +00006371 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006372 return 14;
6373 }
6374
6375 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006376 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006377};
6378} // end anonymous namespace
6379
Roman Divackyf02c9942014-02-24 18:46:27 +00006380bool
6381SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6382 llvm::Value *Address) const {
6383 // This is calculated from the LLVM and GCC tables and verified
6384 // against gcc output. AFAIK all ABIs use the same encoding.
6385
6386 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6387
6388 llvm::IntegerType *i8 = CGF.Int8Ty;
6389 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6390 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6391
6392 // 0-31: the 8-byte general-purpose registers
6393 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6394
6395 // 32-63: f0-31, the 4-byte floating-point registers
6396 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6397
6398 // Y = 64
6399 // PSR = 65
6400 // WIM = 66
6401 // TBR = 67
6402 // PC = 68
6403 // NPC = 69
6404 // FSR = 70
6405 // CSR = 71
6406 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6407
6408 // 72-87: d0-15, the 8-byte floating-point registers
6409 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6410
6411 return false;
6412}
6413
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006414
Robert Lytton0e076492013-08-13 09:43:10 +00006415//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006416// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006417//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006418
Robert Lytton0e076492013-08-13 09:43:10 +00006419namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006420
6421/// A SmallStringEnc instance is used to build up the TypeString by passing
6422/// it by reference between functions that append to it.
6423typedef llvm::SmallString<128> SmallStringEnc;
6424
6425/// TypeStringCache caches the meta encodings of Types.
6426///
6427/// The reason for caching TypeStrings is two fold:
6428/// 1. To cache a type's encoding for later uses;
6429/// 2. As a means to break recursive member type inclusion.
6430///
6431/// A cache Entry can have a Status of:
6432/// NonRecursive: The type encoding is not recursive;
6433/// Recursive: The type encoding is recursive;
6434/// Incomplete: An incomplete TypeString;
6435/// IncompleteUsed: An incomplete TypeString that has been used in a
6436/// Recursive type encoding.
6437///
6438/// A NonRecursive entry will have all of its sub-members expanded as fully
6439/// as possible. Whilst it may contain types which are recursive, the type
6440/// itself is not recursive and thus its encoding may be safely used whenever
6441/// the type is encountered.
6442///
6443/// A Recursive entry will have all of its sub-members expanded as fully as
6444/// possible. The type itself is recursive and it may contain other types which
6445/// are recursive. The Recursive encoding must not be used during the expansion
6446/// of a recursive type's recursive branch. For simplicity the code uses
6447/// IncompleteCount to reject all usage of Recursive encodings for member types.
6448///
6449/// An Incomplete entry is always a RecordType and only encodes its
6450/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6451/// are placed into the cache during type expansion as a means to identify and
6452/// handle recursive inclusion of types as sub-members. If there is recursion
6453/// the entry becomes IncompleteUsed.
6454///
6455/// During the expansion of a RecordType's members:
6456///
6457/// If the cache contains a NonRecursive encoding for the member type, the
6458/// cached encoding is used;
6459///
6460/// If the cache contains a Recursive encoding for the member type, the
6461/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6462///
6463/// If the member is a RecordType, an Incomplete encoding is placed into the
6464/// cache to break potential recursive inclusion of itself as a sub-member;
6465///
6466/// Once a member RecordType has been expanded, its temporary incomplete
6467/// entry is removed from the cache. If a Recursive encoding was swapped out
6468/// it is swapped back in;
6469///
6470/// If an incomplete entry is used to expand a sub-member, the incomplete
6471/// entry is marked as IncompleteUsed. The cache keeps count of how many
6472/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6473///
6474/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6475/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6476/// Else the member is part of a recursive type and thus the recursion has
6477/// been exited too soon for the encoding to be correct for the member.
6478///
6479class TypeStringCache {
6480 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6481 struct Entry {
6482 std::string Str; // The encoded TypeString for the type.
6483 enum Status State; // Information about the encoding in 'Str'.
6484 std::string Swapped; // A temporary place holder for a Recursive encoding
6485 // during the expansion of RecordType's members.
6486 };
6487 std::map<const IdentifierInfo *, struct Entry> Map;
6488 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6489 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6490public:
Robert Lyttond263f142014-05-06 09:38:54 +00006491 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006492 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6493 bool removeIncomplete(const IdentifierInfo *ID);
6494 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6495 bool IsRecursive);
6496 StringRef lookupStr(const IdentifierInfo *ID);
6497};
6498
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006499/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006500/// FieldEncoding is a helper for this ordering process.
6501class FieldEncoding {
6502 bool HasName;
6503 std::string Enc;
6504public:
6505 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6506 StringRef str() {return Enc.c_str();};
6507 bool operator<(const FieldEncoding &rhs) const {
6508 if (HasName != rhs.HasName) return HasName;
6509 return Enc < rhs.Enc;
6510 }
6511};
6512
Robert Lytton7d1db152013-08-19 09:46:39 +00006513class XCoreABIInfo : public DefaultABIInfo {
6514public:
6515 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006516 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6517 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006518};
6519
Robert Lyttond21e2d72014-03-03 13:45:29 +00006520class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006521 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006522public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006523 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006524 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006525 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6526 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006527};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006528
Robert Lytton2d196952013-10-11 10:29:34 +00006529} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006530
Robert Lytton7d1db152013-08-19 09:46:39 +00006531llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6532 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006533 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006534
Robert Lytton2d196952013-10-11 10:29:34 +00006535 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006536 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6537 CGF.Int8PtrPtrTy);
6538 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006539
Robert Lytton2d196952013-10-11 10:29:34 +00006540 // Handle the argument.
6541 ABIArgInfo AI = classifyArgumentType(Ty);
6542 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6543 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6544 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006545 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006546 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006547 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006548 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006549 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006550 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006551 llvm_unreachable("Unsupported ABI kind for va_arg");
6552 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006553 Val = llvm::UndefValue::get(ArgPtrTy);
6554 ArgSize = 0;
6555 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006556 case ABIArgInfo::Extend:
6557 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006558 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6559 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6560 if (ArgSize < 4)
6561 ArgSize = 4;
6562 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006563 case ABIArgInfo::Indirect:
6564 llvm::Value *ArgAddr;
6565 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6566 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006567 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6568 ArgSize = 4;
6569 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006570 }
Robert Lytton2d196952013-10-11 10:29:34 +00006571
6572 // Increment the VAList.
6573 if (ArgSize) {
6574 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6575 Builder.CreateStore(APN, VAListAddrAsBPP);
6576 }
6577 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006578}
Robert Lytton0e076492013-08-13 09:43:10 +00006579
Robert Lytton844aeeb2014-05-02 09:33:20 +00006580/// During the expansion of a RecordType, an incomplete TypeString is placed
6581/// into the cache as a means to identify and break recursion.
6582/// If there is a Recursive encoding in the cache, it is swapped out and will
6583/// be reinserted by removeIncomplete().
6584/// All other types of encoding should have been used rather than arriving here.
6585void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6586 std::string StubEnc) {
6587 if (!ID)
6588 return;
6589 Entry &E = Map[ID];
6590 assert( (E.Str.empty() || E.State == Recursive) &&
6591 "Incorrectly use of addIncomplete");
6592 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6593 E.Swapped.swap(E.Str); // swap out the Recursive
6594 E.Str.swap(StubEnc);
6595 E.State = Incomplete;
6596 ++IncompleteCount;
6597}
6598
6599/// Once the RecordType has been expanded, the temporary incomplete TypeString
6600/// must be removed from the cache.
6601/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6602/// Returns true if the RecordType was defined recursively.
6603bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6604 if (!ID)
6605 return false;
6606 auto I = Map.find(ID);
6607 assert(I != Map.end() && "Entry not present");
6608 Entry &E = I->second;
6609 assert( (E.State == Incomplete ||
6610 E.State == IncompleteUsed) &&
6611 "Entry must be an incomplete type");
6612 bool IsRecursive = false;
6613 if (E.State == IncompleteUsed) {
6614 // We made use of our Incomplete encoding, thus we are recursive.
6615 IsRecursive = true;
6616 --IncompleteUsedCount;
6617 }
6618 if (E.Swapped.empty())
6619 Map.erase(I);
6620 else {
6621 // Swap the Recursive back.
6622 E.Swapped.swap(E.Str);
6623 E.Swapped.clear();
6624 E.State = Recursive;
6625 }
6626 --IncompleteCount;
6627 return IsRecursive;
6628}
6629
6630/// Add the encoded TypeString to the cache only if it is NonRecursive or
6631/// Recursive (viz: all sub-members were expanded as fully as possible).
6632void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6633 bool IsRecursive) {
6634 if (!ID || IncompleteUsedCount)
6635 return; // No key or it is is an incomplete sub-type so don't add.
6636 Entry &E = Map[ID];
6637 if (IsRecursive && !E.Str.empty()) {
6638 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6639 "This is not the same Recursive entry");
6640 // The parent container was not recursive after all, so we could have used
6641 // this Recursive sub-member entry after all, but we assumed the worse when
6642 // we started viz: IncompleteCount!=0.
6643 return;
6644 }
6645 assert(E.Str.empty() && "Entry already present");
6646 E.Str = Str.str();
6647 E.State = IsRecursive? Recursive : NonRecursive;
6648}
6649
6650/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6651/// are recursively expanding a type (IncompleteCount != 0) and the cached
6652/// encoding is Recursive, return an empty StringRef.
6653StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6654 if (!ID)
6655 return StringRef(); // We have no key.
6656 auto I = Map.find(ID);
6657 if (I == Map.end())
6658 return StringRef(); // We have no encoding.
6659 Entry &E = I->second;
6660 if (E.State == Recursive && IncompleteCount)
6661 return StringRef(); // We don't use Recursive encodings for member types.
6662
6663 if (E.State == Incomplete) {
6664 // The incomplete type is being used to break out of recursion.
6665 E.State = IncompleteUsed;
6666 ++IncompleteUsedCount;
6667 }
6668 return E.Str.c_str();
6669}
6670
6671/// The XCore ABI includes a type information section that communicates symbol
6672/// type information to the linker. The linker uses this information to verify
6673/// safety/correctness of things such as array bound and pointers et al.
6674/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6675/// This type information (TypeString) is emitted into meta data for all global
6676/// symbols: definitions, declarations, functions & variables.
6677///
6678/// The TypeString carries type, qualifier, name, size & value details.
6679/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6680/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6681/// The output is tested by test/CodeGen/xcore-stringtype.c.
6682///
6683static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6684 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6685
6686/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6687void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6688 CodeGen::CodeGenModule &CGM) const {
6689 SmallStringEnc Enc;
6690 if (getTypeString(Enc, D, CGM, TSC)) {
6691 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006692 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6693 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006694 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6695 llvm::NamedMDNode *MD =
6696 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6697 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6698 }
6699}
6700
6701static bool appendType(SmallStringEnc &Enc, QualType QType,
6702 const CodeGen::CodeGenModule &CGM,
6703 TypeStringCache &TSC);
6704
6705/// Helper function for appendRecordType().
6706/// Builds a SmallVector containing the encoded field types in declaration order.
6707static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6708 const RecordDecl *RD,
6709 const CodeGen::CodeGenModule &CGM,
6710 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006711 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006712 SmallStringEnc Enc;
6713 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006714 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006715 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006716 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006717 Enc += "b(";
6718 llvm::raw_svector_ostream OS(Enc);
6719 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006720 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006721 OS.flush();
6722 Enc += ':';
6723 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006724 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006725 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006726 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006727 Enc += ')';
6728 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006729 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006730 }
6731 return true;
6732}
6733
6734/// Appends structure and union types to Enc and adds encoding to cache.
6735/// Recursively calls appendType (via extractFieldType) for each field.
6736/// Union types have their fields ordered according to the ABI.
6737static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6738 const CodeGen::CodeGenModule &CGM,
6739 TypeStringCache &TSC, const IdentifierInfo *ID) {
6740 // Append the cached TypeString if we have one.
6741 StringRef TypeString = TSC.lookupStr(ID);
6742 if (!TypeString.empty()) {
6743 Enc += TypeString;
6744 return true;
6745 }
6746
6747 // Start to emit an incomplete TypeString.
6748 size_t Start = Enc.size();
6749 Enc += (RT->isUnionType()? 'u' : 's');
6750 Enc += '(';
6751 if (ID)
6752 Enc += ID->getName();
6753 Enc += "){";
6754
6755 // We collect all encoded fields and order as necessary.
6756 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006757 const RecordDecl *RD = RT->getDecl()->getDefinition();
6758 if (RD && !RD->field_empty()) {
6759 // An incomplete TypeString stub is placed in the cache for this RecordType
6760 // so that recursive calls to this RecordType will use it whilst building a
6761 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006762 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006763 std::string StubEnc(Enc.substr(Start).str());
6764 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6765 TSC.addIncomplete(ID, std::move(StubEnc));
6766 if (!extractFieldType(FE, RD, CGM, TSC)) {
6767 (void) TSC.removeIncomplete(ID);
6768 return false;
6769 }
6770 IsRecursive = TSC.removeIncomplete(ID);
6771 // The ABI requires unions to be sorted but not structures.
6772 // See FieldEncoding::operator< for sort algorithm.
6773 if (RT->isUnionType())
6774 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006775 // We can now complete the TypeString.
6776 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006777 for (unsigned I = 0; I != E; ++I) {
6778 if (I)
6779 Enc += ',';
6780 Enc += FE[I].str();
6781 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006782 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006783 Enc += '}';
6784 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6785 return true;
6786}
6787
6788/// Appends enum types to Enc and adds the encoding to the cache.
6789static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6790 TypeStringCache &TSC,
6791 const IdentifierInfo *ID) {
6792 // Append the cached TypeString if we have one.
6793 StringRef TypeString = TSC.lookupStr(ID);
6794 if (!TypeString.empty()) {
6795 Enc += TypeString;
6796 return true;
6797 }
6798
6799 size_t Start = Enc.size();
6800 Enc += "e(";
6801 if (ID)
6802 Enc += ID->getName();
6803 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006804
6805 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006806 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006807 SmallVector<FieldEncoding, 16> FE;
6808 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6809 ++I) {
6810 SmallStringEnc EnumEnc;
6811 EnumEnc += "m(";
6812 EnumEnc += I->getName();
6813 EnumEnc += "){";
6814 I->getInitVal().toString(EnumEnc);
6815 EnumEnc += '}';
6816 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6817 }
6818 std::sort(FE.begin(), FE.end());
6819 unsigned E = FE.size();
6820 for (unsigned I = 0; I != E; ++I) {
6821 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006822 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006823 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006824 }
6825 }
6826 Enc += '}';
6827 TSC.addIfComplete(ID, Enc.substr(Start), false);
6828 return true;
6829}
6830
6831/// Appends type's qualifier to Enc.
6832/// This is done prior to appending the type's encoding.
6833static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6834 // Qualifiers are emitted in alphabetical order.
6835 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6836 int Lookup = 0;
6837 if (QT.isConstQualified())
6838 Lookup += 1<<0;
6839 if (QT.isRestrictQualified())
6840 Lookup += 1<<1;
6841 if (QT.isVolatileQualified())
6842 Lookup += 1<<2;
6843 Enc += Table[Lookup];
6844}
6845
6846/// Appends built-in types to Enc.
6847static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6848 const char *EncType;
6849 switch (BT->getKind()) {
6850 case BuiltinType::Void:
6851 EncType = "0";
6852 break;
6853 case BuiltinType::Bool:
6854 EncType = "b";
6855 break;
6856 case BuiltinType::Char_U:
6857 EncType = "uc";
6858 break;
6859 case BuiltinType::UChar:
6860 EncType = "uc";
6861 break;
6862 case BuiltinType::SChar:
6863 EncType = "sc";
6864 break;
6865 case BuiltinType::UShort:
6866 EncType = "us";
6867 break;
6868 case BuiltinType::Short:
6869 EncType = "ss";
6870 break;
6871 case BuiltinType::UInt:
6872 EncType = "ui";
6873 break;
6874 case BuiltinType::Int:
6875 EncType = "si";
6876 break;
6877 case BuiltinType::ULong:
6878 EncType = "ul";
6879 break;
6880 case BuiltinType::Long:
6881 EncType = "sl";
6882 break;
6883 case BuiltinType::ULongLong:
6884 EncType = "ull";
6885 break;
6886 case BuiltinType::LongLong:
6887 EncType = "sll";
6888 break;
6889 case BuiltinType::Float:
6890 EncType = "ft";
6891 break;
6892 case BuiltinType::Double:
6893 EncType = "d";
6894 break;
6895 case BuiltinType::LongDouble:
6896 EncType = "ld";
6897 break;
6898 default:
6899 return false;
6900 }
6901 Enc += EncType;
6902 return true;
6903}
6904
6905/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6906static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6907 const CodeGen::CodeGenModule &CGM,
6908 TypeStringCache &TSC) {
6909 Enc += "p(";
6910 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6911 return false;
6912 Enc += ')';
6913 return true;
6914}
6915
6916/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006917static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6918 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006919 const CodeGen::CodeGenModule &CGM,
6920 TypeStringCache &TSC, StringRef NoSizeEnc) {
6921 if (AT->getSizeModifier() != ArrayType::Normal)
6922 return false;
6923 Enc += "a(";
6924 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6925 CAT->getSize().toStringUnsigned(Enc);
6926 else
6927 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6928 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006929 // The Qualifiers should be attached to the type rather than the array.
6930 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006931 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6932 return false;
6933 Enc += ')';
6934 return true;
6935}
6936
6937/// Appends a function encoding to Enc, calling appendType for the return type
6938/// and the arguments.
6939static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6940 const CodeGen::CodeGenModule &CGM,
6941 TypeStringCache &TSC) {
6942 Enc += "f{";
6943 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6944 return false;
6945 Enc += "}(";
6946 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6947 // N.B. we are only interested in the adjusted param types.
6948 auto I = FPT->param_type_begin();
6949 auto E = FPT->param_type_end();
6950 if (I != E) {
6951 do {
6952 if (!appendType(Enc, *I, CGM, TSC))
6953 return false;
6954 ++I;
6955 if (I != E)
6956 Enc += ',';
6957 } while (I != E);
6958 if (FPT->isVariadic())
6959 Enc += ",va";
6960 } else {
6961 if (FPT->isVariadic())
6962 Enc += "va";
6963 else
6964 Enc += '0';
6965 }
6966 }
6967 Enc += ')';
6968 return true;
6969}
6970
6971/// Handles the type's qualifier before dispatching a call to handle specific
6972/// type encodings.
6973static bool appendType(SmallStringEnc &Enc, QualType QType,
6974 const CodeGen::CodeGenModule &CGM,
6975 TypeStringCache &TSC) {
6976
6977 QualType QT = QType.getCanonicalType();
6978
Robert Lytton6adb20f2014-06-05 09:06:21 +00006979 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6980 // The Qualifiers should be attached to the type rather than the array.
6981 // Thus we don't call appendQualifier() here.
6982 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6983
Robert Lytton844aeeb2014-05-02 09:33:20 +00006984 appendQualifier(Enc, QT);
6985
6986 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6987 return appendBuiltinType(Enc, BT);
6988
Robert Lytton844aeeb2014-05-02 09:33:20 +00006989 if (const PointerType *PT = QT->getAs<PointerType>())
6990 return appendPointerType(Enc, PT, CGM, TSC);
6991
6992 if (const EnumType *ET = QT->getAs<EnumType>())
6993 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6994
6995 if (const RecordType *RT = QT->getAsStructureType())
6996 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6997
6998 if (const RecordType *RT = QT->getAsUnionType())
6999 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7000
7001 if (const FunctionType *FT = QT->getAs<FunctionType>())
7002 return appendFunctionType(Enc, FT, CGM, TSC);
7003
7004 return false;
7005}
7006
7007static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7008 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7009 if (!D)
7010 return false;
7011
7012 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7013 if (FD->getLanguageLinkage() != CLanguageLinkage)
7014 return false;
7015 return appendType(Enc, FD->getType(), CGM, TSC);
7016 }
7017
7018 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7019 if (VD->getLanguageLinkage() != CLanguageLinkage)
7020 return false;
7021 QualType QT = VD->getType().getCanonicalType();
7022 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7023 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007024 // The Qualifiers should be attached to the type rather than the array.
7025 // Thus we don't call appendQualifier() here.
7026 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007027 }
7028 return appendType(Enc, QT, CGM, TSC);
7029 }
7030 return false;
7031}
7032
7033
Robert Lytton0e076492013-08-13 09:43:10 +00007034//===----------------------------------------------------------------------===//
7035// Driver code
7036//===----------------------------------------------------------------------===//
7037
Rafael Espindola9f834732014-09-19 01:54:22 +00007038const llvm::Triple &CodeGenModule::getTriple() const {
7039 return getTarget().getTriple();
7040}
7041
7042bool CodeGenModule::supportsCOMDAT() const {
7043 return !getTriple().isOSBinFormatMachO();
7044}
7045
Chris Lattner2b037972010-07-29 02:01:43 +00007046const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007047 if (TheTargetCodeGenInfo)
7048 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007049
John McCallc8e01702013-04-16 22:48:15 +00007050 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007051 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007052 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007053 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007054
Derek Schuff09338a22012-09-06 17:37:28 +00007055 case llvm::Triple::le32:
7056 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007057 case llvm::Triple::mips:
7058 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007059 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7060
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007061 case llvm::Triple::mips64:
7062 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007063 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7064
Tim Northover25e8a672014-05-24 12:51:25 +00007065 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007066 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007067 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007068 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007069 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007070
Tim Northover573cbee2014-05-24 12:52:07 +00007071 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007072 }
7073
Daniel Dunbard59655c2009-09-12 00:59:49 +00007074 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007075 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007076 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007077 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007078 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007079 if (Triple.getOS() == llvm::Triple::Win32) {
7080 TheTargetCodeGenInfo =
7081 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7082 return *TheTargetCodeGenInfo;
7083 }
7084
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007085 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007086 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007087 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007088 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007089 (CodeGenOpts.FloatABI != "soft" &&
7090 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007091 Kind = ARMABIInfo::AAPCS_VFP;
7092
Derek Schuff71658bd2015-01-29 00:47:04 +00007093 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007094 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007095
John McCallea8d8bb2010-03-11 00:10:12 +00007096 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007097 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007098 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007099 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007100 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007101 if (getTarget().getABI() == "elfv2")
7102 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007103 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007104
Ulrich Weigandb7122372014-07-21 00:48:09 +00007105 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007106 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007107 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007108 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007109 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007110 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007111 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007112 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007113 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007114 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007115
Ulrich Weigandb7122372014-07-21 00:48:09 +00007116 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007117 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007118 }
John McCallea8d8bb2010-03-11 00:10:12 +00007119
Peter Collingbournec947aae2012-05-20 23:28:41 +00007120 case llvm::Triple::nvptx:
7121 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007122 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007123
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007124 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007125 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007126
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007127 case llvm::Triple::systemz: {
7128 bool HasVector = getTarget().getABI() == "vector";
7129 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7130 HasVector));
7131 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007132
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007133 case llvm::Triple::tce:
7134 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7135
Eli Friedman33465822011-07-08 23:31:17 +00007136 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007137 bool IsDarwinVectorABI = Triple.isOSDarwin();
7138 bool IsSmallStructInRegABI =
7139 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007140 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007141
John McCall1fe2a8c2013-06-18 02:46:29 +00007142 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007143 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007144 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007145 IsDarwinVectorABI, IsSmallStructInRegABI,
7146 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007147 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007148 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007149 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007150 new X86_32TargetCodeGenInfo(Types,
7151 IsDarwinVectorABI, IsSmallStructInRegABI,
7152 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007153 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007154 }
Eli Friedman33465822011-07-08 23:31:17 +00007155 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007156
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007157 case llvm::Triple::x86_64: {
Chris Lattner04dc9572010-08-31 16:44:54 +00007158 switch (Triple.getOS()) {
7159 case llvm::Triple::Win32:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00007160 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007161 case llvm::Triple::PS4:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00007162 return *(TheTargetCodeGenInfo = new PS4TargetCodeGenInfo(Types));
Chris Lattner04dc9572010-08-31 16:44:54 +00007163 default:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00007164 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types));
Chris Lattner04dc9572010-08-31 16:44:54 +00007165 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007166 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007167 case llvm::Triple::hexagon:
7168 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007169 case llvm::Triple::r600:
7170 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007171 case llvm::Triple::amdgcn:
7172 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007173 case llvm::Triple::sparcv9:
7174 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007175 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007176 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007177 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007178}