blob: 9d2871649c832771605e9461075d53aa48f0b261 [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 Kleckner40ca9132014-05-13 22:05:45 +0000409 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000410 return ABIArgInfo::getIndirect(0);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000411
Chris Lattner9723d6c2010-03-11 18:19:55 +0000412 // Treat an enum type as its underlying type.
413 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
414 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000415
Chris Lattner9723d6c2010-03-11 18:19:55 +0000416 return (Ty->isPromotableIntegerType() ?
417 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000418}
419
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000420ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
421 if (RetTy->isVoidType())
422 return ABIArgInfo::getIgnore();
423
424 if (isAggregateTypeForABI(RetTy))
425 return ABIArgInfo::getIndirect(0);
426
427 // Treat an enum type as its underlying type.
428 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
429 RetTy = EnumTy->getDecl()->getIntegerType();
430
431 return (RetTy->isPromotableIntegerType() ?
432 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
433}
434
Derek Schuff09338a22012-09-06 17:37:28 +0000435//===----------------------------------------------------------------------===//
436// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000437//
438// This is a simplified version of the x86_32 ABI. Arguments and return values
439// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000440//===----------------------------------------------------------------------===//
441
442class PNaClABIInfo : public ABIInfo {
443 public:
444 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
445
446 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000447 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000448
Craig Topper4f12f102014-03-12 06:41:41 +0000449 void computeInfo(CGFunctionInfo &FI) const override;
450 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
451 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000452};
453
454class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
455 public:
456 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
457 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
458};
459
460void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000461 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000462 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
463
Reid Kleckner40ca9132014-05-13 22:05:45 +0000464 for (auto &I : FI.arguments())
465 I.info = classifyArgumentType(I.type);
466}
Derek Schuff09338a22012-09-06 17:37:28 +0000467
468llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
469 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000470 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000471}
472
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000473/// \brief Classify argument of given type \p Ty.
474ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000475 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000476 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000477 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000478 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000479 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
480 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000481 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000482 } else if (Ty->isFloatingType()) {
483 // Floating-point types don't go inreg.
484 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000485 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000486
487 return (Ty->isPromotableIntegerType() ?
488 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000489}
490
491ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
492 if (RetTy->isVoidType())
493 return ABIArgInfo::getIgnore();
494
Eli Benderskye20dad62013-04-04 22:49:35 +0000495 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000496 if (isAggregateTypeForABI(RetTy))
497 return ABIArgInfo::getIndirect(0);
498
499 // Treat an enum type as its underlying type.
500 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
501 RetTy = EnumTy->getDecl()->getIntegerType();
502
503 return (RetTy->isPromotableIntegerType() ?
504 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
505}
506
Chad Rosier651c1832013-03-25 21:00:27 +0000507/// IsX86_MMXType - Return true if this is an MMX type.
508bool IsX86_MMXType(llvm::Type *IRType) {
509 // 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 +0000510 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
511 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
512 IRType->getScalarSizeInBits() != 64;
513}
514
Jay Foad7c57be32011-07-11 09:56:20 +0000515static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000516 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000517 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000518 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
519 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
520 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000521 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000522 }
523
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000524 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000525 }
526
527 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000528 return Ty;
529}
530
Reid Kleckner80944df2014-10-31 22:00:51 +0000531/// Returns true if this type can be passed in SSE registers with the
532/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
533static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
534 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
535 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
536 return true;
537 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
538 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
539 // registers specially.
540 unsigned VecSize = Context.getTypeSize(VT);
541 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
542 return true;
543 }
544 return false;
545}
546
547/// Returns true if this aggregate is small enough to be passed in SSE registers
548/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
549static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
550 return NumMembers <= 4;
551}
552
Chris Lattner0cf24192010-06-28 20:05:43 +0000553//===----------------------------------------------------------------------===//
554// X86-32 ABI Implementation
555//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000556
Reid Kleckner661f35b2014-01-18 01:12:41 +0000557/// \brief Similar to llvm::CCState, but for Clang.
558struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000559 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000560
561 unsigned CC;
562 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000563 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000564};
565
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000566/// X86_32ABIInfo - The X86-32 ABI information.
567class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000568 enum Class {
569 Integer,
570 Float
571 };
572
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000573 static const unsigned MinABIStackAlignInBytes = 4;
574
David Chisnallde3a0692009-08-17 23:08:21 +0000575 bool IsDarwinVectorABI;
576 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000577 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000578 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000579
580 static bool isRegisterSize(unsigned Size) {
581 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
582 }
583
Reid Kleckner80944df2014-10-31 22:00:51 +0000584 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
585 // FIXME: Assumes vectorcall is in use.
586 return isX86VectorTypeForVectorCall(getContext(), Ty);
587 }
588
589 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
590 uint64_t NumMembers) const override {
591 // FIXME: Assumes vectorcall is in use.
592 return isX86VectorCallAggregateSmallEnough(NumMembers);
593 }
594
Reid Kleckner40ca9132014-05-13 22:05:45 +0000595 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000596
Daniel Dunbar557893d2010-04-21 19:10:51 +0000597 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
598 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000599 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
600
601 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000602
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000603 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000604 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000605
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000606 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000607 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000608 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
609 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000610
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000611 /// \brief Rewrite the function info so that all memory arguments use
612 /// inalloca.
613 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
614
615 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
616 unsigned &StackOffset, ABIArgInfo &Info,
617 QualType Type) const;
618
Rafael Espindola75419dc2012-07-23 23:30:29 +0000619public:
620
Craig Topper4f12f102014-03-12 06:41:41 +0000621 void computeInfo(CGFunctionInfo &FI) const override;
622 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
623 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000624
Chad Rosier651c1832013-03-25 21:00:27 +0000625 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000626 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000627 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000628 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000629};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000630
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000631class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
632public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000633 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000634 bool d, bool p, bool w, unsigned r)
635 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000636
John McCall1fe2a8c2013-06-18 02:46:29 +0000637 static bool isStructReturnInRegABI(
638 const llvm::Triple &Triple, const CodeGenOptions &Opts);
639
Charles Davis4ea31ab2010-02-13 15:54:06 +0000640 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000641 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000642
Craig Topper4f12f102014-03-12 06:41:41 +0000643 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000644 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000645 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000646 return 4;
647 }
648
649 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000650 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000651
Jay Foad7c57be32011-07-11 09:56:20 +0000652 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000653 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000654 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000655 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
656 }
657
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000658 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
659 std::string &Constraints,
660 std::vector<llvm::Type *> &ResultRegTypes,
661 std::vector<llvm::Type *> &ResultTruncRegTypes,
662 std::vector<LValue> &ResultRegDests,
663 std::string &AsmString,
664 unsigned NumOutputs) const override;
665
Craig Topper4f12f102014-03-12 06:41:41 +0000666 llvm::Constant *
667 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000668 unsigned Sig = (0xeb << 0) | // jmp rel8
669 (0x06 << 8) | // .+0x08
670 ('F' << 16) |
671 ('T' << 24);
672 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
673 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000674};
675
676}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000677
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000678/// Rewrite input constraint references after adding some output constraints.
679/// In the case where there is one output and one input and we add one output,
680/// we need to replace all operand references greater than or equal to 1:
681/// mov $0, $1
682/// mov eax, $1
683/// The result will be:
684/// mov $0, $2
685/// mov eax, $2
686static void rewriteInputConstraintReferences(unsigned FirstIn,
687 unsigned NumNewOuts,
688 std::string &AsmString) {
689 std::string Buf;
690 llvm::raw_string_ostream OS(Buf);
691 size_t Pos = 0;
692 while (Pos < AsmString.size()) {
693 size_t DollarStart = AsmString.find('$', Pos);
694 if (DollarStart == std::string::npos)
695 DollarStart = AsmString.size();
696 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
697 if (DollarEnd == std::string::npos)
698 DollarEnd = AsmString.size();
699 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
700 Pos = DollarEnd;
701 size_t NumDollars = DollarEnd - DollarStart;
702 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
703 // We have an operand reference.
704 size_t DigitStart = Pos;
705 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
706 if (DigitEnd == std::string::npos)
707 DigitEnd = AsmString.size();
708 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
709 unsigned OperandIndex;
710 if (!OperandStr.getAsInteger(10, OperandIndex)) {
711 if (OperandIndex >= FirstIn)
712 OperandIndex += NumNewOuts;
713 OS << OperandIndex;
714 } else {
715 OS << OperandStr;
716 }
717 Pos = DigitEnd;
718 }
719 }
720 AsmString = std::move(OS.str());
721}
722
723/// Add output constraints for EAX:EDX because they are return registers.
724void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
725 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
726 std::vector<llvm::Type *> &ResultRegTypes,
727 std::vector<llvm::Type *> &ResultTruncRegTypes,
728 std::vector<LValue> &ResultRegDests, std::string &AsmString,
729 unsigned NumOutputs) const {
730 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
731
732 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
733 // larger.
734 if (!Constraints.empty())
735 Constraints += ',';
736 if (RetWidth <= 32) {
737 Constraints += "={eax}";
738 ResultRegTypes.push_back(CGF.Int32Ty);
739 } else {
740 // Use the 'A' constraint for EAX:EDX.
741 Constraints += "=A";
742 ResultRegTypes.push_back(CGF.Int64Ty);
743 }
744
745 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
746 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
747 ResultTruncRegTypes.push_back(CoerceTy);
748
749 // Coerce the integer by bitcasting the return slot pointer.
750 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
751 CoerceTy->getPointerTo()));
752 ResultRegDests.push_back(ReturnSlot);
753
754 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
755}
756
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000757/// shouldReturnTypeInRegister - Determine if the given type should be
758/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000759bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
760 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000761 uint64_t Size = Context.getTypeSize(Ty);
762
763 // Type must be register sized.
764 if (!isRegisterSize(Size))
765 return false;
766
767 if (Ty->isVectorType()) {
768 // 64- and 128- bit vectors inside structures are not returned in
769 // registers.
770 if (Size == 64 || Size == 128)
771 return false;
772
773 return true;
774 }
775
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000776 // If this is a builtin, pointer, enum, complex type, member pointer, or
777 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000778 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000779 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000780 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000781 return true;
782
783 // Arrays are treated like records.
784 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000785 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000786
787 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000788 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000789 if (!RT) return false;
790
Anders Carlsson40446e82010-01-27 03:25:19 +0000791 // FIXME: Traverse bases here too.
792
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000793 // Structure types are passed in register if all fields would be
794 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000795 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000796 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000797 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000798 continue;
799
800 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000801 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000802 return false;
803 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000804 return true;
805}
806
Reid Kleckner661f35b2014-01-18 01:12:41 +0000807ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
808 // If the return value is indirect, then the hidden argument is consuming one
809 // integer register.
810 if (State.FreeRegs) {
811 --State.FreeRegs;
812 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
813 }
814 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
815}
816
Reid Kleckner40ca9132014-05-13 22:05:45 +0000817ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000818 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000819 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000820
Reid Kleckner80944df2014-10-31 22:00:51 +0000821 const Type *Base = nullptr;
822 uint64_t NumElts = 0;
823 if (State.CC == llvm::CallingConv::X86_VectorCall &&
824 isHomogeneousAggregate(RetTy, Base, NumElts)) {
825 // The LLVM struct type for such an aggregate should lower properly.
826 return ABIArgInfo::getDirect();
827 }
828
Chris Lattner458b2aa2010-07-29 02:16:43 +0000829 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000830 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000831 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000832 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000833
834 // 128-bit vectors are a special case; they are returned in
835 // registers and we need to make sure to pick a type the LLVM
836 // backend will like.
837 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000838 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000839 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000840
841 // Always return in register if it fits in a general purpose
842 // register, or if it is 64 bits and has a single element.
843 if ((Size == 8 || Size == 16 || Size == 32) ||
844 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000845 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000846 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000847
Reid Kleckner661f35b2014-01-18 01:12:41 +0000848 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000849 }
850
851 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000852 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000853
John McCalla1dee5302010-08-22 10:59:02 +0000854 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000855 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000856 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000857 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000858 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000859 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000860
David Chisnallde3a0692009-08-17 23:08:21 +0000861 // If specified, structs and unions are always indirect.
862 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000863 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000864
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000865 // Small structures which are register sized are generally returned
866 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000867 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000868 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000869
870 // As a special-case, if the struct is a "single-element" struct, and
871 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000872 // floating-point register. (MSVC does not apply this special case.)
873 // We apply a similar transformation for pointer types to improve the
874 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000875 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000876 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000877 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000878 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
879
880 // FIXME: We should be able to narrow this integer in cases with dead
881 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000882 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000883 }
884
Reid Kleckner661f35b2014-01-18 01:12:41 +0000885 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000886 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000887
Chris Lattner458b2aa2010-07-29 02:16:43 +0000888 // Treat an enum type as its underlying type.
889 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
890 RetTy = EnumTy->getDecl()->getIntegerType();
891
892 return (RetTy->isPromotableIntegerType() ?
893 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000894}
895
Eli Friedman7919bea2012-06-05 19:40:46 +0000896static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
897 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
898}
899
Daniel Dunbared23de32010-09-16 20:42:00 +0000900static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
901 const RecordType *RT = Ty->getAs<RecordType>();
902 if (!RT)
903 return 0;
904 const RecordDecl *RD = RT->getDecl();
905
906 // If this is a C++ record, check the bases first.
907 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000908 for (const auto &I : CXXRD->bases())
909 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000910 return false;
911
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000912 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000913 QualType FT = i->getType();
914
Eli Friedman7919bea2012-06-05 19:40:46 +0000915 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000916 return true;
917
918 if (isRecordWithSSEVectorType(Context, FT))
919 return true;
920 }
921
922 return false;
923}
924
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000925unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
926 unsigned Align) const {
927 // Otherwise, if the alignment is less than or equal to the minimum ABI
928 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000929 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000930 return 0; // Use default alignment.
931
932 // On non-Darwin, the stack type alignment is always 4.
933 if (!IsDarwinVectorABI) {
934 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000935 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000936 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000937
Daniel Dunbared23de32010-09-16 20:42:00 +0000938 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000939 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
940 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000941 return 16;
942
943 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000944}
945
Rafael Espindola703c47f2012-10-19 05:04:37 +0000946ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000947 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000948 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000949 if (State.FreeRegs) {
950 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000951 return ABIArgInfo::getIndirectInReg(0, false);
952 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000953 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000954 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000955
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000956 // Compute the byval alignment.
957 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
958 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
959 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000960 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000961
962 // If the stack alignment is less than the type alignment, realign the
963 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000964 bool Realign = TypeAlign > StackAlign;
965 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000966}
967
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000968X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
969 const Type *T = isSingleElementStruct(Ty, getContext());
970 if (!T)
971 T = Ty.getTypePtr();
972
973 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
974 BuiltinType::Kind K = BT->getKind();
975 if (K == BuiltinType::Float || K == BuiltinType::Double)
976 return Float;
977 }
978 return Integer;
979}
980
Reid Kleckner661f35b2014-01-18 01:12:41 +0000981bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
982 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000983 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000984 Class C = classify(Ty);
985 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000986 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000987
Rafael Espindola077dd592012-10-24 01:58:58 +0000988 unsigned Size = getContext().getTypeSize(Ty);
989 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000990
991 if (SizeInRegs == 0)
992 return false;
993
Reid Kleckner661f35b2014-01-18 01:12:41 +0000994 if (SizeInRegs > State.FreeRegs) {
995 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000996 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000997 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000998
Reid Kleckner661f35b2014-01-18 01:12:41 +0000999 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001000
Reid Kleckner80944df2014-10-31 22:00:51 +00001001 if (State.CC == llvm::CallingConv::X86_FastCall ||
1002 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001003 if (Size > 32)
1004 return false;
1005
1006 if (Ty->isIntegralOrEnumerationType())
1007 return true;
1008
1009 if (Ty->isPointerType())
1010 return true;
1011
1012 if (Ty->isReferenceType())
1013 return true;
1014
Reid Kleckner661f35b2014-01-18 01:12:41 +00001015 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001016 NeedsPadding = true;
1017
Rafael Espindola077dd592012-10-24 01:58:58 +00001018 return false;
1019 }
1020
Rafael Espindola703c47f2012-10-19 05:04:37 +00001021 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001022}
1023
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001024ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1025 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001026 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001027
Reid Klecknerb1be6832014-11-15 01:41:41 +00001028 Ty = useFirstFieldIfTransparentUnion(Ty);
1029
Reid Kleckner80944df2014-10-31 22:00:51 +00001030 // Check with the C++ ABI first.
1031 const RecordType *RT = Ty->getAs<RecordType>();
1032 if (RT) {
1033 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1034 if (RAA == CGCXXABI::RAA_Indirect) {
1035 return getIndirectResult(Ty, false, State);
1036 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1037 // The field index doesn't matter, we'll fix it up later.
1038 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1039 }
1040 }
1041
1042 // vectorcall adds the concept of a homogenous vector aggregate, similar
1043 // to other targets.
1044 const Type *Base = nullptr;
1045 uint64_t NumElts = 0;
1046 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1047 isHomogeneousAggregate(Ty, Base, NumElts)) {
1048 if (State.FreeSSERegs >= NumElts) {
1049 State.FreeSSERegs -= NumElts;
1050 if (Ty->isBuiltinType() || Ty->isVectorType())
1051 return ABIArgInfo::getDirect();
1052 return ABIArgInfo::getExpand();
1053 }
1054 return getIndirectResult(Ty, /*ByVal=*/false, State);
1055 }
1056
1057 if (isAggregateTypeForABI(Ty)) {
1058 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001059 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001060 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001061 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001062
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001063 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001064 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001065 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001066 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001067
Eli Friedman9f061a32011-11-18 00:28:11 +00001068 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001069 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001070 return ABIArgInfo::getIgnore();
1071
Rafael Espindolafad28de2012-10-24 01:59:00 +00001072 llvm::LLVMContext &LLVMContext = getVMContext();
1073 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1074 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001075 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001076 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001077 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001078 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1079 return ABIArgInfo::getDirectInReg(Result);
1080 }
Craig Topper8a13c412014-05-21 05:09:00 +00001081 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001082
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001083 // Expand small (<= 128-bit) record types when we know that the stack layout
1084 // of those arguments will match the struct. This is important because the
1085 // LLVM backend isn't smart enough to remove byval, which inhibits many
1086 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001087 if (getContext().getTypeSize(Ty) <= 4*32 &&
1088 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001089 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001090 State.CC == llvm::CallingConv::X86_FastCall ||
1091 State.CC == llvm::CallingConv::X86_VectorCall,
1092 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001093
Reid Kleckner661f35b2014-01-18 01:12:41 +00001094 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001095 }
1096
Chris Lattnerd774ae92010-08-26 20:05:13 +00001097 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001098 // On Darwin, some vectors are passed in memory, we handle this by passing
1099 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001100 if (IsDarwinVectorABI) {
1101 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001102 if ((Size == 8 || Size == 16 || Size == 32) ||
1103 (Size == 64 && VT->getNumElements() == 1))
1104 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1105 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001106 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001107
Chad Rosier651c1832013-03-25 21:00:27 +00001108 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1109 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001110
Chris Lattnerd774ae92010-08-26 20:05:13 +00001111 return ABIArgInfo::getDirect();
1112 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001113
1114
Chris Lattner458b2aa2010-07-29 02:16:43 +00001115 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1116 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001117
Rafael Espindolafad28de2012-10-24 01:59:00 +00001118 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001119 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001120
1121 if (Ty->isPromotableIntegerType()) {
1122 if (InReg)
1123 return ABIArgInfo::getExtendInReg();
1124 return ABIArgInfo::getExtend();
1125 }
1126 if (InReg)
1127 return ABIArgInfo::getDirectInReg();
1128 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001129}
1130
Rafael Espindolaa6472962012-07-24 00:01:07 +00001131void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001132 CCState State(FI.getCallingConvention());
1133 if (State.CC == llvm::CallingConv::X86_FastCall)
1134 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001135 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1136 State.FreeRegs = 2;
1137 State.FreeSSERegs = 6;
1138 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001139 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001140 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001141 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001142
Reid Kleckner677539d2014-07-10 01:58:55 +00001143 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001144 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001145 } else if (FI.getReturnInfo().isIndirect()) {
1146 // The C++ ABI is not aware of register usage, so we have to check if the
1147 // return value was sret and put it in a register ourselves if appropriate.
1148 if (State.FreeRegs) {
1149 --State.FreeRegs; // The sret parameter consumes a register.
1150 FI.getReturnInfo().setInReg(true);
1151 }
1152 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001153
Peter Collingbournef7706832014-12-12 23:41:25 +00001154 // The chain argument effectively gives us another free register.
1155 if (FI.isChainCall())
1156 ++State.FreeRegs;
1157
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001158 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001159 for (auto &I : FI.arguments()) {
1160 I.info = classifyArgumentType(I.type, State);
1161 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001162 }
1163
1164 // If we needed to use inalloca for any argument, do a second pass and rewrite
1165 // all the memory arguments to use inalloca.
1166 if (UsedInAlloca)
1167 rewriteWithInAlloca(FI);
1168}
1169
1170void
1171X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1172 unsigned &StackOffset,
1173 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001174 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1175 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1176 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1177 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1178
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001179 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1180 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001181 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001182 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001183 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001184 unsigned NumBytes = StackOffset - OldOffset;
1185 assert(NumBytes);
1186 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1187 Ty = llvm::ArrayType::get(Ty, NumBytes);
1188 FrameFields.push_back(Ty);
1189 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001190}
1191
Reid Kleckner852361d2014-07-26 00:12:26 +00001192static bool isArgInAlloca(const ABIArgInfo &Info) {
1193 // Leave ignored and inreg arguments alone.
1194 switch (Info.getKind()) {
1195 case ABIArgInfo::InAlloca:
1196 return true;
1197 case ABIArgInfo::Indirect:
1198 assert(Info.getIndirectByVal());
1199 return true;
1200 case ABIArgInfo::Ignore:
1201 return false;
1202 case ABIArgInfo::Direct:
1203 case ABIArgInfo::Extend:
1204 case ABIArgInfo::Expand:
1205 if (Info.getInReg())
1206 return false;
1207 return true;
1208 }
1209 llvm_unreachable("invalid enum");
1210}
1211
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001212void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1213 assert(IsWin32StructABI && "inalloca only supported on win32");
1214
1215 // Build a packed struct type for all of the arguments in memory.
1216 SmallVector<llvm::Type *, 6> FrameFields;
1217
1218 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001219 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1220
1221 // Put 'this' into the struct before 'sret', if necessary.
1222 bool IsThisCall =
1223 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1224 ABIArgInfo &Ret = FI.getReturnInfo();
1225 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1226 isArgInAlloca(I->info)) {
1227 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1228 ++I;
1229 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001230
1231 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001232 if (Ret.isIndirect() && !Ret.getInReg()) {
1233 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1234 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001235 // On Windows, the hidden sret parameter is always returned in eax.
1236 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001237 }
1238
1239 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001240 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001241 ++I;
1242
1243 // Put arguments passed in memory into the struct.
1244 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001245 if (isArgInAlloca(I->info))
1246 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001247 }
1248
1249 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1250 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001251}
1252
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001253llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1254 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001255 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001256
1257 CGBuilderTy &Builder = CGF.Builder;
1258 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1259 "ap");
1260 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001261
1262 // Compute if the address needs to be aligned
1263 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1264 Align = getTypeStackAlignInBytes(Ty, Align);
1265 Align = std::max(Align, 4U);
1266 if (Align > 4) {
1267 // addr = (addr + align - 1) & -align;
1268 llvm::Value *Offset =
1269 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1270 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1271 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1272 CGF.Int32Ty);
1273 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1274 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1275 Addr->getType(),
1276 "ap.cur.aligned");
1277 }
1278
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001279 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001280 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001281 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1282
1283 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001284 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001285 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001286 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001287 "ap.next");
1288 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1289
1290 return AddrTyped;
1291}
1292
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001293bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1294 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1295 assert(Triple.getArch() == llvm::Triple::x86);
1296
1297 switch (Opts.getStructReturnConvention()) {
1298 case CodeGenOptions::SRCK_Default:
1299 break;
1300 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1301 return false;
1302 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1303 return true;
1304 }
1305
1306 if (Triple.isOSDarwin())
1307 return true;
1308
1309 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001310 case llvm::Triple::DragonFly:
1311 case llvm::Triple::FreeBSD:
1312 case llvm::Triple::OpenBSD:
1313 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001314 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001315 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001316 default:
1317 return false;
1318 }
1319}
1320
Charles Davis4ea31ab2010-02-13 15:54:06 +00001321void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1322 llvm::GlobalValue *GV,
1323 CodeGen::CodeGenModule &CGM) const {
1324 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1325 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1326 // Get the LLVM function.
1327 llvm::Function *Fn = cast<llvm::Function>(GV);
1328
1329 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001330 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001331 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001332 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1333 llvm::AttributeSet::get(CGM.getLLVMContext(),
1334 llvm::AttributeSet::FunctionIndex,
1335 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001336 }
1337 }
1338}
1339
John McCallbeec5a02010-03-06 00:35:14 +00001340bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1341 CodeGen::CodeGenFunction &CGF,
1342 llvm::Value *Address) const {
1343 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001344
Chris Lattnerece04092012-02-07 00:39:47 +00001345 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001346
John McCallbeec5a02010-03-06 00:35:14 +00001347 // 0-7 are the eight integer registers; the order is different
1348 // on Darwin (for EH), but the range is the same.
1349 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001350 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001351
John McCallc8e01702013-04-16 22:48:15 +00001352 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001353 // 12-16 are st(0..4). Not sure why we stop at 4.
1354 // These have size 16, which is sizeof(long double) on
1355 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001356 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001357 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001358
John McCallbeec5a02010-03-06 00:35:14 +00001359 } else {
1360 // 9 is %eflags, which doesn't get a size on Darwin for some
1361 // reason.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001362 Builder.CreateStore(
1363 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9));
John McCallbeec5a02010-03-06 00:35:14 +00001364
1365 // 11-16 are st(0..5). Not sure why we stop at 5.
1366 // These have size 12, which is sizeof(long double) on
1367 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001368 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001369 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1370 }
John McCallbeec5a02010-03-06 00:35:14 +00001371
1372 return false;
1373}
1374
Chris Lattner0cf24192010-06-28 20:05:43 +00001375//===----------------------------------------------------------------------===//
1376// X86-64 ABI Implementation
1377//===----------------------------------------------------------------------===//
1378
1379
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001380namespace {
1381/// X86_64ABIInfo - The X86_64 ABI information.
1382class X86_64ABIInfo : public ABIInfo {
1383 enum Class {
1384 Integer = 0,
1385 SSE,
1386 SSEUp,
1387 X87,
1388 X87Up,
1389 ComplexX87,
1390 NoClass,
1391 Memory
1392 };
1393
1394 /// merge - Implement the X86_64 ABI merging algorithm.
1395 ///
1396 /// Merge an accumulating classification \arg Accum with a field
1397 /// classification \arg Field.
1398 ///
1399 /// \param Accum - The accumulating classification. This should
1400 /// always be either NoClass or the result of a previous merge
1401 /// call. In addition, this should never be Memory (the caller
1402 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001403 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001404
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001405 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1406 ///
1407 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1408 /// final MEMORY or SSE classes when necessary.
1409 ///
1410 /// \param AggregateSize - The size of the current aggregate in
1411 /// the classification process.
1412 ///
1413 /// \param Lo - The classification for the parts of the type
1414 /// residing in the low word of the containing object.
1415 ///
1416 /// \param Hi - The classification for the parts of the type
1417 /// residing in the higher words of the containing object.
1418 ///
1419 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1420
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001421 /// classify - Determine the x86_64 register classes in which the
1422 /// given type T should be passed.
1423 ///
1424 /// \param Lo - The classification for the parts of the type
1425 /// residing in the low word of the containing object.
1426 ///
1427 /// \param Hi - The classification for the parts of the type
1428 /// residing in the high word of the containing object.
1429 ///
1430 /// \param OffsetBase - The bit offset of this type in the
1431 /// containing object. Some parameters are classified different
1432 /// depending on whether they straddle an eightbyte boundary.
1433 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001434 /// \param isNamedArg - Whether the argument in question is a "named"
1435 /// argument, as used in AMD64-ABI 3.5.7.
1436 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001437 /// If a word is unused its result will be NoClass; if a type should
1438 /// be passed in Memory then at least the classification of \arg Lo
1439 /// will be Memory.
1440 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001441 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001442 ///
1443 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1444 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001445 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1446 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001447
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001448 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001449 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1450 unsigned IROffset, QualType SourceTy,
1451 unsigned SourceOffset) const;
1452 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1453 unsigned IROffset, QualType SourceTy,
1454 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001455
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001456 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001457 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001458 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001459
1460 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001461 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001462 ///
1463 /// \param freeIntRegs - The number of free integer registers remaining
1464 /// available.
1465 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001466
Chris Lattner458b2aa2010-07-29 02:16:43 +00001467 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001468
Bill Wendling5cd41c42010-10-18 03:41:31 +00001469 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001470 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001471 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001472 unsigned &neededSSE,
1473 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001474
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001475 bool IsIllegalVectorType(QualType Ty) const;
1476
John McCalle0fda732011-04-21 01:20:55 +00001477 /// The 0.98 ABI revision clarified a lot of ambiguities,
1478 /// unfortunately in ways that were not always consistent with
1479 /// certain previous compilers. In particular, platforms which
1480 /// required strict binary compatibility with older versions of GCC
1481 /// may need to exempt themselves.
1482 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001483 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001484 }
1485
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001486 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001487 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1488 // 64-bit hardware.
1489 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001490
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001491public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001492 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001493 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001494 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001495 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001496
John McCalla729c622012-02-17 03:33:10 +00001497 bool isPassedUsingAVXType(QualType type) const {
1498 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001499 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001500 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1501 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001502 if (info.isDirect()) {
1503 llvm::Type *ty = info.getCoerceToType();
1504 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1505 return (vectorTy->getBitWidth() > 128);
1506 }
1507 return false;
1508 }
1509
Craig Topper4f12f102014-03-12 06:41:41 +00001510 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001511
Craig Topper4f12f102014-03-12 06:41:41 +00001512 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1513 CodeGenFunction &CGF) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001514
1515 bool has64BitPointers() const {
1516 return Has64BitPointers;
1517 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001518};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001519
Chris Lattner04dc9572010-08-31 16:44:54 +00001520/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001521class WinX86_64ABIInfo : public ABIInfo {
1522
Reid Kleckner80944df2014-10-31 22:00:51 +00001523 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1524 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001525
Chris Lattner04dc9572010-08-31 16:44:54 +00001526public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001527 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1528
Craig Topper4f12f102014-03-12 06:41:41 +00001529 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001530
Craig Topper4f12f102014-03-12 06:41:41 +00001531 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1532 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001533
1534 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1535 // FIXME: Assumes vectorcall is in use.
1536 return isX86VectorTypeForVectorCall(getContext(), Ty);
1537 }
1538
1539 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1540 uint64_t NumMembers) const override {
1541 // FIXME: Assumes vectorcall is in use.
1542 return isX86VectorCallAggregateSmallEnough(NumMembers);
1543 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001544};
1545
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001546class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001547 bool HasAVX;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001548public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001549 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Alexander Musman09184fe2014-09-30 05:29:28 +00001550 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCallbeec5a02010-03-06 00:35:14 +00001551
John McCalla729c622012-02-17 03:33:10 +00001552 const X86_64ABIInfo &getABIInfo() const {
1553 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1554 }
1555
Craig Topper4f12f102014-03-12 06:41:41 +00001556 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001557 return 7;
1558 }
1559
1560 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001561 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001562 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001563
John McCall943fae92010-05-27 06:19:26 +00001564 // 0-15 are the 16 integer registers.
1565 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001566 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001567 return false;
1568 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001569
Jay Foad7c57be32011-07-11 09:56:20 +00001570 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001571 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001572 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001573 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1574 }
1575
John McCalla729c622012-02-17 03:33:10 +00001576 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001577 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001578 // The default CC on x86-64 sets %al to the number of SSA
1579 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001580 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001581 // that when AVX types are involved: the ABI explicitly states it is
1582 // undefined, and it doesn't work in practice because of how the ABI
1583 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001584 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001585 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001586 for (CallArgList::const_iterator
1587 it = args.begin(), ie = args.end(); it != ie; ++it) {
1588 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1589 HasAVXType = true;
1590 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001591 }
1592 }
John McCalla729c622012-02-17 03:33:10 +00001593
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001594 if (!HasAVXType)
1595 return true;
1596 }
John McCallcbc038a2011-09-21 08:08:30 +00001597
John McCalla729c622012-02-17 03:33:10 +00001598 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001599 }
1600
Craig Topper4f12f102014-03-12 06:41:41 +00001601 llvm::Constant *
1602 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001603 unsigned Sig;
1604 if (getABIInfo().has64BitPointers())
1605 Sig = (0xeb << 0) | // jmp rel8
1606 (0x0a << 8) | // .+0x0c
1607 ('F' << 16) |
1608 ('T' << 24);
1609 else
1610 Sig = (0xeb << 0) | // jmp rel8
1611 (0x06 << 8) | // .+0x08
1612 ('F' << 16) |
1613 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001614 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1615 }
1616
Alexander Musman09184fe2014-09-30 05:29:28 +00001617 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1618 return HasAVX ? 32 : 16;
1619 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001620};
1621
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001622class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1623public:
1624 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1625 : X86_64TargetCodeGenInfo(CGT, HasAVX) {}
1626
1627 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001628 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001629 Opt = "\01";
1630 Opt += Lib;
1631 }
1632};
1633
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001634static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001635 // If the argument does not end in .lib, automatically add the suffix.
1636 // If the argument contains a space, enclose it in quotes.
1637 // This matches the behavior of MSVC.
1638 bool Quote = (Lib.find(" ") != StringRef::npos);
1639 std::string ArgStr = Quote ? "\"" : "";
1640 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001641 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001642 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001643 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001644 return ArgStr;
1645}
1646
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001647class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1648public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001649 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1650 bool d, bool p, bool w, unsigned RegParms)
1651 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001652
Hans Wennborg77dc2362015-01-20 19:45:50 +00001653 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1654 CodeGen::CodeGenModule &CGM) const override;
1655
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001656 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001657 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001658 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001659 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001660 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001661
1662 void getDetectMismatchOption(llvm::StringRef Name,
1663 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001664 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001665 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001666 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001667};
1668
Hans Wennborg77dc2362015-01-20 19:45:50 +00001669static void addStackProbeSizeTargetAttribute(const Decl *D,
1670 llvm::GlobalValue *GV,
1671 CodeGen::CodeGenModule &CGM) {
1672 if (isa<FunctionDecl>(D)) {
1673 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1674 llvm::Function *Fn = cast<llvm::Function>(GV);
1675
1676 Fn->addFnAttr("stack-probe-size", llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
1677 }
1678 }
1679}
1680
1681void WinX86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1682 llvm::GlobalValue *GV,
1683 CodeGen::CodeGenModule &CGM) const {
1684 X86_32TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1685
1686 addStackProbeSizeTargetAttribute(D, GV, CGM);
1687}
1688
Chris Lattner04dc9572010-08-31 16:44:54 +00001689class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001690 bool HasAVX;
Chris Lattner04dc9572010-08-31 16:44:54 +00001691public:
Alexander Musman09184fe2014-09-30 05:29:28 +00001692 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1693 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001694
Hans Wennborg77dc2362015-01-20 19:45:50 +00001695 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1696 CodeGen::CodeGenModule &CGM) const override;
1697
Craig Topper4f12f102014-03-12 06:41:41 +00001698 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001699 return 7;
1700 }
1701
1702 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001703 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001704 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001705
Chris Lattner04dc9572010-08-31 16:44:54 +00001706 // 0-15 are the 16 integer registers.
1707 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001708 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001709 return false;
1710 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001711
1712 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001713 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001714 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001715 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001716 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001717
1718 void getDetectMismatchOption(llvm::StringRef Name,
1719 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001720 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001721 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001722 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001723
1724 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1725 return HasAVX ? 32 : 16;
1726 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001727};
1728
Hans Wennborg77dc2362015-01-20 19:45:50 +00001729void WinX86_64TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1730 llvm::GlobalValue *GV,
1731 CodeGen::CodeGenModule &CGM) const {
1732 TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1733
1734 addStackProbeSizeTargetAttribute(D, GV, CGM);
1735}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001736}
1737
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001738void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1739 Class &Hi) const {
1740 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1741 //
1742 // (a) If one of the classes is Memory, the whole argument is passed in
1743 // memory.
1744 //
1745 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1746 // memory.
1747 //
1748 // (c) If the size of the aggregate exceeds two eightbytes and the first
1749 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1750 // argument is passed in memory. NOTE: This is necessary to keep the
1751 // ABI working for processors that don't support the __m256 type.
1752 //
1753 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1754 //
1755 // Some of these are enforced by the merging logic. Others can arise
1756 // only with unions; for example:
1757 // union { _Complex double; unsigned; }
1758 //
1759 // Note that clauses (b) and (c) were added in 0.98.
1760 //
1761 if (Hi == Memory)
1762 Lo = Memory;
1763 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1764 Lo = Memory;
1765 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1766 Lo = Memory;
1767 if (Hi == SSEUp && Lo != SSE)
1768 Hi = SSE;
1769}
1770
Chris Lattnerd776fb12010-06-28 21:43:59 +00001771X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001772 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1773 // classified recursively so that always two fields are
1774 // considered. The resulting class is calculated according to
1775 // the classes of the fields in the eightbyte:
1776 //
1777 // (a) If both classes are equal, this is the resulting class.
1778 //
1779 // (b) If one of the classes is NO_CLASS, the resulting class is
1780 // the other class.
1781 //
1782 // (c) If one of the classes is MEMORY, the result is the MEMORY
1783 // class.
1784 //
1785 // (d) If one of the classes is INTEGER, the result is the
1786 // INTEGER.
1787 //
1788 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1789 // MEMORY is used as class.
1790 //
1791 // (f) Otherwise class SSE is used.
1792
1793 // Accum should never be memory (we should have returned) or
1794 // ComplexX87 (because this cannot be passed in a structure).
1795 assert((Accum != Memory && Accum != ComplexX87) &&
1796 "Invalid accumulated classification during merge.");
1797 if (Accum == Field || Field == NoClass)
1798 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001799 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001800 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001801 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001802 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001803 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001804 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001805 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1806 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001807 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001808 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001809}
1810
Chris Lattner5c740f12010-06-30 19:14:05 +00001811void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001812 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001813 // FIXME: This code can be simplified by introducing a simple value class for
1814 // Class pairs with appropriate constructor methods for the various
1815 // situations.
1816
1817 // FIXME: Some of the split computations are wrong; unaligned vectors
1818 // shouldn't be passed in registers for example, so there is no chance they
1819 // can straddle an eightbyte. Verify & simplify.
1820
1821 Lo = Hi = NoClass;
1822
1823 Class &Current = OffsetBase < 64 ? Lo : Hi;
1824 Current = Memory;
1825
John McCall9dd450b2009-09-21 23:43:11 +00001826 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001827 BuiltinType::Kind k = BT->getKind();
1828
1829 if (k == BuiltinType::Void) {
1830 Current = NoClass;
1831 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1832 Lo = Integer;
1833 Hi = Integer;
1834 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1835 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001836 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1837 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001838 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001839 Current = SSE;
1840 } else if (k == BuiltinType::LongDouble) {
1841 Lo = X87;
1842 Hi = X87Up;
1843 }
1844 // FIXME: _Decimal32 and _Decimal64 are SSE.
1845 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001846 return;
1847 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001848
Chris Lattnerd776fb12010-06-28 21:43:59 +00001849 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001850 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001851 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001852 return;
1853 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001854
Chris Lattnerd776fb12010-06-28 21:43:59 +00001855 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001856 Current = Integer;
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 (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001861 if (Ty->isMemberFunctionPointerType()) {
1862 if (Has64BitPointers) {
1863 // If Has64BitPointers, this is an {i64, i64}, so classify both
1864 // Lo and Hi now.
1865 Lo = Hi = Integer;
1866 } else {
1867 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1868 // straddles an eightbyte boundary, Hi should be classified as well.
1869 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1870 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1871 if (EB_FuncPtr != EB_ThisAdj) {
1872 Lo = Hi = Integer;
1873 } else {
1874 Current = Integer;
1875 }
1876 }
1877 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001878 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001879 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001880 return;
1881 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001882
Chris Lattnerd776fb12010-06-28 21:43:59 +00001883 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001884 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001885 if (Size == 32) {
1886 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1887 // float> as integer.
1888 Current = Integer;
1889
1890 // If this type crosses an eightbyte boundary, it should be
1891 // split.
1892 uint64_t EB_Real = (OffsetBase) / 64;
1893 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1894 if (EB_Real != EB_Imag)
1895 Hi = Lo;
1896 } else if (Size == 64) {
1897 // gcc passes <1 x double> in memory. :(
1898 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1899 return;
1900
1901 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001902 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001903 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1904 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1905 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001906 Current = Integer;
1907 else
1908 Current = SSE;
1909
1910 // If this type crosses an eightbyte boundary, it should be
1911 // split.
1912 if (OffsetBase && OffsetBase != 64)
1913 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001914 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001915 // Arguments of 256-bits are split into four eightbyte chunks. The
1916 // least significant one belongs to class SSE and all the others to class
1917 // SSEUP. The original Lo and Hi design considers that types can't be
1918 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1919 // This design isn't correct for 256-bits, but since there're no cases
1920 // where the upper parts would need to be inspected, avoid adding
1921 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001922 //
1923 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1924 // registers if they are "named", i.e. not part of the "..." of a
1925 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001926 Lo = SSE;
1927 Hi = SSEUp;
1928 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001929 return;
1930 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001931
Chris Lattnerd776fb12010-06-28 21:43:59 +00001932 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001933 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001934
Chris Lattner2b037972010-07-29 02:01:43 +00001935 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001936 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001937 if (Size <= 64)
1938 Current = Integer;
1939 else if (Size <= 128)
1940 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001941 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001942 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001943 else if (ET == getContext().DoubleTy ||
1944 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001945 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001946 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001947 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001948 Current = ComplexX87;
1949
1950 // If this complex type crosses an eightbyte boundary then it
1951 // should be split.
1952 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001953 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001954 if (Hi == NoClass && EB_Real != EB_Imag)
1955 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001956
Chris Lattnerd776fb12010-06-28 21:43:59 +00001957 return;
1958 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001959
Chris Lattner2b037972010-07-29 02:01:43 +00001960 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001961 // Arrays are treated like structures.
1962
Chris Lattner2b037972010-07-29 02:01:43 +00001963 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001964
1965 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001966 // than four eightbytes, ..., it has class MEMORY.
1967 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001968 return;
1969
1970 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1971 // fields, it has class MEMORY.
1972 //
1973 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001974 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001975 return;
1976
1977 // Otherwise implement simplified merge. We could be smarter about
1978 // this, but it isn't worth it and would be harder to verify.
1979 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001980 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001981 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001982
1983 // The only case a 256-bit wide vector could be used is when the array
1984 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1985 // to work for sizes wider than 128, early check and fallback to memory.
1986 if (Size > 128 && EltSize != 256)
1987 return;
1988
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001989 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1990 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001991 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001992 Lo = merge(Lo, FieldLo);
1993 Hi = merge(Hi, FieldHi);
1994 if (Lo == Memory || Hi == Memory)
1995 break;
1996 }
1997
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001998 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001999 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002000 return;
2001 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002002
Chris Lattnerd776fb12010-06-28 21:43:59 +00002003 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002004 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002005
2006 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002007 // than four eightbytes, ..., it has class MEMORY.
2008 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002009 return;
2010
Anders Carlsson20759ad2009-09-16 15:53:40 +00002011 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2012 // copy constructor or a non-trivial destructor, it is passed by invisible
2013 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002014 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002015 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002016
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002017 const RecordDecl *RD = RT->getDecl();
2018
2019 // Assume variable sized types are passed in memory.
2020 if (RD->hasFlexibleArrayMember())
2021 return;
2022
Chris Lattner2b037972010-07-29 02:01:43 +00002023 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002024
2025 // Reset Lo class, this will be recomputed.
2026 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002027
2028 // If this is a C++ record, classify the bases first.
2029 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002030 for (const auto &I : CXXRD->bases()) {
2031 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002032 "Unexpected base class!");
2033 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002034 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002035
2036 // Classify this field.
2037 //
2038 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2039 // single eightbyte, each is classified separately. Each eightbyte gets
2040 // initialized to class NO_CLASS.
2041 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002042 uint64_t Offset =
2043 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002044 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002045 Lo = merge(Lo, FieldLo);
2046 Hi = merge(Hi, FieldHi);
2047 if (Lo == Memory || Hi == Memory)
2048 break;
2049 }
2050 }
2051
2052 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002053 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002054 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002055 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002056 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2057 bool BitField = i->isBitField();
2058
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002059 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2060 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002061 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002062 // The only case a 256-bit wide vector could be used is when the struct
2063 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2064 // to work for sizes wider than 128, early check and fallback to memory.
2065 //
2066 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2067 Lo = Memory;
2068 return;
2069 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002070 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002071 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002072 Lo = Memory;
2073 return;
2074 }
2075
2076 // Classify this field.
2077 //
2078 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2079 // exceeds a single eightbyte, each is classified
2080 // separately. Each eightbyte gets initialized to class
2081 // NO_CLASS.
2082 Class FieldLo, FieldHi;
2083
2084 // Bit-fields require special handling, they do not force the
2085 // structure to be passed in memory even if unaligned, and
2086 // therefore they can straddle an eightbyte.
2087 if (BitField) {
2088 // Ignore padding bit-fields.
2089 if (i->isUnnamedBitfield())
2090 continue;
2091
2092 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002093 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002094
2095 uint64_t EB_Lo = Offset / 64;
2096 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002097
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002098 if (EB_Lo) {
2099 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2100 FieldLo = NoClass;
2101 FieldHi = Integer;
2102 } else {
2103 FieldLo = Integer;
2104 FieldHi = EB_Hi ? Integer : NoClass;
2105 }
2106 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002107 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002108 Lo = merge(Lo, FieldLo);
2109 Hi = merge(Hi, FieldHi);
2110 if (Lo == Memory || Hi == Memory)
2111 break;
2112 }
2113
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002114 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002115 }
2116}
2117
Chris Lattner22a931e2010-06-29 06:01:59 +00002118ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002119 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2120 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002121 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002122 // Treat an enum type as its underlying type.
2123 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2124 Ty = EnumTy->getDecl()->getIntegerType();
2125
2126 return (Ty->isPromotableIntegerType() ?
2127 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2128 }
2129
2130 return ABIArgInfo::getIndirect(0);
2131}
2132
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002133bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2134 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2135 uint64_t Size = getContext().getTypeSize(VecTy);
2136 unsigned LargestVector = HasAVX ? 256 : 128;
2137 if (Size <= 64 || Size > LargestVector)
2138 return true;
2139 }
2140
2141 return false;
2142}
2143
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002144ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2145 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002146 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2147 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002148 //
2149 // This assumption is optimistic, as there could be free registers available
2150 // when we need to pass this argument in memory, and LLVM could try to pass
2151 // the argument in the free register. This does not seem to happen currently,
2152 // but this code would be much safer if we could mark the argument with
2153 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002154 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002155 // Treat an enum type as its underlying type.
2156 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2157 Ty = EnumTy->getDecl()->getIntegerType();
2158
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002159 return (Ty->isPromotableIntegerType() ?
2160 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002161 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002162
Mark Lacey3825e832013-10-06 01:33:34 +00002163 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002164 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002165
Chris Lattner44c2b902011-05-22 23:21:23 +00002166 // Compute the byval alignment. We specify the alignment of the byval in all
2167 // cases so that the mid-level optimizer knows the alignment of the byval.
2168 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002169
2170 // Attempt to avoid passing indirect results using byval when possible. This
2171 // is important for good codegen.
2172 //
2173 // We do this by coercing the value into a scalar type which the backend can
2174 // handle naturally (i.e., without using byval).
2175 //
2176 // For simplicity, we currently only do this when we have exhausted all of the
2177 // free integer registers. Doing this when there are free integer registers
2178 // would require more care, as we would have to ensure that the coerced value
2179 // did not claim the unused register. That would require either reording the
2180 // arguments to the function (so that any subsequent inreg values came first),
2181 // or only doing this optimization when there were no following arguments that
2182 // might be inreg.
2183 //
2184 // We currently expect it to be rare (particularly in well written code) for
2185 // arguments to be passed on the stack when there are still free integer
2186 // registers available (this would typically imply large structs being passed
2187 // by value), so this seems like a fair tradeoff for now.
2188 //
2189 // We can revisit this if the backend grows support for 'onstack' parameter
2190 // attributes. See PR12193.
2191 if (freeIntRegs == 0) {
2192 uint64_t Size = getContext().getTypeSize(Ty);
2193
2194 // If this type fits in an eightbyte, coerce it into the matching integral
2195 // type, which will end up on the stack (with alignment 8).
2196 if (Align == 8 && Size <= 64)
2197 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2198 Size));
2199 }
2200
Chris Lattner44c2b902011-05-22 23:21:23 +00002201 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002202}
2203
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002204/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2205/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002206llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002207 // Wrapper structs/arrays that only contain vectors are passed just like
2208 // vectors; strip them off if present.
2209 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2210 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002211
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002212 llvm::Type *IRType = CGT.ConvertType(Ty);
Benjamin Kramer83b1bf32015-03-02 16:09:24 +00002213 assert(isa<llvm::VectorType>(IRType) &&
2214 "Trying to return a non-vector type in a vector register!");
2215 return IRType;
Chris Lattner4200fe42010-07-29 04:56:46 +00002216}
2217
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002218/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2219/// is known to either be off the end of the specified type or being in
2220/// alignment padding. The user type specified is known to be at most 128 bits
2221/// in size, and have passed through X86_64ABIInfo::classify with a successful
2222/// classification that put one of the two halves in the INTEGER class.
2223///
2224/// It is conservatively correct to return false.
2225static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2226 unsigned EndBit, ASTContext &Context) {
2227 // If the bytes being queried are off the end of the type, there is no user
2228 // data hiding here. This handles analysis of builtins, vectors and other
2229 // types that don't contain interesting padding.
2230 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2231 if (TySize <= StartBit)
2232 return true;
2233
Chris Lattner98076a22010-07-29 07:43:55 +00002234 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2235 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2236 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2237
2238 // Check each element to see if the element overlaps with the queried range.
2239 for (unsigned i = 0; i != NumElts; ++i) {
2240 // If the element is after the span we care about, then we're done..
2241 unsigned EltOffset = i*EltSize;
2242 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002243
Chris Lattner98076a22010-07-29 07:43:55 +00002244 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2245 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2246 EndBit-EltOffset, Context))
2247 return false;
2248 }
2249 // If it overlaps no elements, then it is safe to process as padding.
2250 return true;
2251 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002252
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002253 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2254 const RecordDecl *RD = RT->getDecl();
2255 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002256
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002257 // If this is a C++ record, check the bases first.
2258 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002259 for (const auto &I : CXXRD->bases()) {
2260 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002261 "Unexpected base class!");
2262 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002263 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002264
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002265 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002266 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002267 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002268
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002269 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002270 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002271 EndBit-BaseOffset, Context))
2272 return false;
2273 }
2274 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002275
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002276 // Verify that no field has data that overlaps the region of interest. Yes
2277 // this could be sped up a lot by being smarter about queried fields,
2278 // however we're only looking at structs up to 16 bytes, so we don't care
2279 // much.
2280 unsigned idx = 0;
2281 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2282 i != e; ++i, ++idx) {
2283 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002284
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002285 // If we found a field after the region we care about, then we're done.
2286 if (FieldOffset >= EndBit) break;
2287
2288 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2289 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2290 Context))
2291 return false;
2292 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002293
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002294 // If nothing in this record overlapped the area of interest, then we're
2295 // clean.
2296 return true;
2297 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002298
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002299 return false;
2300}
2301
Chris Lattnere556a712010-07-29 18:39:32 +00002302/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2303/// float member at the specified offset. For example, {int,{float}} has a
2304/// float at offset 4. It is conservatively correct for this routine to return
2305/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002306static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002307 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002308 // Base case if we find a float.
2309 if (IROffset == 0 && IRType->isFloatTy())
2310 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002311
Chris Lattnere556a712010-07-29 18:39:32 +00002312 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002313 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002314 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2315 unsigned Elt = SL->getElementContainingOffset(IROffset);
2316 IROffset -= SL->getElementOffset(Elt);
2317 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2318 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002319
Chris Lattnere556a712010-07-29 18:39:32 +00002320 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002321 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2322 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002323 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2324 IROffset -= IROffset/EltSize*EltSize;
2325 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2326 }
2327
2328 return false;
2329}
2330
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002331
2332/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2333/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002334llvm::Type *X86_64ABIInfo::
2335GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002336 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002337 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002338 // pass as float if the last 4 bytes is just padding. This happens for
2339 // structs that contain 3 floats.
2340 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2341 SourceOffset*8+64, getContext()))
2342 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002343
Chris Lattnere556a712010-07-29 18:39:32 +00002344 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2345 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2346 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002347 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2348 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002349 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002350
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002351 return llvm::Type::getDoubleTy(getVMContext());
2352}
2353
2354
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002355/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2356/// an 8-byte GPR. This means that we either have a scalar or we are talking
2357/// about the high or low part of an up-to-16-byte struct. This routine picks
2358/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002359/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2360/// etc).
2361///
2362/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2363/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2364/// the 8-byte value references. PrefType may be null.
2365///
Alp Toker9907f082014-07-09 14:06:35 +00002366/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002367/// an offset into this that we're processing (which is always either 0 or 8).
2368///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002369llvm::Type *X86_64ABIInfo::
2370GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002371 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002372 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2373 // returning an 8-byte unit starting with it. See if we can safely use it.
2374 if (IROffset == 0) {
2375 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002376 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2377 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002378 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002379
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002380 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2381 // goodness in the source type is just tail padding. This is allowed to
2382 // kick in for struct {double,int} on the int, but not on
2383 // struct{double,int,int} because we wouldn't return the second int. We
2384 // have to do this analysis on the source type because we can't depend on
2385 // unions being lowered a specific way etc.
2386 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002387 IRType->isIntegerTy(32) ||
2388 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2389 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2390 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002391
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002392 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2393 SourceOffset*8+64, getContext()))
2394 return IRType;
2395 }
2396 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002397
Chris Lattner2192fe52011-07-18 04:24:23 +00002398 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002399 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002400 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002401 if (IROffset < SL->getSizeInBytes()) {
2402 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2403 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002404
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002405 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2406 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002407 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002408 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002409
Chris Lattner2192fe52011-07-18 04:24:23 +00002410 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002411 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002412 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002413 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002414 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2415 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002416 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002417
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002418 // Okay, we don't have any better idea of what to pass, so we pass this in an
2419 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002420 unsigned TySizeInBytes =
2421 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002422
Chris Lattner3f763422010-07-29 17:34:39 +00002423 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002424
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002425 // It is always safe to classify this as an integer type up to i64 that
2426 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002427 return llvm::IntegerType::get(getVMContext(),
2428 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002429}
2430
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002431
2432/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2433/// be used as elements of a two register pair to pass or return, return a
2434/// first class aggregate to represent them. For example, if the low part of
2435/// a by-value argument should be passed as i32* and the high part as float,
2436/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002437static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002438GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002439 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002440 // In order to correctly satisfy the ABI, we need to the high part to start
2441 // at offset 8. If the high and low parts we inferred are both 4-byte types
2442 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2443 // the second element at offset 8. Check for this:
2444 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2445 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002446 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002447 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002448
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002449 // To handle this, we have to increase the size of the low part so that the
2450 // second element will start at an 8 byte offset. We can't increase the size
2451 // of the second element because it might make us access off the end of the
2452 // struct.
2453 if (HiStart != 8) {
2454 // There are only two sorts of types the ABI generation code can produce for
2455 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2456 // Promote these to a larger type.
2457 if (Lo->isFloatTy())
2458 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2459 else {
2460 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2461 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2462 }
2463 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002464
Reid Kleckneree7cf842014-12-01 22:02:27 +00002465 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002466
2467
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002468 // Verify that the second element is at an 8-byte offset.
2469 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2470 "Invalid x86-64 argument pair!");
2471 return Result;
2472}
2473
Chris Lattner31faff52010-07-28 23:06:14 +00002474ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002475classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002476 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2477 // classification algorithm.
2478 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002479 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002480
2481 // Check some invariants.
2482 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002483 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2484
Craig Topper8a13c412014-05-21 05:09:00 +00002485 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002486 switch (Lo) {
2487 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002488 if (Hi == NoClass)
2489 return ABIArgInfo::getIgnore();
2490 // If the low part is just padding, it takes no register, leave ResType
2491 // null.
2492 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2493 "Unknown missing lo part");
2494 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002495
2496 case SSEUp:
2497 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002498 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002499
2500 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2501 // hidden argument.
2502 case Memory:
2503 return getIndirectReturnResult(RetTy);
2504
2505 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2506 // available register of the sequence %rax, %rdx is used.
2507 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002508 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002509
Chris Lattner1f3a0632010-07-29 21:42:50 +00002510 // If we have a sign or zero extended integer, make sure to return Extend
2511 // so that the parameter gets the right LLVM IR attributes.
2512 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2513 // Treat an enum type as its underlying type.
2514 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2515 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002516
Chris Lattner1f3a0632010-07-29 21:42:50 +00002517 if (RetTy->isIntegralOrEnumerationType() &&
2518 RetTy->isPromotableIntegerType())
2519 return ABIArgInfo::getExtend();
2520 }
Chris Lattner31faff52010-07-28 23:06:14 +00002521 break;
2522
2523 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2524 // available SSE register of the sequence %xmm0, %xmm1 is used.
2525 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002526 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002527 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002528
2529 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2530 // returned on the X87 stack in %st0 as 80-bit x87 number.
2531 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002532 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002533 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002534
2535 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2536 // part of the value is returned in %st0 and the imaginary part in
2537 // %st1.
2538 case ComplexX87:
2539 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002540 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002541 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002542 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002543 break;
2544 }
2545
Craig Topper8a13c412014-05-21 05:09:00 +00002546 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002547 switch (Hi) {
2548 // Memory was handled previously and X87 should
2549 // never occur as a hi class.
2550 case Memory:
2551 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002552 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002553
2554 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002555 case NoClass:
2556 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002557
Chris Lattner52b3c132010-09-01 00:20:33 +00002558 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002559 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002560 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2561 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002562 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002563 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002564 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002565 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2566 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002567 break;
2568
2569 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002570 // is passed in the next available eightbyte chunk if the last used
2571 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002572 //
Chris Lattner57540c52011-04-15 05:22:18 +00002573 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002574 case SSEUp:
2575 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002576 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002577 break;
2578
2579 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2580 // returned together with the previous X87 value in %st0.
2581 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002582 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002583 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002584 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002585 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002586 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002587 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002588 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2589 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002590 }
Chris Lattner31faff52010-07-28 23:06:14 +00002591 break;
2592 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002593
Chris Lattner52b3c132010-09-01 00:20:33 +00002594 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002595 // known to pass in the high eightbyte of the result. We do this by forming a
2596 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002597 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002598 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002599
Chris Lattner1f3a0632010-07-29 21:42:50 +00002600 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002601}
2602
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002603ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002604 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2605 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002606 const
2607{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002608 Ty = useFirstFieldIfTransparentUnion(Ty);
2609
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002610 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002611 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002612
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002613 // Check some invariants.
2614 // FIXME: Enforce these by construction.
2615 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2617
2618 neededInt = 0;
2619 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002620 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002621 switch (Lo) {
2622 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002623 if (Hi == NoClass)
2624 return ABIArgInfo::getIgnore();
2625 // If the low part is just padding, it takes no register, leave ResType
2626 // null.
2627 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2628 "Unknown missing lo part");
2629 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002630
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002631 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2632 // on the stack.
2633 case Memory:
2634
2635 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2636 // COMPLEX_X87, it is passed in memory.
2637 case X87:
2638 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002639 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002640 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002641 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002642
2643 case SSEUp:
2644 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002645 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002646
2647 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2648 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2649 // and %r9 is used.
2650 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002651 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002652
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002653 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002654 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002655
2656 // If we have a sign or zero extended integer, make sure to return Extend
2657 // so that the parameter gets the right LLVM IR attributes.
2658 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2659 // Treat an enum type as its underlying type.
2660 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2661 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002662
Chris Lattner1f3a0632010-07-29 21:42:50 +00002663 if (Ty->isIntegralOrEnumerationType() &&
2664 Ty->isPromotableIntegerType())
2665 return ABIArgInfo::getExtend();
2666 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002667
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002668 break;
2669
2670 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2671 // available SSE register is used, the registers are taken in the
2672 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002673 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002674 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002675 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002676 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002677 break;
2678 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002679 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002680
Craig Topper8a13c412014-05-21 05:09:00 +00002681 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002682 switch (Hi) {
2683 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002684 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685 // which is passed in memory.
2686 case Memory:
2687 case X87:
2688 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002689 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002690
2691 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002692
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002693 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002694 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002695 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002696 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002697
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002698 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2699 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002700 break;
2701
2702 // X87Up generally doesn't occur here (long double is passed in
2703 // memory), except in situations involving unions.
2704 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002705 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002706 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002707
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002708 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2709 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002710
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002711 ++neededSSE;
2712 break;
2713
2714 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2715 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002716 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002717 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002718 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002719 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002720 break;
2721 }
2722
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002723 // If a high part was specified, merge it together with the low part. It is
2724 // known to pass in the high eightbyte of the result. We do this by forming a
2725 // first class struct aggregate with the high and low part: {low, high}
2726 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002727 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002728
Chris Lattner1f3a0632010-07-29 21:42:50 +00002729 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002730}
2731
Chris Lattner22326a12010-07-29 02:31:05 +00002732void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002733
Reid Kleckner40ca9132014-05-13 22:05:45 +00002734 if (!getCXXABI().classifyReturnType(FI))
2735 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002736
2737 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002738 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002739
2740 // If the return value is indirect, then the hidden argument is consuming one
2741 // integer register.
2742 if (FI.getReturnInfo().isIndirect())
2743 --freeIntRegs;
2744
Peter Collingbournef7706832014-12-12 23:41:25 +00002745 // The chain argument effectively gives us another free register.
2746 if (FI.isChainCall())
2747 ++freeIntRegs;
2748
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002749 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002750 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2751 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002752 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002753 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002754 it != ie; ++it, ++ArgNo) {
2755 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002756
Bill Wendling9987c0e2010-10-18 23:51:38 +00002757 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002758 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002759 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002760
2761 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2762 // eightbyte of an argument, the whole argument is passed on the
2763 // stack. If registers have already been assigned for some
2764 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002765 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002766 freeIntRegs -= neededInt;
2767 freeSSERegs -= neededSSE;
2768 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002769 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002770 }
2771 }
2772}
2773
2774static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2775 QualType Ty,
2776 CodeGenFunction &CGF) {
David Blaikie2e804282015-04-05 22:47:07 +00002777 llvm::Value *overflow_arg_area_p = CGF.Builder.CreateStructGEP(
2778 nullptr, VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002779 llvm::Value *overflow_arg_area =
2780 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2781
2782 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2783 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002784 // It isn't stated explicitly in the standard, but in practice we use
2785 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002786 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2787 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002788 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002789 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002790 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002791 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2792 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002793 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002794 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002795 overflow_arg_area =
2796 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2797 overflow_arg_area->getType(),
2798 "overflow_arg_area.align");
2799 }
2800
2801 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002802 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002803 llvm::Value *Res =
2804 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002805 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002806
2807 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2808 // l->overflow_arg_area + sizeof(type).
2809 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2810 // an 8 byte boundary.
2811
2812 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002813 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002814 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002815 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2816 "overflow_arg_area.next");
2817 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2818
2819 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2820 return Res;
2821}
2822
2823llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2824 CodeGenFunction &CGF) const {
2825 // Assume that va_list type is correct; should be pointer to LLVM type:
2826 // struct {
2827 // i32 gp_offset;
2828 // i32 fp_offset;
2829 // i8* overflow_arg_area;
2830 // i8* reg_save_area;
2831 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002832 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002833
Chris Lattner9723d6c2010-03-11 18:19:55 +00002834 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002835 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2836 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002837
2838 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2839 // in the registers. If not go to step 7.
2840 if (!neededInt && !neededSSE)
2841 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2842
2843 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2844 // general purpose registers needed to pass type and num_fp to hold
2845 // the number of floating point registers needed.
2846
2847 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2848 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2849 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2850 //
2851 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2852 // register save space).
2853
Craig Topper8a13c412014-05-21 05:09:00 +00002854 llvm::Value *InRegs = nullptr;
2855 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2856 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002857 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002858 gp_offset_p =
2859 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002860 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002861 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2862 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002863 }
2864
2865 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002866 fp_offset_p =
2867 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002868 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2869 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002870 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2871 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002872 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2873 }
2874
2875 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2876 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2877 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2878 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2879
2880 // Emit code to load the value if it was passed in registers.
2881
2882 CGF.EmitBlock(InRegBlock);
2883
2884 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2885 // an offset of l->gp_offset and/or l->fp_offset. This may require
2886 // copying to a temporary location in case the parameter is passed
2887 // in different register classes or requires an alignment greater
2888 // than 8 for general purpose registers and 16 for XMM registers.
2889 //
2890 // FIXME: This really results in shameful code when we end up needing to
2891 // collect arguments from different places; often what should result in a
2892 // simple assembling of a structure from scattered addresses has many more
2893 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002894 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
David Blaikie1ed728c2015-04-05 22:45:47 +00002895 llvm::Value *RegAddr = CGF.Builder.CreateLoad(
2896 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3), "reg_save_area");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002897 if (neededInt && neededSSE) {
2898 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002899 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002900 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002901 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2902 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002903 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002904 llvm::Type *TyLo = ST->getElementType(0);
2905 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002906 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002907 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002908 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2909 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002910 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2911 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002912 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2913 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002914 llvm::Value *V =
2915 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
David Blaikie1ed728c2015-04-05 22:45:47 +00002916 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002917 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
David Blaikie1ed728c2015-04-05 22:45:47 +00002918 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002919
Owen Anderson170229f2009-07-14 23:10:40 +00002920 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002921 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002922 } else if (neededInt) {
2923 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2924 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002925 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002926
2927 // Copy to a temporary if necessary to ensure the appropriate alignment.
2928 std::pair<CharUnits, CharUnits> SizeAlign =
2929 CGF.getContext().getTypeInfoInChars(Ty);
2930 uint64_t TySize = SizeAlign.first.getQuantity();
2931 unsigned TyAlign = SizeAlign.second.getQuantity();
2932 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002933 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2934 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2935 RegAddr = Tmp;
2936 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002937 } else if (neededSSE == 1) {
2938 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2939 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2940 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002941 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002942 assert(neededSSE == 2 && "Invalid number of needed registers!");
2943 // SSE registers are spaced 16 bytes apart in the register save
2944 // area, we need to collect the two eightbytes together.
2945 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002946 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002947 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002948 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002949 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00002950 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002951 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2952 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002953 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2954 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002955 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Chris Lattner0cf24192010-06-28 20:05:43 +00002956 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2957 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002958 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Chris Lattner0cf24192010-06-28 20:05:43 +00002959 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2960 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002961 }
2962
2963 // AMD64-ABI 3.5.7p5: Step 5. Set:
2964 // l->gp_offset = l->gp_offset + num_gp * 8
2965 // l->fp_offset = l->fp_offset + num_fp * 16.
2966 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002967 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002968 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2969 gp_offset_p);
2970 }
2971 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002972 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002973 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2974 fp_offset_p);
2975 }
2976 CGF.EmitBranch(ContBlock);
2977
2978 // Emit code to load the value if it was passed in memory.
2979
2980 CGF.EmitBlock(InMemBlock);
2981 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2982
2983 // Return the appropriate result.
2984
2985 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002986 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002987 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002988 ResAddr->addIncoming(RegAddr, InRegBlock);
2989 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002990 return ResAddr;
2991}
2992
Reid Kleckner80944df2014-10-31 22:00:51 +00002993ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
2994 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002995
2996 if (Ty->isVoidType())
2997 return ABIArgInfo::getIgnore();
2998
2999 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3000 Ty = EnumTy->getDecl()->getIntegerType();
3001
Reid Kleckner80944df2014-10-31 22:00:51 +00003002 TypeInfo Info = getContext().getTypeInfo(Ty);
3003 uint64_t Width = Info.Width;
3004 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003005
Reid Kleckner9005f412014-05-02 00:51:20 +00003006 const RecordType *RT = Ty->getAs<RecordType>();
3007 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003008 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003009 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003010 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3011 }
3012
3013 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003014 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3015
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003016 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003017 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003018 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003019 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003020 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003021
Reid Kleckner80944df2014-10-31 22:00:51 +00003022 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3023 // other targets.
3024 const Type *Base = nullptr;
3025 uint64_t NumElts = 0;
3026 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3027 if (FreeSSERegs >= NumElts) {
3028 FreeSSERegs -= NumElts;
3029 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3030 return ABIArgInfo::getDirect();
3031 return ABIArgInfo::getExpand();
3032 }
3033 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3034 }
3035
3036
Reid Klecknerec87fec2014-05-02 01:17:12 +00003037 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003038 // If the member pointer is represented by an LLVM int or ptr, pass it
3039 // directly.
3040 llvm::Type *LLTy = CGT.ConvertType(Ty);
3041 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3042 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003043 }
3044
Michael Kuperstein4f818702015-02-24 09:35:58 +00003045 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003046 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3047 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003048 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003049 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003050
Reid Kleckner9005f412014-05-02 00:51:20 +00003051 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003052 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003053 }
3054
Julien Lerouge10dcff82014-08-27 00:36:55 +00003055 // Bool type is always extended to the ABI, other builtin types are not
3056 // extended.
3057 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3058 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003059 return ABIArgInfo::getExtend();
3060
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003061 return ABIArgInfo::getDirect();
3062}
3063
3064void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003065 bool IsVectorCall =
3066 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003067
Reid Kleckner80944df2014-10-31 22:00:51 +00003068 // We can use up to 4 SSE return registers with vectorcall.
3069 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3070 if (!getCXXABI().classifyReturnType(FI))
3071 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3072
3073 // We can use up to 6 SSE register parameters with vectorcall.
3074 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003075 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003076 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003077}
3078
Chris Lattner04dc9572010-08-31 16:44:54 +00003079llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3080 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003081 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003082
Chris Lattner04dc9572010-08-31 16:44:54 +00003083 CGBuilderTy &Builder = CGF.Builder;
3084 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3085 "ap");
3086 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3087 llvm::Type *PTy =
3088 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3089 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3090
3091 uint64_t Offset =
3092 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3093 llvm::Value *NextAddr =
3094 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3095 "ap.next");
3096 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3097
3098 return AddrTyped;
3099}
Chris Lattner0cf24192010-06-28 20:05:43 +00003100
John McCallea8d8bb2010-03-11 00:10:12 +00003101// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003102namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003103/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3104class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003105public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003106 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3107
3108 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3109 CodeGenFunction &CGF) const override;
3110};
3111
3112class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3113public:
3114 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003115
Craig Topper4f12f102014-03-12 06:41:41 +00003116 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003117 // This is recovered from gcc output.
3118 return 1; // r1 is the dedicated stack pointer
3119 }
3120
3121 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003122 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003123
3124 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3125 return 16; // Natural alignment for Altivec vectors.
3126 }
John McCallea8d8bb2010-03-11 00:10:12 +00003127};
3128
3129}
3130
Roman Divacky8a12d842014-11-03 18:32:54 +00003131llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3132 QualType Ty,
3133 CodeGenFunction &CGF) const {
3134 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3135 // TODO: Implement this. For now ignore.
3136 (void)CTy;
3137 return nullptr;
3138 }
3139
3140 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3141 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3142 llvm::Type *CharPtr = CGF.Int8PtrTy;
3143 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3144
3145 CGBuilderTy &Builder = CGF.Builder;
3146 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3147 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3148 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3149 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3150 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3151 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3152 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3153 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3154 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3155 // Align GPR when TY is i64.
3156 if (isI64) {
3157 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3158 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3159 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3160 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3161 }
3162 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3163 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3164 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3165 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3166 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3167
3168 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3169 Builder.getInt8(8), "cond");
3170
3171 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3172 Builder.getInt8(isInt ? 4 : 8));
3173
3174 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3175
3176 if (Ty->isFloatingType())
3177 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3178
3179 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3180 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3181 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3182
3183 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3184
3185 CGF.EmitBlock(UsingRegs);
3186
3187 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3188 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3189 // Increase the GPR/FPR indexes.
3190 if (isInt) {
3191 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3192 Builder.CreateStore(GPR, GPRPtr);
3193 } else {
3194 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3195 Builder.CreateStore(FPR, FPRPtr);
3196 }
3197 CGF.EmitBranch(Cont);
3198
3199 CGF.EmitBlock(UsingOverflow);
3200
3201 // Increase the overflow area.
3202 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3203 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3204 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3205 CGF.EmitBranch(Cont);
3206
3207 CGF.EmitBlock(Cont);
3208
3209 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3210 Result->addIncoming(Result1, UsingRegs);
3211 Result->addIncoming(Result2, UsingOverflow);
3212
3213 if (Ty->isAggregateType()) {
3214 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3215 return Builder.CreateLoad(AGGPtr, false, "aggr");
3216 }
3217
3218 return Result;
3219}
3220
John McCallea8d8bb2010-03-11 00:10:12 +00003221bool
3222PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3223 llvm::Value *Address) const {
3224 // This is calculated from the LLVM and GCC tables and verified
3225 // against gcc output. AFAIK all ABIs use the same encoding.
3226
3227 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003228
Chris Lattnerece04092012-02-07 00:39:47 +00003229 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003230 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3231 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3232 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3233
3234 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003235 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003236
3237 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003238 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003239
3240 // 64-76 are various 4-byte special-purpose registers:
3241 // 64: mq
3242 // 65: lr
3243 // 66: ctr
3244 // 67: ap
3245 // 68-75 cr0-7
3246 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003247 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003248
3249 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003250 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003251
3252 // 109: vrsave
3253 // 110: vscr
3254 // 111: spe_acc
3255 // 112: spefscr
3256 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003257 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003258
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003259 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003260}
3261
Roman Divackyd966e722012-05-09 18:22:46 +00003262// PowerPC-64
3263
3264namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003265/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3266class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003267public:
3268 enum ABIKind {
3269 ELFv1 = 0,
3270 ELFv2
3271 };
3272
3273private:
3274 static const unsigned GPRBits = 64;
3275 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003276 bool HasQPX;
3277
3278 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3279 // will be passed in a QPX register.
3280 bool IsQPXVectorTy(const Type *Ty) const {
3281 if (!HasQPX)
3282 return false;
3283
3284 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3285 unsigned NumElements = VT->getNumElements();
3286 if (NumElements == 1)
3287 return false;
3288
3289 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3290 if (getContext().getTypeSize(Ty) <= 256)
3291 return true;
3292 } else if (VT->getElementType()->
3293 isSpecificBuiltinType(BuiltinType::Float)) {
3294 if (getContext().getTypeSize(Ty) <= 128)
3295 return true;
3296 }
3297 }
3298
3299 return false;
3300 }
3301
3302 bool IsQPXVectorTy(QualType Ty) const {
3303 return IsQPXVectorTy(Ty.getTypePtr());
3304 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003305
3306public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003307 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3308 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003309
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003310 bool isPromotableTypeForABI(QualType Ty) const;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003311 bool isAlignedParamType(QualType Ty, bool &Align32) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003312
3313 ABIArgInfo classifyReturnType(QualType RetTy) const;
3314 ABIArgInfo classifyArgumentType(QualType Ty) const;
3315
Reid Klecknere9f6a712014-10-31 17:10:41 +00003316 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3317 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3318 uint64_t Members) const override;
3319
Bill Schmidt84d37792012-10-12 19:26:17 +00003320 // TODO: We can add more logic to computeInfo to improve performance.
3321 // Example: For aggregate arguments that fit in a register, we could
3322 // use getDirectInReg (as is done below for structs containing a single
3323 // floating-point value) to avoid pushing them to memory on function
3324 // entry. This would require changing the logic in PPCISelLowering
3325 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003326 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003327 if (!getCXXABI().classifyReturnType(FI))
3328 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003329 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003330 // We rely on the default argument classification for the most part.
3331 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003332 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003333 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003334 if (T) {
3335 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003336 if (IsQPXVectorTy(T) ||
3337 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003338 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003339 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003340 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003341 continue;
3342 }
3343 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003344 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003345 }
3346 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003347
Craig Topper4f12f102014-03-12 06:41:41 +00003348 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3349 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003350};
3351
3352class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003353 bool HasQPX;
3354
Bill Schmidt25cb3492012-10-03 19:18:57 +00003355public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003356 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003357 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
3358 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)),
3359 HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003360
Craig Topper4f12f102014-03-12 06:41:41 +00003361 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003362 // This is recovered from gcc output.
3363 return 1; // r1 is the dedicated stack pointer
3364 }
3365
3366 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003367 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003368
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003369 unsigned getOpenMPSimdDefaultAlignment(QualType QT) const override {
3370 if (HasQPX)
3371 if (const PointerType *PT = QT->getAs<PointerType>())
3372 if (PT->getPointeeType()->isSpecificBuiltinType(BuiltinType::Double))
3373 return 32; // Natural alignment for QPX doubles.
3374
Hal Finkel92e31a52014-10-03 17:45:20 +00003375 return 16; // Natural alignment for Altivec and VSX vectors.
3376 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003377};
3378
Roman Divackyd966e722012-05-09 18:22:46 +00003379class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3380public:
3381 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3382
Craig Topper4f12f102014-03-12 06:41:41 +00003383 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003384 // This is recovered from gcc output.
3385 return 1; // r1 is the dedicated stack pointer
3386 }
3387
3388 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003389 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003390
3391 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3392 return 16; // Natural alignment for Altivec vectors.
3393 }
Roman Divackyd966e722012-05-09 18:22:46 +00003394};
3395
3396}
3397
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003398// Return true if the ABI requires Ty to be passed sign- or zero-
3399// extended to 64 bits.
3400bool
3401PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3402 // Treat an enum type as its underlying type.
3403 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3404 Ty = EnumTy->getDecl()->getIntegerType();
3405
3406 // Promotable integer types are required to be promoted by the ABI.
3407 if (Ty->isPromotableIntegerType())
3408 return true;
3409
3410 // In addition to the usual promotable integer types, we also need to
3411 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3412 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3413 switch (BT->getKind()) {
3414 case BuiltinType::Int:
3415 case BuiltinType::UInt:
3416 return true;
3417 default:
3418 break;
3419 }
3420
3421 return false;
3422}
3423
Ulrich Weigand581badc2014-07-10 17:20:07 +00003424/// isAlignedParamType - Determine whether a type requires 16-byte
3425/// alignment in the parameter area.
3426bool
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003427PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty, bool &Align32) const {
3428 Align32 = false;
3429
Ulrich Weigand581badc2014-07-10 17:20:07 +00003430 // Complex types are passed just like their elements.
3431 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3432 Ty = CTy->getElementType();
3433
3434 // Only vector types of size 16 bytes need alignment (larger types are
3435 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003436 if (IsQPXVectorTy(Ty)) {
3437 if (getContext().getTypeSize(Ty) > 128)
3438 Align32 = true;
3439
3440 return true;
3441 } else if (Ty->isVectorType()) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003442 return getContext().getTypeSize(Ty) == 128;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003443 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003444
3445 // For single-element float/vector structs, we consider the whole type
3446 // to have the same alignment requirements as its single element.
3447 const Type *AlignAsType = nullptr;
3448 const Type *EltType = isSingleElementStruct(Ty, getContext());
3449 if (EltType) {
3450 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003451 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003452 getContext().getTypeSize(EltType) == 128) ||
3453 (BT && BT->isFloatingPoint()))
3454 AlignAsType = EltType;
3455 }
3456
Ulrich Weigandb7122372014-07-21 00:48:09 +00003457 // Likewise for ELFv2 homogeneous aggregates.
3458 const Type *Base = nullptr;
3459 uint64_t Members = 0;
3460 if (!AlignAsType && Kind == ELFv2 &&
3461 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3462 AlignAsType = Base;
3463
Ulrich Weigand581badc2014-07-10 17:20:07 +00003464 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003465 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3466 if (getContext().getTypeSize(AlignAsType) > 128)
3467 Align32 = true;
3468
3469 return true;
3470 } else if (AlignAsType) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003471 return AlignAsType->isVectorType();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003472 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003473
3474 // Otherwise, we only need alignment for any aggregate type that
3475 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003476 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3477 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
3478 Align32 = true;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003479 return true;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003480 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003481
3482 return false;
3483}
3484
Ulrich Weigandb7122372014-07-21 00:48:09 +00003485/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3486/// aggregate. Base is set to the base element type, and Members is set
3487/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003488bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3489 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003490 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3491 uint64_t NElements = AT->getSize().getZExtValue();
3492 if (NElements == 0)
3493 return false;
3494 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3495 return false;
3496 Members *= NElements;
3497 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3498 const RecordDecl *RD = RT->getDecl();
3499 if (RD->hasFlexibleArrayMember())
3500 return false;
3501
3502 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003503
3504 // If this is a C++ record, check the bases first.
3505 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3506 for (const auto &I : CXXRD->bases()) {
3507 // Ignore empty records.
3508 if (isEmptyRecord(getContext(), I.getType(), true))
3509 continue;
3510
3511 uint64_t FldMembers;
3512 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3513 return false;
3514
3515 Members += FldMembers;
3516 }
3517 }
3518
Ulrich Weigandb7122372014-07-21 00:48:09 +00003519 for (const auto *FD : RD->fields()) {
3520 // Ignore (non-zero arrays of) empty records.
3521 QualType FT = FD->getType();
3522 while (const ConstantArrayType *AT =
3523 getContext().getAsConstantArrayType(FT)) {
3524 if (AT->getSize().getZExtValue() == 0)
3525 return false;
3526 FT = AT->getElementType();
3527 }
3528 if (isEmptyRecord(getContext(), FT, true))
3529 continue;
3530
3531 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3532 if (getContext().getLangOpts().CPlusPlus &&
3533 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3534 continue;
3535
3536 uint64_t FldMembers;
3537 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3538 return false;
3539
3540 Members = (RD->isUnion() ?
3541 std::max(Members, FldMembers) : Members + FldMembers);
3542 }
3543
3544 if (!Base)
3545 return false;
3546
3547 // Ensure there is no padding.
3548 if (getContext().getTypeSize(Base) * Members !=
3549 getContext().getTypeSize(Ty))
3550 return false;
3551 } else {
3552 Members = 1;
3553 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3554 Members = 2;
3555 Ty = CT->getElementType();
3556 }
3557
Reid Klecknere9f6a712014-10-31 17:10:41 +00003558 // Most ABIs only support float, double, and some vector type widths.
3559 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003560 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003561
3562 // The base type must be the same for all members. Types that
3563 // agree in both total size and mode (float vs. vector) are
3564 // treated as being equivalent here.
3565 const Type *TyPtr = Ty.getTypePtr();
3566 if (!Base)
3567 Base = TyPtr;
3568
3569 if (Base->isVectorType() != TyPtr->isVectorType() ||
3570 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3571 return false;
3572 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003573 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3574}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003575
Reid Klecknere9f6a712014-10-31 17:10:41 +00003576bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3577 // Homogeneous aggregates for ELFv2 must have base types of float,
3578 // double, long double, or 128-bit vectors.
3579 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3580 if (BT->getKind() == BuiltinType::Float ||
3581 BT->getKind() == BuiltinType::Double ||
3582 BT->getKind() == BuiltinType::LongDouble)
3583 return true;
3584 }
3585 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003586 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003587 return true;
3588 }
3589 return false;
3590}
3591
3592bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3593 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003594 // Vector types require one register, floating point types require one
3595 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003596 uint32_t NumRegs =
3597 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003598
3599 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003600 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003601}
3602
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003603ABIArgInfo
3604PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003605 Ty = useFirstFieldIfTransparentUnion(Ty);
3606
Bill Schmidt90b22c92012-11-27 02:46:43 +00003607 if (Ty->isAnyComplexType())
3608 return ABIArgInfo::getDirect();
3609
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003610 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3611 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003612 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003613 uint64_t Size = getContext().getTypeSize(Ty);
3614 if (Size > 128)
3615 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3616 else if (Size < 128) {
3617 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3618 return ABIArgInfo::getDirect(CoerceTy);
3619 }
3620 }
3621
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003622 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003623 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003624 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003625
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003626 bool Align32;
3627 uint64_t ABIAlign = isAlignedParamType(Ty, Align32) ?
3628 (Align32 ? 32 : 16) : 8;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003629 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003630
3631 // ELFv2 homogeneous aggregates are passed as array types.
3632 const Type *Base = nullptr;
3633 uint64_t Members = 0;
3634 if (Kind == ELFv2 &&
3635 isHomogeneousAggregate(Ty, Base, Members)) {
3636 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3637 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3638 return ABIArgInfo::getDirect(CoerceTy);
3639 }
3640
Ulrich Weigand601957f2014-07-21 00:56:36 +00003641 // If an aggregate may end up fully in registers, we do not
3642 // use the ByVal method, but pass the aggregate as array.
3643 // This is usually beneficial since we avoid forcing the
3644 // back-end to store the argument to memory.
3645 uint64_t Bits = getContext().getTypeSize(Ty);
3646 if (Bits > 0 && Bits <= 8 * GPRBits) {
3647 llvm::Type *CoerceTy;
3648
3649 // Types up to 8 bytes are passed as integer type (which will be
3650 // properly aligned in the argument save area doubleword).
3651 if (Bits <= GPRBits)
3652 CoerceTy = llvm::IntegerType::get(getVMContext(),
3653 llvm::RoundUpToAlignment(Bits, 8));
3654 // Larger types are passed as arrays, with the base type selected
3655 // according to the required alignment in the save area.
3656 else {
3657 uint64_t RegBits = ABIAlign * 8;
3658 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3659 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3660 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3661 }
3662
3663 return ABIArgInfo::getDirect(CoerceTy);
3664 }
3665
Ulrich Weigandb7122372014-07-21 00:48:09 +00003666 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003667 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3668 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003669 }
3670
3671 return (isPromotableTypeForABI(Ty) ?
3672 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3673}
3674
3675ABIArgInfo
3676PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3677 if (RetTy->isVoidType())
3678 return ABIArgInfo::getIgnore();
3679
Bill Schmidta3d121c2012-12-17 04:20:17 +00003680 if (RetTy->isAnyComplexType())
3681 return ABIArgInfo::getDirect();
3682
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003683 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3684 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003685 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003686 uint64_t Size = getContext().getTypeSize(RetTy);
3687 if (Size > 128)
3688 return ABIArgInfo::getIndirect(0);
3689 else if (Size < 128) {
3690 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3691 return ABIArgInfo::getDirect(CoerceTy);
3692 }
3693 }
3694
Ulrich Weigandb7122372014-07-21 00:48:09 +00003695 if (isAggregateTypeForABI(RetTy)) {
3696 // ELFv2 homogeneous aggregates are returned as array types.
3697 const Type *Base = nullptr;
3698 uint64_t Members = 0;
3699 if (Kind == ELFv2 &&
3700 isHomogeneousAggregate(RetTy, Base, Members)) {
3701 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3702 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3703 return ABIArgInfo::getDirect(CoerceTy);
3704 }
3705
3706 // ELFv2 small aggregates are returned in up to two registers.
3707 uint64_t Bits = getContext().getTypeSize(RetTy);
3708 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3709 if (Bits == 0)
3710 return ABIArgInfo::getIgnore();
3711
3712 llvm::Type *CoerceTy;
3713 if (Bits > GPRBits) {
3714 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003715 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003716 } else
3717 CoerceTy = llvm::IntegerType::get(getVMContext(),
3718 llvm::RoundUpToAlignment(Bits, 8));
3719 return ABIArgInfo::getDirect(CoerceTy);
3720 }
3721
3722 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003723 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003724 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003725
3726 return (isPromotableTypeForABI(RetTy) ?
3727 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3728}
3729
Bill Schmidt25cb3492012-10-03 19:18:57 +00003730// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3731llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3732 QualType Ty,
3733 CodeGenFunction &CGF) const {
3734 llvm::Type *BP = CGF.Int8PtrTy;
3735 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3736
3737 CGBuilderTy &Builder = CGF.Builder;
3738 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3739 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3740
Ulrich Weigand581badc2014-07-10 17:20:07 +00003741 // Handle types that require 16-byte alignment in the parameter save area.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003742 bool Align32;
3743 if (isAlignedParamType(Ty, Align32)) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003744 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003745 AddrAsInt = Builder.CreateAdd(AddrAsInt,
3746 Builder.getInt64(Align32 ? 31 : 15));
3747 AddrAsInt = Builder.CreateAnd(AddrAsInt,
3748 Builder.getInt64(Align32 ? -32 : -16));
Ulrich Weigand581badc2014-07-10 17:20:07 +00003749 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3750 }
3751
Bill Schmidt924c4782013-01-14 17:45:36 +00003752 // Update the va_list pointer. The pointer should be bumped by the
3753 // size of the object. We can trust getTypeSize() except for a complex
3754 // type whose base type is smaller than a doubleword. For these, the
3755 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003756 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003757 QualType BaseTy;
3758 unsigned CplxBaseSize = 0;
3759
3760 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3761 BaseTy = CTy->getElementType();
3762 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3763 if (CplxBaseSize < 8)
3764 SizeInBytes = 16;
3765 }
3766
Bill Schmidt25cb3492012-10-03 19:18:57 +00003767 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3768 llvm::Value *NextAddr =
3769 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3770 "ap.next");
3771 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3772
Bill Schmidt924c4782013-01-14 17:45:36 +00003773 // If we have a complex type and the base type is smaller than 8 bytes,
3774 // the ABI calls for the real and imaginary parts to be right-adjusted
3775 // in separate doublewords. However, Clang expects us to produce a
3776 // pointer to a structure with the two parts packed tightly. So generate
3777 // loads of the real and imaginary parts relative to the va_list pointer,
3778 // and store them to a temporary structure.
3779 if (CplxBaseSize && CplxBaseSize < 8) {
3780 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3781 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003782 if (CGF.CGM.getDataLayout().isBigEndian()) {
3783 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3784 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3785 } else {
3786 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3787 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003788 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3789 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3790 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3791 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3792 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
David Blaikie2e804282015-04-05 22:47:07 +00003793 llvm::AllocaInst *Ptr =
3794 CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), "vacplx");
3795 llvm::Value *RealPtr =
3796 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 0, ".real");
3797 llvm::Value *ImagPtr =
3798 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 1, ".imag");
Bill Schmidt924c4782013-01-14 17:45:36 +00003799 Builder.CreateStore(Real, RealPtr, false);
3800 Builder.CreateStore(Imag, ImagPtr, false);
3801 return Ptr;
3802 }
3803
Bill Schmidt25cb3492012-10-03 19:18:57 +00003804 // If the argument is smaller than 8 bytes, it is right-adjusted in
3805 // its doubleword slot. Adjust the pointer to pick it up from the
3806 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003807 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003808 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3809 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3810 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3811 }
3812
3813 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3814 return Builder.CreateBitCast(Addr, PTy);
3815}
3816
3817static bool
3818PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3819 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003820 // This is calculated from the LLVM and GCC tables and verified
3821 // against gcc output. AFAIK all ABIs use the same encoding.
3822
3823 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3824
3825 llvm::IntegerType *i8 = CGF.Int8Ty;
3826 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3827 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3828 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3829
3830 // 0-31: r0-31, the 8-byte general-purpose registers
3831 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3832
3833 // 32-63: fp0-31, the 8-byte floating-point registers
3834 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3835
3836 // 64-76 are various 4-byte special-purpose registers:
3837 // 64: mq
3838 // 65: lr
3839 // 66: ctr
3840 // 67: ap
3841 // 68-75 cr0-7
3842 // 76: xer
3843 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3844
3845 // 77-108: v0-31, the 16-byte vector registers
3846 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3847
3848 // 109: vrsave
3849 // 110: vscr
3850 // 111: spe_acc
3851 // 112: spefscr
3852 // 113: sfp
3853 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3854
3855 return false;
3856}
John McCallea8d8bb2010-03-11 00:10:12 +00003857
Bill Schmidt25cb3492012-10-03 19:18:57 +00003858bool
3859PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3860 CodeGen::CodeGenFunction &CGF,
3861 llvm::Value *Address) const {
3862
3863 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3864}
3865
3866bool
3867PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3868 llvm::Value *Address) const {
3869
3870 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3871}
3872
Chris Lattner0cf24192010-06-28 20:05:43 +00003873//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003874// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003875//===----------------------------------------------------------------------===//
3876
3877namespace {
3878
Tim Northover573cbee2014-05-24 12:52:07 +00003879class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003880public:
3881 enum ABIKind {
3882 AAPCS = 0,
3883 DarwinPCS
3884 };
3885
3886private:
3887 ABIKind Kind;
3888
3889public:
Tim Northover573cbee2014-05-24 12:52:07 +00003890 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003891
3892private:
3893 ABIKind getABIKind() const { return Kind; }
3894 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3895
3896 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003897 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003898 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3899 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3900 uint64_t Members) const override;
3901
Tim Northovera2ee4332014-03-29 15:09:45 +00003902 bool isIllegalVectorType(QualType Ty) const;
3903
David Blaikie1cbb9712014-11-14 19:09:44 +00003904 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003905 if (!getCXXABI().classifyReturnType(FI))
3906 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003907
Tim Northoverb047bfa2014-11-27 21:02:49 +00003908 for (auto &it : FI.arguments())
3909 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003910 }
3911
3912 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3913 CodeGenFunction &CGF) const;
3914
3915 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3916 CodeGenFunction &CGF) const;
3917
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003918 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3919 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003920 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3921 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3922 }
3923};
3924
Tim Northover573cbee2014-05-24 12:52:07 +00003925class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003926public:
Tim Northover573cbee2014-05-24 12:52:07 +00003927 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3928 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003929
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003930 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003931 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3932 }
3933
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003934 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3935 return 31;
3936 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003937
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003938 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00003939};
3940}
3941
Tim Northoverb047bfa2014-11-27 21:02:49 +00003942ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003943 Ty = useFirstFieldIfTransparentUnion(Ty);
3944
Tim Northovera2ee4332014-03-29 15:09:45 +00003945 // Handle illegal vector types here.
3946 if (isIllegalVectorType(Ty)) {
3947 uint64_t Size = getContext().getTypeSize(Ty);
3948 if (Size <= 32) {
3949 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00003950 return ABIArgInfo::getDirect(ResType);
3951 }
3952 if (Size == 64) {
3953 llvm::Type *ResType =
3954 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00003955 return ABIArgInfo::getDirect(ResType);
3956 }
3957 if (Size == 128) {
3958 llvm::Type *ResType =
3959 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00003960 return ABIArgInfo::getDirect(ResType);
3961 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003962 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3963 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003964
3965 if (!isAggregateTypeForABI(Ty)) {
3966 // Treat an enum type as its underlying type.
3967 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3968 Ty = EnumTy->getDecl()->getIntegerType();
3969
Tim Northovera2ee4332014-03-29 15:09:45 +00003970 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3971 ? ABIArgInfo::getExtend()
3972 : ABIArgInfo::getDirect());
3973 }
3974
3975 // Structures with either a non-trivial destructor or a non-trivial
3976 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003977 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003978 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00003979 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003980 }
3981
3982 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3983 // elsewhere for GNU compatibility.
3984 if (isEmptyRecord(getContext(), Ty, true)) {
3985 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3986 return ABIArgInfo::getIgnore();
3987
Tim Northovera2ee4332014-03-29 15:09:45 +00003988 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3989 }
3990
3991 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003992 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003993 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003994 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00003995 return ABIArgInfo::getDirect(
3996 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00003997 }
3998
3999 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4000 uint64_t Size = getContext().getTypeSize(Ty);
4001 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004002 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004003 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004004
Tim Northovera2ee4332014-03-29 15:09:45 +00004005 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4006 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004007 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004008 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4009 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4010 }
4011 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4012 }
4013
Tim Northovera2ee4332014-03-29 15:09:45 +00004014 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4015}
4016
Tim Northover573cbee2014-05-24 12:52:07 +00004017ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004018 if (RetTy->isVoidType())
4019 return ABIArgInfo::getIgnore();
4020
4021 // Large vector types should be returned via memory.
4022 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4023 return ABIArgInfo::getIndirect(0);
4024
4025 if (!isAggregateTypeForABI(RetTy)) {
4026 // Treat an enum type as its underlying type.
4027 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4028 RetTy = EnumTy->getDecl()->getIntegerType();
4029
Tim Northover4dab6982014-04-18 13:46:08 +00004030 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4031 ? ABIArgInfo::getExtend()
4032 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004033 }
4034
Tim Northovera2ee4332014-03-29 15:09:45 +00004035 if (isEmptyRecord(getContext(), RetTy, true))
4036 return ABIArgInfo::getIgnore();
4037
Craig Topper8a13c412014-05-21 05:09:00 +00004038 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004039 uint64_t Members = 0;
4040 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004041 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4042 return ABIArgInfo::getDirect();
4043
4044 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4045 uint64_t Size = getContext().getTypeSize(RetTy);
4046 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004047 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004048 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004049
4050 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4051 // For aggregates with 16-byte alignment, we use i128.
4052 if (Alignment < 128 && Size == 128) {
4053 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4054 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4055 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004056 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4057 }
4058
4059 return ABIArgInfo::getIndirect(0);
4060}
4061
Tim Northover573cbee2014-05-24 12:52:07 +00004062/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4063bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004064 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4065 // Check whether VT is legal.
4066 unsigned NumElements = VT->getNumElements();
4067 uint64_t Size = getContext().getTypeSize(VT);
4068 // NumElements should be power of 2 between 1 and 16.
4069 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4070 return true;
4071 return Size != 64 && (Size != 128 || NumElements == 1);
4072 }
4073 return false;
4074}
4075
Reid Klecknere9f6a712014-10-31 17:10:41 +00004076bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4077 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4078 // point type or a short-vector type. This is the same as the 32-bit ABI,
4079 // but with the difference that any floating-point type is allowed,
4080 // including __fp16.
4081 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4082 if (BT->isFloatingPoint())
4083 return true;
4084 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4085 unsigned VecSize = getContext().getTypeSize(VT);
4086 if (VecSize == 64 || VecSize == 128)
4087 return true;
4088 }
4089 return false;
4090}
4091
4092bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4093 uint64_t Members) const {
4094 return Members <= 4;
4095}
4096
Tim Northoverb047bfa2014-11-27 21:02:49 +00004097llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4098 QualType Ty,
4099 CodeGenFunction &CGF) const {
4100 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004101 bool IsIndirect = AI.isIndirect();
4102
Tim Northoverb047bfa2014-11-27 21:02:49 +00004103 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4104 if (IsIndirect)
4105 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4106 else if (AI.getCoerceToType())
4107 BaseTy = AI.getCoerceToType();
4108
4109 unsigned NumRegs = 1;
4110 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4111 BaseTy = ArrTy->getElementType();
4112 NumRegs = ArrTy->getNumElements();
4113 }
4114 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4115
Tim Northovera2ee4332014-03-29 15:09:45 +00004116 // The AArch64 va_list type and handling is specified in the Procedure Call
4117 // Standard, section B.4:
4118 //
4119 // struct {
4120 // void *__stack;
4121 // void *__gr_top;
4122 // void *__vr_top;
4123 // int __gr_offs;
4124 // int __vr_offs;
4125 // };
4126
4127 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4128 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4129 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4130 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4131 auto &Ctx = CGF.getContext();
4132
Craig Topper8a13c412014-05-21 05:09:00 +00004133 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004134 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004135 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4136 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004137 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004138 reg_offs_p =
4139 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004140 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4141 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004142 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004143 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004144 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004145 reg_offs_p =
4146 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004147 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4148 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004149 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004150 }
4151
4152 //=======================================
4153 // Find out where argument was passed
4154 //=======================================
4155
4156 // If reg_offs >= 0 we're already using the stack for this type of
4157 // argument. We don't want to keep updating reg_offs (in case it overflows,
4158 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4159 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004160 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004161 UsingStack = CGF.Builder.CreateICmpSGE(
4162 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4163
4164 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4165
4166 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004167 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004168 CGF.EmitBlock(MaybeRegBlock);
4169
4170 // Integer arguments may need to correct register alignment (for example a
4171 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4172 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004173 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004174 int Align = Ctx.getTypeAlign(Ty) / 8;
4175
4176 reg_offs = CGF.Builder.CreateAdd(
4177 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4178 "align_regoffs");
4179 reg_offs = CGF.Builder.CreateAnd(
4180 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4181 "aligned_regoffs");
4182 }
4183
4184 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004185 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004186 NewOffset = CGF.Builder.CreateAdd(
4187 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4188 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4189
4190 // Now we're in a position to decide whether this argument really was in
4191 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004192 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004193 InRegs = CGF.Builder.CreateICmpSLE(
4194 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4195
4196 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4197
4198 //=======================================
4199 // Argument was in registers
4200 //=======================================
4201
4202 // Now we emit the code for if the argument was originally passed in
4203 // registers. First start the appropriate block:
4204 CGF.EmitBlock(InRegBlock);
4205
Craig Topper8a13c412014-05-21 05:09:00 +00004206 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
David Blaikie2e804282015-04-05 22:47:07 +00004207 reg_top_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, reg_top_index,
4208 "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004209 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4210 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004211 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004212 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4213
4214 if (IsIndirect) {
4215 // If it's been passed indirectly (actually a struct), whatever we find from
4216 // stored registers or on the stack will actually be a struct **.
4217 MemTy = llvm::PointerType::getUnqual(MemTy);
4218 }
4219
Craig Topper8a13c412014-05-21 05:09:00 +00004220 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004221 uint64_t NumMembers = 0;
4222 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004223 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004224 // Homogeneous aggregates passed in registers will have their elements split
4225 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4226 // qN+1, ...). We reload and store into a temporary local variable
4227 // contiguously.
4228 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4229 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4230 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
David Blaikie1ed728c2015-04-05 22:45:47 +00004231 llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(HFATy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004232 int Offset = 0;
4233
4234 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4235 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4236 for (unsigned i = 0; i < NumMembers; ++i) {
4237 llvm::Value *BaseOffset =
4238 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4239 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4240 LoadAddr = CGF.Builder.CreateBitCast(
4241 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
David Blaikie2e804282015-04-05 22:47:07 +00004242 llvm::Value *StoreAddr =
4243 CGF.Builder.CreateStructGEP(Tmp->getAllocatedType(), Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00004244
4245 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4246 CGF.Builder.CreateStore(Elem, StoreAddr);
4247 }
4248
4249 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4250 } else {
4251 // Otherwise the object is contiguous in memory
4252 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004253 if (CGF.CGM.getDataLayout().isBigEndian() &&
4254 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004255 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4256 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4257 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4258
4259 BaseAddr = CGF.Builder.CreateAdd(
4260 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4261
4262 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4263 }
4264
4265 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4266 }
4267
4268 CGF.EmitBranch(ContBlock);
4269
4270 //=======================================
4271 // Argument was on the stack
4272 //=======================================
4273 CGF.EmitBlock(OnStackBlock);
4274
Craig Topper8a13c412014-05-21 05:09:00 +00004275 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
David Blaikie1ed728c2015-04-05 22:45:47 +00004276 stack_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "stack_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004277 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4278
4279 // Again, stack arguments may need realigmnent. In this case both integer and
4280 // floating-point ones might be affected.
4281 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4282 int Align = Ctx.getTypeAlign(Ty) / 8;
4283
4284 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4285
4286 OnStackAddr = CGF.Builder.CreateAdd(
4287 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4288 "align_stack");
4289 OnStackAddr = CGF.Builder.CreateAnd(
4290 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4291 "align_stack");
4292
4293 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4294 }
4295
4296 uint64_t StackSize;
4297 if (IsIndirect)
4298 StackSize = 8;
4299 else
4300 StackSize = Ctx.getTypeSize(Ty) / 8;
4301
4302 // All stack slots are 8 bytes
4303 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4304
4305 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4306 llvm::Value *NewStack =
4307 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4308
4309 // Write the new value of __stack for the next call to va_arg
4310 CGF.Builder.CreateStore(NewStack, stack_p);
4311
4312 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4313 Ctx.getTypeSize(Ty) < 64) {
4314 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4315 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4316
4317 OnStackAddr = CGF.Builder.CreateAdd(
4318 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4319
4320 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4321 }
4322
4323 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4324
4325 CGF.EmitBranch(ContBlock);
4326
4327 //=======================================
4328 // Tidy up
4329 //=======================================
4330 CGF.EmitBlock(ContBlock);
4331
4332 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4333 ResAddr->addIncoming(RegAddr, InRegBlock);
4334 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4335
4336 if (IsIndirect)
4337 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4338
4339 return ResAddr;
4340}
4341
Tim Northover573cbee2014-05-24 12:52:07 +00004342llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004343 CodeGenFunction &CGF) const {
4344 // We do not support va_arg for aggregates or illegal vector types.
4345 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4346 // other cases.
4347 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004348 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004349
4350 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4351 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4352
Craig Topper8a13c412014-05-21 05:09:00 +00004353 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004354 uint64_t Members = 0;
4355 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004356
4357 bool isIndirect = false;
4358 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4359 // be passed indirectly.
4360 if (Size > 16 && !isHA) {
4361 isIndirect = true;
4362 Size = 8;
4363 Align = 8;
4364 }
4365
4366 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4367 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4368
4369 CGBuilderTy &Builder = CGF.Builder;
4370 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4371 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4372
4373 if (isEmptyRecord(getContext(), Ty, true)) {
4374 // These are ignored for parameter passing purposes.
4375 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4376 return Builder.CreateBitCast(Addr, PTy);
4377 }
4378
4379 const uint64_t MinABIAlign = 8;
4380 if (Align > MinABIAlign) {
4381 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4382 Addr = Builder.CreateGEP(Addr, Offset);
4383 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4384 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4385 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4386 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4387 }
4388
4389 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4390 llvm::Value *NextAddr = Builder.CreateGEP(
4391 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4392 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4393
4394 if (isIndirect)
4395 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4396 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4397 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4398
4399 return AddrTyped;
4400}
4401
4402//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004403// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004404//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004405
4406namespace {
4407
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004408class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004409public:
4410 enum ABIKind {
4411 APCS = 0,
4412 AAPCS = 1,
4413 AAPCS_VFP
4414 };
4415
4416private:
4417 ABIKind Kind;
4418
4419public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004420 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004421 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004422 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004423
John McCall3480ef22011-08-30 01:42:09 +00004424 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004425 switch (getTarget().getTriple().getEnvironment()) {
4426 case llvm::Triple::Android:
4427 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004428 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004429 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004430 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004431 return true;
4432 default:
4433 return false;
4434 }
John McCall3480ef22011-08-30 01:42:09 +00004435 }
4436
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004437 bool isEABIHF() const {
4438 switch (getTarget().getTriple().getEnvironment()) {
4439 case llvm::Triple::EABIHF:
4440 case llvm::Triple::GNUEABIHF:
4441 return true;
4442 default:
4443 return false;
4444 }
4445 }
4446
Daniel Dunbar020daa92009-09-12 01:00:39 +00004447 ABIKind getABIKind() const { return Kind; }
4448
Tim Northovera484bc02013-10-01 14:34:25 +00004449private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004450 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004451 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004452 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004453
Reid Klecknere9f6a712014-10-31 17:10:41 +00004454 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4455 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4456 uint64_t Members) const override;
4457
Craig Topper4f12f102014-03-12 06:41:41 +00004458 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004459
Craig Topper4f12f102014-03-12 06:41:41 +00004460 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4461 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004462
4463 llvm::CallingConv::ID getLLVMDefaultCC() const;
4464 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004465 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004466};
4467
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004468class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4469public:
Chris Lattner2b037972010-07-29 02:01:43 +00004470 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4471 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004472
John McCall3480ef22011-08-30 01:42:09 +00004473 const ARMABIInfo &getABIInfo() const {
4474 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4475 }
4476
Craig Topper4f12f102014-03-12 06:41:41 +00004477 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004478 return 13;
4479 }
Roman Divackyc1617352011-05-18 19:36:54 +00004480
Craig Topper4f12f102014-03-12 06:41:41 +00004481 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004482 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4483 }
4484
Roman Divackyc1617352011-05-18 19:36:54 +00004485 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004486 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004487 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004488
4489 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004490 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004491 return false;
4492 }
John McCall3480ef22011-08-30 01:42:09 +00004493
Craig Topper4f12f102014-03-12 06:41:41 +00004494 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004495 if (getABIInfo().isEABI()) return 88;
4496 return TargetCodeGenInfo::getSizeOfUnwindException();
4497 }
Tim Northovera484bc02013-10-01 14:34:25 +00004498
4499 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004500 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004501 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4502 if (!FD)
4503 return;
4504
4505 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4506 if (!Attr)
4507 return;
4508
4509 const char *Kind;
4510 switch (Attr->getInterrupt()) {
4511 case ARMInterruptAttr::Generic: Kind = ""; break;
4512 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4513 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4514 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4515 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4516 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4517 }
4518
4519 llvm::Function *Fn = cast<llvm::Function>(GV);
4520
4521 Fn->addFnAttr("interrupt", Kind);
4522
4523 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4524 return;
4525
4526 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4527 // however this is not necessarily true on taking any interrupt. Instruct
4528 // the backend to perform a realignment as part of the function prologue.
4529 llvm::AttrBuilder B;
4530 B.addStackAlignmentAttr(8);
4531 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4532 llvm::AttributeSet::get(CGM.getLLVMContext(),
4533 llvm::AttributeSet::FunctionIndex,
4534 B));
4535 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004536};
4537
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004538class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4539 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4540 CodeGen::CodeGenModule &CGM) const;
4541
4542public:
4543 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4544 : ARMTargetCodeGenInfo(CGT, K) {}
4545
4546 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4547 CodeGen::CodeGenModule &CGM) const override;
4548};
4549
4550void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4551 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4552 if (!isa<FunctionDecl>(D))
4553 return;
4554 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4555 return;
4556
4557 llvm::Function *F = cast<llvm::Function>(GV);
4558 F->addFnAttr("stack-probe-size",
4559 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4560}
4561
4562void WindowsARMTargetCodeGenInfo::SetTargetAttributes(
4563 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4564 ARMTargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
4565 addStackProbeSizeTargetAttribute(D, GV, CGM);
4566}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004567}
4568
Chris Lattner22326a12010-07-29 02:31:05 +00004569void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004570 if (!getCXXABI().classifyReturnType(FI))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004571 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004572
Tim Northoverbc784d12015-02-24 17:22:40 +00004573 for (auto &I : FI.arguments())
4574 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004575
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004576 // Always honor user-specified calling convention.
4577 if (FI.getCallingConvention() != llvm::CallingConv::C)
4578 return;
4579
John McCall882987f2013-02-28 19:01:20 +00004580 llvm::CallingConv::ID cc = getRuntimeCC();
4581 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004582 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004583}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004584
John McCall882987f2013-02-28 19:01:20 +00004585/// Return the default calling convention that LLVM will use.
4586llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4587 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004588 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004589 return llvm::CallingConv::ARM_AAPCS_VFP;
4590 else if (isEABI())
4591 return llvm::CallingConv::ARM_AAPCS;
4592 else
4593 return llvm::CallingConv::ARM_APCS;
4594}
4595
4596/// Return the calling convention that our ABI would like us to use
4597/// as the C calling convention.
4598llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004599 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004600 case APCS: return llvm::CallingConv::ARM_APCS;
4601 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4602 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004603 }
John McCall882987f2013-02-28 19:01:20 +00004604 llvm_unreachable("bad ABI kind");
4605}
4606
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004607void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004608 assert(getRuntimeCC() == llvm::CallingConv::C);
4609
4610 // Don't muddy up the IR with a ton of explicit annotations if
4611 // they'd just match what LLVM will infer from the triple.
4612 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4613 if (abiCC != getLLVMDefaultCC())
4614 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004615
4616 BuiltinCC = (getABIKind() == APCS ?
4617 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004618}
4619
Tim Northoverbc784d12015-02-24 17:22:40 +00004620ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4621 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004622 // 6.1.2.1 The following argument types are VFP CPRCs:
4623 // A single-precision floating-point type (including promoted
4624 // half-precision types); A double-precision floating-point type;
4625 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4626 // with a Base Type of a single- or double-precision floating-point type,
4627 // 64-bit containerized vectors or 128-bit containerized vectors with one
4628 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004629 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004630
Reid Klecknerb1be6832014-11-15 01:41:41 +00004631 Ty = useFirstFieldIfTransparentUnion(Ty);
4632
Manman Renfef9e312012-10-16 19:18:39 +00004633 // Handle illegal vector types here.
4634 if (isIllegalVectorType(Ty)) {
4635 uint64_t Size = getContext().getTypeSize(Ty);
4636 if (Size <= 32) {
4637 llvm::Type *ResType =
4638 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004639 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004640 }
4641 if (Size == 64) {
4642 llvm::Type *ResType = llvm::VectorType::get(
4643 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004644 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004645 }
4646 if (Size == 128) {
4647 llvm::Type *ResType = llvm::VectorType::get(
4648 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004649 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004650 }
4651 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4652 }
4653
John McCalla1dee5302010-08-22 10:59:02 +00004654 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004655 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004656 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004657 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004658 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004659
Tim Northover5a1558e2014-11-07 22:30:50 +00004660 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4661 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004662 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004663
Oliver Stannard405bded2014-02-11 09:25:50 +00004664 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northover1060eae2013-06-21 22:49:34 +00004665 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004666 }
Tim Northover1060eae2013-06-21 22:49:34 +00004667
Daniel Dunbar09d33622009-09-14 21:54:03 +00004668 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004669 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004670 return ABIArgInfo::getIgnore();
4671
Tim Northover5a1558e2014-11-07 22:30:50 +00004672 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004673 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4674 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004675 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004676 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004677 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004678 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004679 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004680 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004681 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004682 }
4683
Manman Ren6c30e132012-08-13 21:23:55 +00004684 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004685 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4686 // most 8-byte. We realign the indirect argument if type alignment is bigger
4687 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004688 uint64_t ABIAlign = 4;
4689 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4690 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004691 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004692 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004693
Manman Ren8cd99812012-11-06 04:58:01 +00004694 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northoverd157e192015-03-09 21:40:42 +00004695 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004696 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004697 }
4698
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004699 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004700 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004701 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004702 // FIXME: Try to match the types of the arguments more accurately where
4703 // we can.
4704 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004705 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4706 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004707 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004708 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4709 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004710 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004711
Tim Northover5a1558e2014-11-07 22:30:50 +00004712 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004713}
4714
Chris Lattner458b2aa2010-07-29 02:16:43 +00004715static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004716 llvm::LLVMContext &VMContext) {
4717 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4718 // is called integer-like if its size is less than or equal to one word, and
4719 // the offset of each of its addressable sub-fields is zero.
4720
4721 uint64_t Size = Context.getTypeSize(Ty);
4722
4723 // Check that the type fits in a word.
4724 if (Size > 32)
4725 return false;
4726
4727 // FIXME: Handle vector types!
4728 if (Ty->isVectorType())
4729 return false;
4730
Daniel Dunbard53bac72009-09-14 02:20:34 +00004731 // Float types are never treated as "integer like".
4732 if (Ty->isRealFloatingType())
4733 return false;
4734
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004735 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004736 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004737 return true;
4738
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004739 // Small complex integer types are "integer like".
4740 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4741 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004742
4743 // Single element and zero sized arrays should be allowed, by the definition
4744 // above, but they are not.
4745
4746 // Otherwise, it must be a record type.
4747 const RecordType *RT = Ty->getAs<RecordType>();
4748 if (!RT) return false;
4749
4750 // Ignore records with flexible arrays.
4751 const RecordDecl *RD = RT->getDecl();
4752 if (RD->hasFlexibleArrayMember())
4753 return false;
4754
4755 // Check that all sub-fields are at offset 0, and are themselves "integer
4756 // like".
4757 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4758
4759 bool HadField = false;
4760 unsigned idx = 0;
4761 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4762 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004763 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004764
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004765 // Bit-fields are not addressable, we only need to verify they are "integer
4766 // like". We still have to disallow a subsequent non-bitfield, for example:
4767 // struct { int : 0; int x }
4768 // is non-integer like according to gcc.
4769 if (FD->isBitField()) {
4770 if (!RD->isUnion())
4771 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004772
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004773 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4774 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004775
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004776 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004777 }
4778
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004779 // Check if this field is at offset 0.
4780 if (Layout.getFieldOffset(idx) != 0)
4781 return false;
4782
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004783 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4784 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004785
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004786 // Only allow at most one field in a structure. This doesn't match the
4787 // wording above, but follows gcc in situations with a field following an
4788 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004789 if (!RD->isUnion()) {
4790 if (HadField)
4791 return false;
4792
4793 HadField = true;
4794 }
4795 }
4796
4797 return true;
4798}
4799
Oliver Stannard405bded2014-02-11 09:25:50 +00004800ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4801 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004802 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004803
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004804 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004805 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004806
Daniel Dunbar19964db2010-09-23 01:54:32 +00004807 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004808 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbar19964db2010-09-23 01:54:32 +00004809 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004810 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004811
John McCalla1dee5302010-08-22 10:59:02 +00004812 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004813 // Treat an enum type as its underlying type.
4814 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4815 RetTy = EnumTy->getDecl()->getIntegerType();
4816
Tim Northover5a1558e2014-11-07 22:30:50 +00004817 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4818 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004819 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004820
4821 // Are we following APCS?
4822 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004823 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004824 return ABIArgInfo::getIgnore();
4825
Daniel Dunbareedf1512010-02-01 23:31:19 +00004826 // Complex types are all returned as packed integers.
4827 //
4828 // FIXME: Consider using 2 x vector types if the back end handles them
4829 // correctly.
4830 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004831 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4832 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004833
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004834 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004835 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004836 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004837 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004838 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004839 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004840 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004841 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4842 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004843 }
4844
4845 // Otherwise return in memory.
4846 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004847 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004848
4849 // Otherwise this is an AAPCS variant.
4850
Chris Lattner458b2aa2010-07-29 02:16:43 +00004851 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004852 return ABIArgInfo::getIgnore();
4853
Bob Wilson1d9269a2011-11-02 04:51:36 +00004854 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004855 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004856 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004857 uint64_t Members;
4858 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004859 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004860 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004861 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004862 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004863 }
4864
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004865 // Aggregates <= 4 bytes are returned in r0; other aggregates
4866 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004867 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004868 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004869 if (getDataLayout().isBigEndian())
4870 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004871 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004872
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004873 // Return in the smallest viable integer type.
4874 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004875 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004876 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004877 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4878 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004879 }
4880
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004881 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004882}
4883
Manman Renfef9e312012-10-16 19:18:39 +00004884/// isIllegalVector - check whether Ty is an illegal vector type.
4885bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4886 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4887 // Check whether VT is legal.
4888 unsigned NumElements = VT->getNumElements();
4889 uint64_t Size = getContext().getTypeSize(VT);
4890 // NumElements should be power of 2.
4891 if ((NumElements & (NumElements - 1)) != 0)
4892 return true;
4893 // Size should be greater than 32 bits.
4894 return Size <= 32;
4895 }
4896 return false;
4897}
4898
Reid Klecknere9f6a712014-10-31 17:10:41 +00004899bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4900 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4901 // double, or 64-bit or 128-bit vectors.
4902 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4903 if (BT->getKind() == BuiltinType::Float ||
4904 BT->getKind() == BuiltinType::Double ||
4905 BT->getKind() == BuiltinType::LongDouble)
4906 return true;
4907 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4908 unsigned VecSize = getContext().getTypeSize(VT);
4909 if (VecSize == 64 || VecSize == 128)
4910 return true;
4911 }
4912 return false;
4913}
4914
4915bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4916 uint64_t Members) const {
4917 return Members <= 4;
4918}
4919
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004920llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004921 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004922 llvm::Type *BP = CGF.Int8PtrTy;
4923 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004924
4925 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004926 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004927 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004928
Tim Northover1711cc92013-06-21 23:05:33 +00004929 if (isEmptyRecord(getContext(), Ty, true)) {
4930 // These are ignored for parameter passing purposes.
4931 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4932 return Builder.CreateBitCast(Addr, PTy);
4933 }
4934
Manman Rencca54d02012-10-16 19:01:37 +00004935 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004936 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004937 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004938
4939 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4940 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004941 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4942 getABIKind() == ARMABIInfo::AAPCS)
4943 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4944 else
4945 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004946 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4947 if (isIllegalVectorType(Ty) && Size > 16) {
4948 IsIndirect = true;
4949 Size = 4;
4950 TyAlign = 4;
4951 }
Manman Rencca54d02012-10-16 19:01:37 +00004952
4953 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004954 if (TyAlign > 4) {
4955 assert((TyAlign & (TyAlign - 1)) == 0 &&
4956 "Alignment is not power of 2!");
4957 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4958 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4959 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004960 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004961 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004962
4963 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004964 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004965 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004966 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004967 "ap.next");
4968 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4969
Manman Renfef9e312012-10-16 19:18:39 +00004970 if (IsIndirect)
4971 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004972 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004973 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4974 // may not be correctly aligned for the vector type. We create an aligned
4975 // temporary space and copy the content over from ap.cur to the temporary
4976 // space. This is necessary if the natural alignment of the type is greater
4977 // than the ABI alignment.
4978 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4979 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4980 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4981 "var.align");
4982 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4983 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4984 Builder.CreateMemCpy(Dst, Src,
4985 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4986 TyAlign, false);
4987 Addr = AlignedTemp; //The content is in aligned location.
4988 }
4989 llvm::Type *PTy =
4990 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4991 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4992
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004993 return AddrTyped;
4994}
4995
Chris Lattner0cf24192010-06-28 20:05:43 +00004996//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004997// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004998//===----------------------------------------------------------------------===//
4999
5000namespace {
5001
Justin Holewinski83e96682012-05-24 17:43:12 +00005002class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005003public:
Justin Holewinski36837432013-03-30 14:38:24 +00005004 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005005
5006 ABIArgInfo classifyReturnType(QualType RetTy) const;
5007 ABIArgInfo classifyArgumentType(QualType Ty) const;
5008
Craig Topper4f12f102014-03-12 06:41:41 +00005009 void computeInfo(CGFunctionInfo &FI) const override;
5010 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5011 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005012};
5013
Justin Holewinski83e96682012-05-24 17:43:12 +00005014class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005015public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005016 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5017 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005018
5019 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5020 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005021private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005022 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5023 // resulting MDNode to the nvvm.annotations MDNode.
5024 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005025};
5026
Justin Holewinski83e96682012-05-24 17:43:12 +00005027ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005028 if (RetTy->isVoidType())
5029 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005030
5031 // note: this is different from default ABI
5032 if (!RetTy->isScalarType())
5033 return ABIArgInfo::getDirect();
5034
5035 // Treat an enum type as its underlying type.
5036 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5037 RetTy = EnumTy->getDecl()->getIntegerType();
5038
5039 return (RetTy->isPromotableIntegerType() ?
5040 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005041}
5042
Justin Holewinski83e96682012-05-24 17:43:12 +00005043ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005044 // Treat an enum type as its underlying type.
5045 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5046 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005047
Eli Bendersky95338a02014-10-29 13:43:21 +00005048 // Return aggregates type as indirect by value
5049 if (isAggregateTypeForABI(Ty))
5050 return ABIArgInfo::getIndirect(0, /* byval */ true);
5051
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005052 return (Ty->isPromotableIntegerType() ?
5053 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005054}
5055
Justin Holewinski83e96682012-05-24 17:43:12 +00005056void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005057 if (!getCXXABI().classifyReturnType(FI))
5058 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005059 for (auto &I : FI.arguments())
5060 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005061
5062 // Always honor user-specified calling convention.
5063 if (FI.getCallingConvention() != llvm::CallingConv::C)
5064 return;
5065
John McCall882987f2013-02-28 19:01:20 +00005066 FI.setEffectiveCallingConvention(getRuntimeCC());
5067}
5068
Justin Holewinski83e96682012-05-24 17:43:12 +00005069llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5070 CodeGenFunction &CFG) const {
5071 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005072}
5073
Justin Holewinski83e96682012-05-24 17:43:12 +00005074void NVPTXTargetCodeGenInfo::
5075SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5076 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005077 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5078 if (!FD) return;
5079
5080 llvm::Function *F = cast<llvm::Function>(GV);
5081
5082 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005083 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005084 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005085 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005086 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005087 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005088 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5089 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005090 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005091 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005092 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005093 }
Justin Holewinski38031972011-10-05 17:58:44 +00005094
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005095 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005096 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005097 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005098 // __global__ functions cannot be called from the device, we do not
5099 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005100 if (FD->hasAttr<CUDAGlobalAttr>()) {
5101 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5102 addNVVMMetadata(F, "kernel", 1);
5103 }
Artem Belevich7093e402015-04-21 22:55:54 +00005104 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005105 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005106 llvm::APSInt MaxThreads(32);
5107 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5108 if (MaxThreads > 0)
5109 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5110
5111 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5112 // not specified in __launch_bounds__ or if the user specified a 0 value,
5113 // we don't have to add a PTX directive.
5114 if (Attr->getMinBlocks()) {
5115 llvm::APSInt MinBlocks(32);
5116 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5117 if (MinBlocks > 0)
5118 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5119 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005120 }
5121 }
Justin Holewinski38031972011-10-05 17:58:44 +00005122 }
5123}
5124
Eli Benderskye06a2c42014-04-15 16:57:05 +00005125void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5126 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005127 llvm::Module *M = F->getParent();
5128 llvm::LLVMContext &Ctx = M->getContext();
5129
5130 // Get "nvvm.annotations" metadata node
5131 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5132
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005133 llvm::Metadata *MDVals[] = {
5134 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5135 llvm::ConstantAsMetadata::get(
5136 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005137 // Append metadata to nvvm.annotations
5138 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5139}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005140}
5141
5142//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005143// SystemZ ABI Implementation
5144//===----------------------------------------------------------------------===//
5145
5146namespace {
5147
5148class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005149 bool HasVector;
5150
Ulrich Weigand47445072013-05-06 16:26:41 +00005151public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005152 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5153 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005154
5155 bool isPromotableIntegerType(QualType Ty) const;
5156 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005157 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005158 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005159 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005160
5161 ABIArgInfo classifyReturnType(QualType RetTy) const;
5162 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5163
Craig Topper4f12f102014-03-12 06:41:41 +00005164 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005165 if (!getCXXABI().classifyReturnType(FI))
5166 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005167 for (auto &I : FI.arguments())
5168 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005169 }
5170
Craig Topper4f12f102014-03-12 06:41:41 +00005171 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5172 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005173};
5174
5175class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5176public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005177 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5178 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005179};
5180
5181}
5182
5183bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5184 // Treat an enum type as its underlying type.
5185 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5186 Ty = EnumTy->getDecl()->getIntegerType();
5187
5188 // Promotable integer types are required to be promoted by the ABI.
5189 if (Ty->isPromotableIntegerType())
5190 return true;
5191
5192 // 32-bit values must also be promoted.
5193 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5194 switch (BT->getKind()) {
5195 case BuiltinType::Int:
5196 case BuiltinType::UInt:
5197 return true;
5198 default:
5199 return false;
5200 }
5201 return false;
5202}
5203
5204bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005205 return (Ty->isAnyComplexType() ||
5206 Ty->isVectorType() ||
5207 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005208}
5209
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005210bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5211 return (HasVector &&
5212 Ty->isVectorType() &&
5213 getContext().getTypeSize(Ty) <= 128);
5214}
5215
Ulrich Weigand47445072013-05-06 16:26:41 +00005216bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5217 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5218 switch (BT->getKind()) {
5219 case BuiltinType::Float:
5220 case BuiltinType::Double:
5221 return true;
5222 default:
5223 return false;
5224 }
5225
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005226 return false;
5227}
5228
5229QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005230 if (const RecordType *RT = Ty->getAsStructureType()) {
5231 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005232 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005233
5234 // If this is a C++ record, check the bases first.
5235 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005236 for (const auto &I : CXXRD->bases()) {
5237 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005238
5239 // Empty bases don't affect things either way.
5240 if (isEmptyRecord(getContext(), Base, true))
5241 continue;
5242
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005243 if (!Found.isNull())
5244 return Ty;
5245 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005246 }
5247
5248 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005249 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005250 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005251 // Unlike isSingleElementStruct(), empty structure and array fields
5252 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005253 if (getContext().getLangOpts().CPlusPlus &&
5254 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5255 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005256
5257 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005258 // Nested structures still do though.
5259 if (!Found.isNull())
5260 return Ty;
5261 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005262 }
5263
5264 // Unlike isSingleElementStruct(), trailing padding is allowed.
5265 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005266 if (!Found.isNull())
5267 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005268 }
5269
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005270 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005271}
5272
5273llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5274 CodeGenFunction &CGF) const {
5275 // Assume that va_list type is correct; should be pointer to LLVM type:
5276 // struct {
5277 // i64 __gpr;
5278 // i64 __fpr;
5279 // i8 *__overflow_arg_area;
5280 // i8 *__reg_save_area;
5281 // };
5282
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005283 // Every non-vector argument occupies 8 bytes and is passed by preference
5284 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5285 // always passed on the stack.
Ulrich Weigand47445072013-05-06 16:26:41 +00005286 Ty = CGF.getContext().getCanonicalType(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005287 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
5288 llvm::Type *APTy = llvm::PointerType::getUnqual(ArgTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005289 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005290 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005291 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005292 bool IsVector = false;
Ulrich Weigand47445072013-05-06 16:26:41 +00005293 unsigned UnpaddedBitSize;
5294 if (IsIndirect) {
5295 APTy = llvm::PointerType::getUnqual(APTy);
5296 UnpaddedBitSize = 64;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005297 } else {
5298 if (AI.getCoerceToType())
5299 ArgTy = AI.getCoerceToType();
5300 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005301 IsVector = ArgTy->isVectorTy();
Ulrich Weigand47445072013-05-06 16:26:41 +00005302 UnpaddedBitSize = getContext().getTypeSize(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005303 }
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005304 unsigned PaddedBitSize = (IsVector && UnpaddedBitSize > 64) ? 128 : 64;
Ulrich Weigand47445072013-05-06 16:26:41 +00005305 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5306
5307 unsigned PaddedSize = PaddedBitSize / 8;
5308 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5309
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005310 llvm::Type *IndexTy = CGF.Int64Ty;
5311 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5312
5313 if (IsVector) {
5314 // Work out the address of a vector argument on the stack.
5315 // Vector arguments are always passed in the high bits of a
5316 // single (8 byte) or double (16 byte) stack slot.
5317 llvm::Value *OverflowArgAreaPtr =
5318 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 2,
5319 "overflow_arg_area_ptr");
5320 llvm::Value *OverflowArgArea =
5321 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5322 llvm::Value *MemAddr =
5323 CGF.Builder.CreateBitCast(OverflowArgArea, APTy, "mem_addr");
5324
5325 // Update overflow_arg_area_ptr pointer
5326 llvm::Value *NewOverflowArgArea =
5327 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5328 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5329
5330 return MemAddr;
5331 }
5332
Ulrich Weigand47445072013-05-06 16:26:41 +00005333 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5334 if (InFPRs) {
5335 MaxRegs = 4; // Maximum of 4 FPR arguments
5336 RegCountField = 1; // __fpr
5337 RegSaveIndex = 16; // save offset for f0
5338 RegPadding = 0; // floats are passed in the high bits of an FPR
5339 } else {
5340 MaxRegs = 5; // Maximum of 5 GPR arguments
5341 RegCountField = 0; // __gpr
5342 RegSaveIndex = 2; // save offset for r2
5343 RegPadding = Padding; // values are passed in the low bits of a GPR
5344 }
5345
David Blaikie2e804282015-04-05 22:47:07 +00005346 llvm::Value *RegCountPtr = CGF.Builder.CreateStructGEP(
5347 nullptr, VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005348 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005349 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5350 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005351 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005352
5353 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5354 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5355 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5356 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5357
5358 // Emit code to load the value if it was passed in registers.
5359 CGF.EmitBlock(InRegBlock);
5360
5361 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005362 llvm::Value *ScaledRegCount =
5363 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5364 llvm::Value *RegBase =
5365 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5366 llvm::Value *RegOffset =
5367 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5368 llvm::Value *RegSaveAreaPtr =
David Blaikie2e804282015-04-05 22:47:07 +00005369 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005370 llvm::Value *RegSaveArea =
5371 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5372 llvm::Value *RawRegAddr =
5373 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5374 llvm::Value *RegAddr =
5375 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5376
5377 // Update the register count
5378 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5379 llvm::Value *NewRegCount =
5380 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5381 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5382 CGF.EmitBranch(ContBlock);
5383
5384 // Emit code to load the value if it was passed in memory.
5385 CGF.EmitBlock(InMemBlock);
5386
5387 // Work out the address of a stack argument.
David Blaikie2e804282015-04-05 22:47:07 +00005388 llvm::Value *OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5389 nullptr, VAListAddr, 2, "overflow_arg_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005390 llvm::Value *OverflowArgArea =
5391 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5392 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5393 llvm::Value *RawMemAddr =
5394 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5395 llvm::Value *MemAddr =
5396 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5397
5398 // Update overflow_arg_area_ptr pointer
5399 llvm::Value *NewOverflowArgArea =
5400 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5401 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5402 CGF.EmitBranch(ContBlock);
5403
5404 // Return the appropriate result.
5405 CGF.EmitBlock(ContBlock);
5406 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5407 ResAddr->addIncoming(RegAddr, InRegBlock);
5408 ResAddr->addIncoming(MemAddr, InMemBlock);
5409
5410 if (IsIndirect)
5411 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5412
5413 return ResAddr;
5414}
5415
Ulrich Weigand47445072013-05-06 16:26:41 +00005416ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5417 if (RetTy->isVoidType())
5418 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005419 if (isVectorArgumentType(RetTy))
5420 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005421 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5422 return ABIArgInfo::getIndirect(0);
5423 return (isPromotableIntegerType(RetTy) ?
5424 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5425}
5426
5427ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5428 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005429 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005430 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5431
5432 // Integers and enums are extended to full register width.
5433 if (isPromotableIntegerType(Ty))
5434 return ABIArgInfo::getExtend();
5435
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005436 // Handle vector types and vector-like structure types. Note that
5437 // as opposed to float-like structure types, we do not allow any
5438 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005439 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005440 QualType SingleElementTy = GetSingleElementType(Ty);
5441 if (isVectorArgumentType(SingleElementTy) &&
5442 getContext().getTypeSize(SingleElementTy) == Size)
5443 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5444
5445 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005446 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005447 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005448
5449 // Handle small structures.
5450 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5451 // Structures with flexible arrays have variable length, so really
5452 // fail the size test above.
5453 const RecordDecl *RD = RT->getDecl();
5454 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005455 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005456
5457 // The structure is passed as an unextended integer, a float, or a double.
5458 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005459 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005460 assert(Size == 32 || Size == 64);
5461 if (Size == 32)
5462 PassTy = llvm::Type::getFloatTy(getVMContext());
5463 else
5464 PassTy = llvm::Type::getDoubleTy(getVMContext());
5465 } else
5466 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5467 return ABIArgInfo::getDirect(PassTy);
5468 }
5469
5470 // Non-structure compounds are passed indirectly.
5471 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005472 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005473
Craig Topper8a13c412014-05-21 05:09:00 +00005474 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005475}
5476
5477//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005478// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005479//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005480
5481namespace {
5482
5483class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5484public:
Chris Lattner2b037972010-07-29 02:01:43 +00005485 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5486 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005487 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005488 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005489};
5490
5491}
5492
5493void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5494 llvm::GlobalValue *GV,
5495 CodeGen::CodeGenModule &M) const {
5496 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5497 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5498 // Handle 'interrupt' attribute:
5499 llvm::Function *F = cast<llvm::Function>(GV);
5500
5501 // Step 1: Set ISR calling convention.
5502 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5503
5504 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005505 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005506
5507 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005508 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005509 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5510 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005511 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005512 }
5513}
5514
Chris Lattner0cf24192010-06-28 20:05:43 +00005515//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005516// MIPS ABI Implementation. This works for both little-endian and
5517// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005518//===----------------------------------------------------------------------===//
5519
John McCall943fae92010-05-27 06:19:26 +00005520namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005521class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005522 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005523 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5524 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005525 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005526 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005527 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005528 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005529public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005530 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005531 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005532 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005533
5534 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005535 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005536 void computeInfo(CGFunctionInfo &FI) const override;
5537 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5538 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005539};
5540
John McCall943fae92010-05-27 06:19:26 +00005541class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005542 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005543public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005544 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5545 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005546 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005547
Craig Topper4f12f102014-03-12 06:41:41 +00005548 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005549 return 29;
5550 }
5551
Reed Kotler373feca2013-01-16 17:10:28 +00005552 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005553 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005554 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5555 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005556 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005557 if (FD->hasAttr<Mips16Attr>()) {
5558 Fn->addFnAttr("mips16");
5559 }
5560 else if (FD->hasAttr<NoMips16Attr>()) {
5561 Fn->addFnAttr("nomips16");
5562 }
Reed Kotler373feca2013-01-16 17:10:28 +00005563 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005564
John McCall943fae92010-05-27 06:19:26 +00005565 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005566 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005567
Craig Topper4f12f102014-03-12 06:41:41 +00005568 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005569 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005570 }
John McCall943fae92010-05-27 06:19:26 +00005571};
5572}
5573
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005574void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005575 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005576 llvm::IntegerType *IntTy =
5577 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005578
5579 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5580 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5581 ArgList.push_back(IntTy);
5582
5583 // If necessary, add one more integer type to ArgList.
5584 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5585
5586 if (R)
5587 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005588}
5589
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005590// In N32/64, an aligned double precision floating point field is passed in
5591// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005592llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005593 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5594
5595 if (IsO32) {
5596 CoerceToIntArgs(TySize, ArgList);
5597 return llvm::StructType::get(getVMContext(), ArgList);
5598 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005599
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005600 if (Ty->isComplexType())
5601 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005602
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005603 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005604
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005605 // Unions/vectors are passed in integer registers.
5606 if (!RT || !RT->isStructureOrClassType()) {
5607 CoerceToIntArgs(TySize, ArgList);
5608 return llvm::StructType::get(getVMContext(), ArgList);
5609 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005610
5611 const RecordDecl *RD = RT->getDecl();
5612 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005613 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005614
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005615 uint64_t LastOffset = 0;
5616 unsigned idx = 0;
5617 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5618
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005619 // Iterate over fields in the struct/class and check if there are any aligned
5620 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005621 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5622 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005623 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005624 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5625
5626 if (!BT || BT->getKind() != BuiltinType::Double)
5627 continue;
5628
5629 uint64_t Offset = Layout.getFieldOffset(idx);
5630 if (Offset % 64) // Ignore doubles that are not aligned.
5631 continue;
5632
5633 // Add ((Offset - LastOffset) / 64) args of type i64.
5634 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5635 ArgList.push_back(I64);
5636
5637 // Add double type.
5638 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5639 LastOffset = Offset + 64;
5640 }
5641
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005642 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5643 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005644
5645 return llvm::StructType::get(getVMContext(), ArgList);
5646}
5647
Akira Hatanakaddd66342013-10-29 18:41:15 +00005648llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5649 uint64_t Offset) const {
5650 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005651 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005652
Akira Hatanakaddd66342013-10-29 18:41:15 +00005653 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005654}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005655
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005656ABIArgInfo
5657MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005658 Ty = useFirstFieldIfTransparentUnion(Ty);
5659
Akira Hatanaka1632af62012-01-09 19:31:25 +00005660 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005661 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005662 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005663
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005664 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5665 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005666 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5667 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005668
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005669 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005670 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005671 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005672 return ABIArgInfo::getIgnore();
5673
Mark Lacey3825e832013-10-06 01:33:34 +00005674 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005675 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005676 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005677 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005678
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005679 // If we have reached here, aggregates are passed directly by coercing to
5680 // another structure type. Padding is inserted if the offset of the
5681 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005682 ABIArgInfo ArgInfo =
5683 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5684 getPaddingType(OrigOffset, CurrOffset));
5685 ArgInfo.setInReg(true);
5686 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005687 }
5688
5689 // Treat an enum type as its underlying type.
5690 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5691 Ty = EnumTy->getDecl()->getIntegerType();
5692
Daniel Sanders5b445b32014-10-24 14:42:42 +00005693 // All integral types are promoted to the GPR width.
5694 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005695 return ABIArgInfo::getExtend();
5696
Akira Hatanakaddd66342013-10-29 18:41:15 +00005697 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005698 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005699}
5700
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005701llvm::Type*
5702MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005703 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005704 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005705
Akira Hatanakab6f74432012-02-09 18:49:26 +00005706 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005707 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005708 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5709 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005710
Akira Hatanakab6f74432012-02-09 18:49:26 +00005711 // N32/64 returns struct/classes in floating point registers if the
5712 // following conditions are met:
5713 // 1. The size of the struct/class is no larger than 128-bit.
5714 // 2. The struct/class has one or two fields all of which are floating
5715 // point types.
5716 // 3. The offset of the first field is zero (this follows what gcc does).
5717 //
5718 // Any other composite results are returned in integer registers.
5719 //
5720 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5721 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5722 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005723 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005724
Akira Hatanakab6f74432012-02-09 18:49:26 +00005725 if (!BT || !BT->isFloatingPoint())
5726 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005727
David Blaikie2d7c57e2012-04-30 02:36:29 +00005728 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005729 }
5730
5731 if (b == e)
5732 return llvm::StructType::get(getVMContext(), RTList,
5733 RD->hasAttr<PackedAttr>());
5734
5735 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005736 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005737 }
5738
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005739 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005740 return llvm::StructType::get(getVMContext(), RTList);
5741}
5742
Akira Hatanakab579fe52011-06-02 00:09:17 +00005743ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005744 uint64_t Size = getContext().getTypeSize(RetTy);
5745
Daniel Sandersed39f582014-09-04 13:28:14 +00005746 if (RetTy->isVoidType())
5747 return ABIArgInfo::getIgnore();
5748
5749 // O32 doesn't treat zero-sized structs differently from other structs.
5750 // However, N32/N64 ignores zero sized return values.
5751 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005752 return ABIArgInfo::getIgnore();
5753
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005754 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005755 if (Size <= 128) {
5756 if (RetTy->isAnyComplexType())
5757 return ABIArgInfo::getDirect();
5758
Daniel Sanderse5018b62014-09-04 15:05:39 +00005759 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005760 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005761 if (!IsO32 ||
5762 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5763 ABIArgInfo ArgInfo =
5764 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5765 ArgInfo.setInReg(true);
5766 return ArgInfo;
5767 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005768 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005769
5770 return ABIArgInfo::getIndirect(0);
5771 }
5772
5773 // Treat an enum type as its underlying type.
5774 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5775 RetTy = EnumTy->getDecl()->getIntegerType();
5776
5777 return (RetTy->isPromotableIntegerType() ?
5778 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5779}
5780
5781void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005782 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005783 if (!getCXXABI().classifyReturnType(FI))
5784 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005785
5786 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005787 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005788
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005789 for (auto &I : FI.arguments())
5790 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005791}
5792
5793llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5794 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005795 llvm::Type *BP = CGF.Int8PtrTy;
5796 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005797
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005798 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5799 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005800 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005801 unsigned PtrWidth = getTarget().getPointerWidth(0);
5802 if ((Ty->isIntegerType() &&
5803 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5804 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005805 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5806 Ty->isSignedIntegerType());
5807 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005808
5809 CGBuilderTy &Builder = CGF.Builder;
5810 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5811 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005812 int64_t TypeAlign =
5813 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005814 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5815 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005816 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5817
5818 if (TypeAlign > MinABIStackAlignInBytes) {
5819 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5820 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5821 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5822 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5823 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5824 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5825 }
5826 else
5827 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5828
5829 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5830 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005831 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5832 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005833 llvm::Value *NextAddr =
5834 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5835 "ap.next");
5836 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5837
5838 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005839}
5840
John McCall943fae92010-05-27 06:19:26 +00005841bool
5842MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5843 llvm::Value *Address) const {
5844 // This information comes from gcc's implementation, which seems to
5845 // as canonical as it gets.
5846
John McCall943fae92010-05-27 06:19:26 +00005847 // Everything on MIPS is 4 bytes. Double-precision FP registers
5848 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005849 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005850
5851 // 0-31 are the general purpose registers, $0 - $31.
5852 // 32-63 are the floating-point registers, $f0 - $f31.
5853 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5854 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005855 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005856
5857 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5858 // They are one bit wide and ignored here.
5859
5860 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5861 // (coprocessor 1 is the FP unit)
5862 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5863 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5864 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005865 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005866 return false;
5867}
5868
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005869//===----------------------------------------------------------------------===//
5870// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5871// Currently subclassed only to implement custom OpenCL C function attribute
5872// handling.
5873//===----------------------------------------------------------------------===//
5874
5875namespace {
5876
5877class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5878public:
5879 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5880 : DefaultTargetCodeGenInfo(CGT) {}
5881
Craig Topper4f12f102014-03-12 06:41:41 +00005882 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5883 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005884};
5885
5886void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5887 llvm::GlobalValue *GV,
5888 CodeGen::CodeGenModule &M) const {
5889 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5890 if (!FD) return;
5891
5892 llvm::Function *F = cast<llvm::Function>(GV);
5893
David Blaikiebbafb8a2012-03-11 07:00:24 +00005894 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005895 if (FD->hasAttr<OpenCLKernelAttr>()) {
5896 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005897 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005898 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5899 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005900 // Convert the reqd_work_group_size() attributes to metadata.
5901 llvm::LLVMContext &Context = F->getContext();
5902 llvm::NamedMDNode *OpenCLMetadata =
5903 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5904
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005905 SmallVector<llvm::Metadata *, 5> Operands;
5906 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005907
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005908 Operands.push_back(
5909 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5910 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5911 Operands.push_back(
5912 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5913 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5914 Operands.push_back(
5915 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5916 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005917
5918 // Add a boolean constant operand for "required" (true) or "hint" (false)
5919 // for implementing the work_group_size_hint attr later. Currently
5920 // always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005921 Operands.push_back(
5922 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005923 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5924 }
5925 }
5926 }
5927}
5928
5929}
John McCall943fae92010-05-27 06:19:26 +00005930
Tony Linthicum76329bf2011-12-12 21:14:55 +00005931//===----------------------------------------------------------------------===//
5932// Hexagon ABI Implementation
5933//===----------------------------------------------------------------------===//
5934
5935namespace {
5936
5937class HexagonABIInfo : public ABIInfo {
5938
5939
5940public:
5941 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5942
5943private:
5944
5945 ABIArgInfo classifyReturnType(QualType RetTy) const;
5946 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5947
Craig Topper4f12f102014-03-12 06:41:41 +00005948 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005949
Craig Topper4f12f102014-03-12 06:41:41 +00005950 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5951 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005952};
5953
5954class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5955public:
5956 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5957 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5958
Craig Topper4f12f102014-03-12 06:41:41 +00005959 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005960 return 29;
5961 }
5962};
5963
5964}
5965
5966void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005967 if (!getCXXABI().classifyReturnType(FI))
5968 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005969 for (auto &I : FI.arguments())
5970 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005971}
5972
5973ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5974 if (!isAggregateTypeForABI(Ty)) {
5975 // Treat an enum type as its underlying type.
5976 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5977 Ty = EnumTy->getDecl()->getIntegerType();
5978
5979 return (Ty->isPromotableIntegerType() ?
5980 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5981 }
5982
5983 // Ignore empty records.
5984 if (isEmptyRecord(getContext(), Ty, true))
5985 return ABIArgInfo::getIgnore();
5986
Mark Lacey3825e832013-10-06 01:33:34 +00005987 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005988 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005989
5990 uint64_t Size = getContext().getTypeSize(Ty);
5991 if (Size > 64)
5992 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5993 // Pass in the smallest viable integer type.
5994 else if (Size > 32)
5995 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5996 else if (Size > 16)
5997 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5998 else if (Size > 8)
5999 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6000 else
6001 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6002}
6003
6004ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6005 if (RetTy->isVoidType())
6006 return ABIArgInfo::getIgnore();
6007
6008 // Large vector types should be returned via memory.
6009 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6010 return ABIArgInfo::getIndirect(0);
6011
6012 if (!isAggregateTypeForABI(RetTy)) {
6013 // Treat an enum type as its underlying type.
6014 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6015 RetTy = EnumTy->getDecl()->getIntegerType();
6016
6017 return (RetTy->isPromotableIntegerType() ?
6018 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6019 }
6020
Tony Linthicum76329bf2011-12-12 21:14:55 +00006021 if (isEmptyRecord(getContext(), RetTy, true))
6022 return ABIArgInfo::getIgnore();
6023
6024 // Aggregates <= 8 bytes are returned in r0; other aggregates
6025 // are returned indirectly.
6026 uint64_t Size = getContext().getTypeSize(RetTy);
6027 if (Size <= 64) {
6028 // Return in the smallest viable integer type.
6029 if (Size <= 8)
6030 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6031 if (Size <= 16)
6032 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6033 if (Size <= 32)
6034 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6035 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6036 }
6037
6038 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6039}
6040
6041llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006042 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006043 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006044 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006045
6046 CGBuilderTy &Builder = CGF.Builder;
6047 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6048 "ap");
6049 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6050 llvm::Type *PTy =
6051 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6052 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6053
6054 uint64_t Offset =
6055 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6056 llvm::Value *NextAddr =
6057 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6058 "ap.next");
6059 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6060
6061 return AddrTyped;
6062}
6063
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006064//===----------------------------------------------------------------------===//
6065// AMDGPU ABI Implementation
6066//===----------------------------------------------------------------------===//
6067
6068namespace {
6069
6070class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6071public:
6072 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6073 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6074 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6075 CodeGen::CodeGenModule &M) const override;
6076};
6077
6078}
6079
6080void AMDGPUTargetCodeGenInfo::SetTargetAttributes(
6081 const Decl *D,
6082 llvm::GlobalValue *GV,
6083 CodeGen::CodeGenModule &M) const {
6084 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6085 if (!FD)
6086 return;
6087
6088 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6089 llvm::Function *F = cast<llvm::Function>(GV);
6090 uint32_t NumVGPR = Attr->getNumVGPR();
6091 if (NumVGPR != 0)
6092 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6093 }
6094
6095 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6096 llvm::Function *F = cast<llvm::Function>(GV);
6097 unsigned NumSGPR = Attr->getNumSGPR();
6098 if (NumSGPR != 0)
6099 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6100 }
6101}
6102
Tony Linthicum76329bf2011-12-12 21:14:55 +00006103
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006104//===----------------------------------------------------------------------===//
6105// SPARC v9 ABI Implementation.
6106// Based on the SPARC Compliance Definition version 2.4.1.
6107//
6108// Function arguments a mapped to a nominal "parameter array" and promoted to
6109// registers depending on their type. Each argument occupies 8 or 16 bytes in
6110// the array, structs larger than 16 bytes are passed indirectly.
6111//
6112// One case requires special care:
6113//
6114// struct mixed {
6115// int i;
6116// float f;
6117// };
6118//
6119// When a struct mixed is passed by value, it only occupies 8 bytes in the
6120// parameter array, but the int is passed in an integer register, and the float
6121// is passed in a floating point register. This is represented as two arguments
6122// with the LLVM IR inreg attribute:
6123//
6124// declare void f(i32 inreg %i, float inreg %f)
6125//
6126// The code generator will only allocate 4 bytes from the parameter array for
6127// the inreg arguments. All other arguments are allocated a multiple of 8
6128// bytes.
6129//
6130namespace {
6131class SparcV9ABIInfo : public ABIInfo {
6132public:
6133 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6134
6135private:
6136 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006137 void computeInfo(CGFunctionInfo &FI) const override;
6138 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6139 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006140
6141 // Coercion type builder for structs passed in registers. The coercion type
6142 // serves two purposes:
6143 //
6144 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6145 // in registers.
6146 // 2. Expose aligned floating point elements as first-level elements, so the
6147 // code generator knows to pass them in floating point registers.
6148 //
6149 // We also compute the InReg flag which indicates that the struct contains
6150 // aligned 32-bit floats.
6151 //
6152 struct CoerceBuilder {
6153 llvm::LLVMContext &Context;
6154 const llvm::DataLayout &DL;
6155 SmallVector<llvm::Type*, 8> Elems;
6156 uint64_t Size;
6157 bool InReg;
6158
6159 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6160 : Context(c), DL(dl), Size(0), InReg(false) {}
6161
6162 // Pad Elems with integers until Size is ToSize.
6163 void pad(uint64_t ToSize) {
6164 assert(ToSize >= Size && "Cannot remove elements");
6165 if (ToSize == Size)
6166 return;
6167
6168 // Finish the current 64-bit word.
6169 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6170 if (Aligned > Size && Aligned <= ToSize) {
6171 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6172 Size = Aligned;
6173 }
6174
6175 // Add whole 64-bit words.
6176 while (Size + 64 <= ToSize) {
6177 Elems.push_back(llvm::Type::getInt64Ty(Context));
6178 Size += 64;
6179 }
6180
6181 // Final in-word padding.
6182 if (Size < ToSize) {
6183 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6184 Size = ToSize;
6185 }
6186 }
6187
6188 // Add a floating point element at Offset.
6189 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6190 // Unaligned floats are treated as integers.
6191 if (Offset % Bits)
6192 return;
6193 // The InReg flag is only required if there are any floats < 64 bits.
6194 if (Bits < 64)
6195 InReg = true;
6196 pad(Offset);
6197 Elems.push_back(Ty);
6198 Size = Offset + Bits;
6199 }
6200
6201 // Add a struct type to the coercion type, starting at Offset (in bits).
6202 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6203 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6204 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6205 llvm::Type *ElemTy = StrTy->getElementType(i);
6206 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6207 switch (ElemTy->getTypeID()) {
6208 case llvm::Type::StructTyID:
6209 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6210 break;
6211 case llvm::Type::FloatTyID:
6212 addFloat(ElemOffset, ElemTy, 32);
6213 break;
6214 case llvm::Type::DoubleTyID:
6215 addFloat(ElemOffset, ElemTy, 64);
6216 break;
6217 case llvm::Type::FP128TyID:
6218 addFloat(ElemOffset, ElemTy, 128);
6219 break;
6220 case llvm::Type::PointerTyID:
6221 if (ElemOffset % 64 == 0) {
6222 pad(ElemOffset);
6223 Elems.push_back(ElemTy);
6224 Size += 64;
6225 }
6226 break;
6227 default:
6228 break;
6229 }
6230 }
6231 }
6232
6233 // Check if Ty is a usable substitute for the coercion type.
6234 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006235 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006236 }
6237
6238 // Get the coercion type as a literal struct type.
6239 llvm::Type *getType() const {
6240 if (Elems.size() == 1)
6241 return Elems.front();
6242 else
6243 return llvm::StructType::get(Context, Elems);
6244 }
6245 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006246};
6247} // end anonymous namespace
6248
6249ABIArgInfo
6250SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6251 if (Ty->isVoidType())
6252 return ABIArgInfo::getIgnore();
6253
6254 uint64_t Size = getContext().getTypeSize(Ty);
6255
6256 // Anything too big to fit in registers is passed with an explicit indirect
6257 // pointer / sret pointer.
6258 if (Size > SizeLimit)
6259 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6260
6261 // Treat an enum type as its underlying type.
6262 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6263 Ty = EnumTy->getDecl()->getIntegerType();
6264
6265 // Integer types smaller than a register are extended.
6266 if (Size < 64 && Ty->isIntegerType())
6267 return ABIArgInfo::getExtend();
6268
6269 // Other non-aggregates go in registers.
6270 if (!isAggregateTypeForABI(Ty))
6271 return ABIArgInfo::getDirect();
6272
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006273 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6274 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6275 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6276 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6277
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006278 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006279 // Build a coercion type from the LLVM struct type.
6280 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6281 if (!StrTy)
6282 return ABIArgInfo::getDirect();
6283
6284 CoerceBuilder CB(getVMContext(), getDataLayout());
6285 CB.addStruct(0, StrTy);
6286 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6287
6288 // Try to use the original type for coercion.
6289 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6290
6291 if (CB.InReg)
6292 return ABIArgInfo::getDirectInReg(CoerceTy);
6293 else
6294 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006295}
6296
6297llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6298 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006299 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6300 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6301 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6302 AI.setCoerceToType(ArgTy);
6303
6304 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6305 CGBuilderTy &Builder = CGF.Builder;
6306 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6307 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6308 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6309 llvm::Value *ArgAddr;
6310 unsigned Stride;
6311
6312 switch (AI.getKind()) {
6313 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006314 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006315 llvm_unreachable("Unsupported ABI kind for va_arg");
6316
6317 case ABIArgInfo::Extend:
6318 Stride = 8;
6319 ArgAddr = Builder
6320 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6321 "extend");
6322 break;
6323
6324 case ABIArgInfo::Direct:
6325 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6326 ArgAddr = Addr;
6327 break;
6328
6329 case ABIArgInfo::Indirect:
6330 Stride = 8;
6331 ArgAddr = Builder.CreateBitCast(Addr,
6332 llvm::PointerType::getUnqual(ArgPtrTy),
6333 "indirect");
6334 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6335 break;
6336
6337 case ABIArgInfo::Ignore:
6338 return llvm::UndefValue::get(ArgPtrTy);
6339 }
6340
6341 // Update VAList.
6342 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6343 Builder.CreateStore(Addr, VAListAddrAsBPP);
6344
6345 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006346}
6347
6348void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6349 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006350 for (auto &I : FI.arguments())
6351 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006352}
6353
6354namespace {
6355class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6356public:
6357 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6358 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006359
Craig Topper4f12f102014-03-12 06:41:41 +00006360 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006361 return 14;
6362 }
6363
6364 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006365 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006366};
6367} // end anonymous namespace
6368
Roman Divackyf02c9942014-02-24 18:46:27 +00006369bool
6370SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6371 llvm::Value *Address) const {
6372 // This is calculated from the LLVM and GCC tables and verified
6373 // against gcc output. AFAIK all ABIs use the same encoding.
6374
6375 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6376
6377 llvm::IntegerType *i8 = CGF.Int8Ty;
6378 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6379 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6380
6381 // 0-31: the 8-byte general-purpose registers
6382 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6383
6384 // 32-63: f0-31, the 4-byte floating-point registers
6385 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6386
6387 // Y = 64
6388 // PSR = 65
6389 // WIM = 66
6390 // TBR = 67
6391 // PC = 68
6392 // NPC = 69
6393 // FSR = 70
6394 // CSR = 71
6395 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6396
6397 // 72-87: d0-15, the 8-byte floating-point registers
6398 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6399
6400 return false;
6401}
6402
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006403
Robert Lytton0e076492013-08-13 09:43:10 +00006404//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006405// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006406//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006407
Robert Lytton0e076492013-08-13 09:43:10 +00006408namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006409
6410/// A SmallStringEnc instance is used to build up the TypeString by passing
6411/// it by reference between functions that append to it.
6412typedef llvm::SmallString<128> SmallStringEnc;
6413
6414/// TypeStringCache caches the meta encodings of Types.
6415///
6416/// The reason for caching TypeStrings is two fold:
6417/// 1. To cache a type's encoding for later uses;
6418/// 2. As a means to break recursive member type inclusion.
6419///
6420/// A cache Entry can have a Status of:
6421/// NonRecursive: The type encoding is not recursive;
6422/// Recursive: The type encoding is recursive;
6423/// Incomplete: An incomplete TypeString;
6424/// IncompleteUsed: An incomplete TypeString that has been used in a
6425/// Recursive type encoding.
6426///
6427/// A NonRecursive entry will have all of its sub-members expanded as fully
6428/// as possible. Whilst it may contain types which are recursive, the type
6429/// itself is not recursive and thus its encoding may be safely used whenever
6430/// the type is encountered.
6431///
6432/// A Recursive entry will have all of its sub-members expanded as fully as
6433/// possible. The type itself is recursive and it may contain other types which
6434/// are recursive. The Recursive encoding must not be used during the expansion
6435/// of a recursive type's recursive branch. For simplicity the code uses
6436/// IncompleteCount to reject all usage of Recursive encodings for member types.
6437///
6438/// An Incomplete entry is always a RecordType and only encodes its
6439/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6440/// are placed into the cache during type expansion as a means to identify and
6441/// handle recursive inclusion of types as sub-members. If there is recursion
6442/// the entry becomes IncompleteUsed.
6443///
6444/// During the expansion of a RecordType's members:
6445///
6446/// If the cache contains a NonRecursive encoding for the member type, the
6447/// cached encoding is used;
6448///
6449/// If the cache contains a Recursive encoding for the member type, the
6450/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6451///
6452/// If the member is a RecordType, an Incomplete encoding is placed into the
6453/// cache to break potential recursive inclusion of itself as a sub-member;
6454///
6455/// Once a member RecordType has been expanded, its temporary incomplete
6456/// entry is removed from the cache. If a Recursive encoding was swapped out
6457/// it is swapped back in;
6458///
6459/// If an incomplete entry is used to expand a sub-member, the incomplete
6460/// entry is marked as IncompleteUsed. The cache keeps count of how many
6461/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6462///
6463/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6464/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6465/// Else the member is part of a recursive type and thus the recursion has
6466/// been exited too soon for the encoding to be correct for the member.
6467///
6468class TypeStringCache {
6469 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6470 struct Entry {
6471 std::string Str; // The encoded TypeString for the type.
6472 enum Status State; // Information about the encoding in 'Str'.
6473 std::string Swapped; // A temporary place holder for a Recursive encoding
6474 // during the expansion of RecordType's members.
6475 };
6476 std::map<const IdentifierInfo *, struct Entry> Map;
6477 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6478 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6479public:
Robert Lyttond263f142014-05-06 09:38:54 +00006480 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006481 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6482 bool removeIncomplete(const IdentifierInfo *ID);
6483 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6484 bool IsRecursive);
6485 StringRef lookupStr(const IdentifierInfo *ID);
6486};
6487
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006488/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006489/// FieldEncoding is a helper for this ordering process.
6490class FieldEncoding {
6491 bool HasName;
6492 std::string Enc;
6493public:
6494 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6495 StringRef str() {return Enc.c_str();};
6496 bool operator<(const FieldEncoding &rhs) const {
6497 if (HasName != rhs.HasName) return HasName;
6498 return Enc < rhs.Enc;
6499 }
6500};
6501
Robert Lytton7d1db152013-08-19 09:46:39 +00006502class XCoreABIInfo : public DefaultABIInfo {
6503public:
6504 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006505 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6506 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006507};
6508
Robert Lyttond21e2d72014-03-03 13:45:29 +00006509class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006510 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006511public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006512 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006513 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006514 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6515 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006516};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006517
Robert Lytton2d196952013-10-11 10:29:34 +00006518} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006519
Robert Lytton7d1db152013-08-19 09:46:39 +00006520llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6521 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006522 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006523
Robert Lytton2d196952013-10-11 10:29:34 +00006524 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006525 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6526 CGF.Int8PtrPtrTy);
6527 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006528
Robert Lytton2d196952013-10-11 10:29:34 +00006529 // Handle the argument.
6530 ABIArgInfo AI = classifyArgumentType(Ty);
6531 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6532 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6533 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006534 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006535 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006536 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006537 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006538 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006539 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006540 llvm_unreachable("Unsupported ABI kind for va_arg");
6541 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006542 Val = llvm::UndefValue::get(ArgPtrTy);
6543 ArgSize = 0;
6544 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006545 case ABIArgInfo::Extend:
6546 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006547 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6548 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6549 if (ArgSize < 4)
6550 ArgSize = 4;
6551 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006552 case ABIArgInfo::Indirect:
6553 llvm::Value *ArgAddr;
6554 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6555 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006556 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6557 ArgSize = 4;
6558 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006559 }
Robert Lytton2d196952013-10-11 10:29:34 +00006560
6561 // Increment the VAList.
6562 if (ArgSize) {
6563 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6564 Builder.CreateStore(APN, VAListAddrAsBPP);
6565 }
6566 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006567}
Robert Lytton0e076492013-08-13 09:43:10 +00006568
Robert Lytton844aeeb2014-05-02 09:33:20 +00006569/// During the expansion of a RecordType, an incomplete TypeString is placed
6570/// into the cache as a means to identify and break recursion.
6571/// If there is a Recursive encoding in the cache, it is swapped out and will
6572/// be reinserted by removeIncomplete().
6573/// All other types of encoding should have been used rather than arriving here.
6574void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6575 std::string StubEnc) {
6576 if (!ID)
6577 return;
6578 Entry &E = Map[ID];
6579 assert( (E.Str.empty() || E.State == Recursive) &&
6580 "Incorrectly use of addIncomplete");
6581 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6582 E.Swapped.swap(E.Str); // swap out the Recursive
6583 E.Str.swap(StubEnc);
6584 E.State = Incomplete;
6585 ++IncompleteCount;
6586}
6587
6588/// Once the RecordType has been expanded, the temporary incomplete TypeString
6589/// must be removed from the cache.
6590/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6591/// Returns true if the RecordType was defined recursively.
6592bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6593 if (!ID)
6594 return false;
6595 auto I = Map.find(ID);
6596 assert(I != Map.end() && "Entry not present");
6597 Entry &E = I->second;
6598 assert( (E.State == Incomplete ||
6599 E.State == IncompleteUsed) &&
6600 "Entry must be an incomplete type");
6601 bool IsRecursive = false;
6602 if (E.State == IncompleteUsed) {
6603 // We made use of our Incomplete encoding, thus we are recursive.
6604 IsRecursive = true;
6605 --IncompleteUsedCount;
6606 }
6607 if (E.Swapped.empty())
6608 Map.erase(I);
6609 else {
6610 // Swap the Recursive back.
6611 E.Swapped.swap(E.Str);
6612 E.Swapped.clear();
6613 E.State = Recursive;
6614 }
6615 --IncompleteCount;
6616 return IsRecursive;
6617}
6618
6619/// Add the encoded TypeString to the cache only if it is NonRecursive or
6620/// Recursive (viz: all sub-members were expanded as fully as possible).
6621void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6622 bool IsRecursive) {
6623 if (!ID || IncompleteUsedCount)
6624 return; // No key or it is is an incomplete sub-type so don't add.
6625 Entry &E = Map[ID];
6626 if (IsRecursive && !E.Str.empty()) {
6627 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6628 "This is not the same Recursive entry");
6629 // The parent container was not recursive after all, so we could have used
6630 // this Recursive sub-member entry after all, but we assumed the worse when
6631 // we started viz: IncompleteCount!=0.
6632 return;
6633 }
6634 assert(E.Str.empty() && "Entry already present");
6635 E.Str = Str.str();
6636 E.State = IsRecursive? Recursive : NonRecursive;
6637}
6638
6639/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6640/// are recursively expanding a type (IncompleteCount != 0) and the cached
6641/// encoding is Recursive, return an empty StringRef.
6642StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6643 if (!ID)
6644 return StringRef(); // We have no key.
6645 auto I = Map.find(ID);
6646 if (I == Map.end())
6647 return StringRef(); // We have no encoding.
6648 Entry &E = I->second;
6649 if (E.State == Recursive && IncompleteCount)
6650 return StringRef(); // We don't use Recursive encodings for member types.
6651
6652 if (E.State == Incomplete) {
6653 // The incomplete type is being used to break out of recursion.
6654 E.State = IncompleteUsed;
6655 ++IncompleteUsedCount;
6656 }
6657 return E.Str.c_str();
6658}
6659
6660/// The XCore ABI includes a type information section that communicates symbol
6661/// type information to the linker. The linker uses this information to verify
6662/// safety/correctness of things such as array bound and pointers et al.
6663/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6664/// This type information (TypeString) is emitted into meta data for all global
6665/// symbols: definitions, declarations, functions & variables.
6666///
6667/// The TypeString carries type, qualifier, name, size & value details.
6668/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6669/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6670/// The output is tested by test/CodeGen/xcore-stringtype.c.
6671///
6672static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6673 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6674
6675/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6676void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6677 CodeGen::CodeGenModule &CGM) const {
6678 SmallStringEnc Enc;
6679 if (getTypeString(Enc, D, CGM, TSC)) {
6680 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006681 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6682 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006683 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6684 llvm::NamedMDNode *MD =
6685 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6686 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6687 }
6688}
6689
6690static bool appendType(SmallStringEnc &Enc, QualType QType,
6691 const CodeGen::CodeGenModule &CGM,
6692 TypeStringCache &TSC);
6693
6694/// Helper function for appendRecordType().
6695/// Builds a SmallVector containing the encoded field types in declaration order.
6696static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6697 const RecordDecl *RD,
6698 const CodeGen::CodeGenModule &CGM,
6699 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006700 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006701 SmallStringEnc Enc;
6702 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006703 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006704 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006705 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006706 Enc += "b(";
6707 llvm::raw_svector_ostream OS(Enc);
6708 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006709 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006710 OS.flush();
6711 Enc += ':';
6712 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006713 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006714 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006715 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006716 Enc += ')';
6717 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006718 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006719 }
6720 return true;
6721}
6722
6723/// Appends structure and union types to Enc and adds encoding to cache.
6724/// Recursively calls appendType (via extractFieldType) for each field.
6725/// Union types have their fields ordered according to the ABI.
6726static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6727 const CodeGen::CodeGenModule &CGM,
6728 TypeStringCache &TSC, const IdentifierInfo *ID) {
6729 // Append the cached TypeString if we have one.
6730 StringRef TypeString = TSC.lookupStr(ID);
6731 if (!TypeString.empty()) {
6732 Enc += TypeString;
6733 return true;
6734 }
6735
6736 // Start to emit an incomplete TypeString.
6737 size_t Start = Enc.size();
6738 Enc += (RT->isUnionType()? 'u' : 's');
6739 Enc += '(';
6740 if (ID)
6741 Enc += ID->getName();
6742 Enc += "){";
6743
6744 // We collect all encoded fields and order as necessary.
6745 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006746 const RecordDecl *RD = RT->getDecl()->getDefinition();
6747 if (RD && !RD->field_empty()) {
6748 // An incomplete TypeString stub is placed in the cache for this RecordType
6749 // so that recursive calls to this RecordType will use it whilst building a
6750 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006751 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006752 std::string StubEnc(Enc.substr(Start).str());
6753 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6754 TSC.addIncomplete(ID, std::move(StubEnc));
6755 if (!extractFieldType(FE, RD, CGM, TSC)) {
6756 (void) TSC.removeIncomplete(ID);
6757 return false;
6758 }
6759 IsRecursive = TSC.removeIncomplete(ID);
6760 // The ABI requires unions to be sorted but not structures.
6761 // See FieldEncoding::operator< for sort algorithm.
6762 if (RT->isUnionType())
6763 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006764 // We can now complete the TypeString.
6765 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006766 for (unsigned I = 0; I != E; ++I) {
6767 if (I)
6768 Enc += ',';
6769 Enc += FE[I].str();
6770 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006771 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006772 Enc += '}';
6773 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6774 return true;
6775}
6776
6777/// Appends enum types to Enc and adds the encoding to the cache.
6778static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6779 TypeStringCache &TSC,
6780 const IdentifierInfo *ID) {
6781 // Append the cached TypeString if we have one.
6782 StringRef TypeString = TSC.lookupStr(ID);
6783 if (!TypeString.empty()) {
6784 Enc += TypeString;
6785 return true;
6786 }
6787
6788 size_t Start = Enc.size();
6789 Enc += "e(";
6790 if (ID)
6791 Enc += ID->getName();
6792 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006793
6794 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006795 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006796 SmallVector<FieldEncoding, 16> FE;
6797 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6798 ++I) {
6799 SmallStringEnc EnumEnc;
6800 EnumEnc += "m(";
6801 EnumEnc += I->getName();
6802 EnumEnc += "){";
6803 I->getInitVal().toString(EnumEnc);
6804 EnumEnc += '}';
6805 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6806 }
6807 std::sort(FE.begin(), FE.end());
6808 unsigned E = FE.size();
6809 for (unsigned I = 0; I != E; ++I) {
6810 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006811 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006812 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006813 }
6814 }
6815 Enc += '}';
6816 TSC.addIfComplete(ID, Enc.substr(Start), false);
6817 return true;
6818}
6819
6820/// Appends type's qualifier to Enc.
6821/// This is done prior to appending the type's encoding.
6822static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6823 // Qualifiers are emitted in alphabetical order.
6824 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6825 int Lookup = 0;
6826 if (QT.isConstQualified())
6827 Lookup += 1<<0;
6828 if (QT.isRestrictQualified())
6829 Lookup += 1<<1;
6830 if (QT.isVolatileQualified())
6831 Lookup += 1<<2;
6832 Enc += Table[Lookup];
6833}
6834
6835/// Appends built-in types to Enc.
6836static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6837 const char *EncType;
6838 switch (BT->getKind()) {
6839 case BuiltinType::Void:
6840 EncType = "0";
6841 break;
6842 case BuiltinType::Bool:
6843 EncType = "b";
6844 break;
6845 case BuiltinType::Char_U:
6846 EncType = "uc";
6847 break;
6848 case BuiltinType::UChar:
6849 EncType = "uc";
6850 break;
6851 case BuiltinType::SChar:
6852 EncType = "sc";
6853 break;
6854 case BuiltinType::UShort:
6855 EncType = "us";
6856 break;
6857 case BuiltinType::Short:
6858 EncType = "ss";
6859 break;
6860 case BuiltinType::UInt:
6861 EncType = "ui";
6862 break;
6863 case BuiltinType::Int:
6864 EncType = "si";
6865 break;
6866 case BuiltinType::ULong:
6867 EncType = "ul";
6868 break;
6869 case BuiltinType::Long:
6870 EncType = "sl";
6871 break;
6872 case BuiltinType::ULongLong:
6873 EncType = "ull";
6874 break;
6875 case BuiltinType::LongLong:
6876 EncType = "sll";
6877 break;
6878 case BuiltinType::Float:
6879 EncType = "ft";
6880 break;
6881 case BuiltinType::Double:
6882 EncType = "d";
6883 break;
6884 case BuiltinType::LongDouble:
6885 EncType = "ld";
6886 break;
6887 default:
6888 return false;
6889 }
6890 Enc += EncType;
6891 return true;
6892}
6893
6894/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6895static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6896 const CodeGen::CodeGenModule &CGM,
6897 TypeStringCache &TSC) {
6898 Enc += "p(";
6899 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6900 return false;
6901 Enc += ')';
6902 return true;
6903}
6904
6905/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006906static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6907 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006908 const CodeGen::CodeGenModule &CGM,
6909 TypeStringCache &TSC, StringRef NoSizeEnc) {
6910 if (AT->getSizeModifier() != ArrayType::Normal)
6911 return false;
6912 Enc += "a(";
6913 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6914 CAT->getSize().toStringUnsigned(Enc);
6915 else
6916 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6917 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006918 // The Qualifiers should be attached to the type rather than the array.
6919 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006920 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6921 return false;
6922 Enc += ')';
6923 return true;
6924}
6925
6926/// Appends a function encoding to Enc, calling appendType for the return type
6927/// and the arguments.
6928static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6929 const CodeGen::CodeGenModule &CGM,
6930 TypeStringCache &TSC) {
6931 Enc += "f{";
6932 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6933 return false;
6934 Enc += "}(";
6935 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6936 // N.B. we are only interested in the adjusted param types.
6937 auto I = FPT->param_type_begin();
6938 auto E = FPT->param_type_end();
6939 if (I != E) {
6940 do {
6941 if (!appendType(Enc, *I, CGM, TSC))
6942 return false;
6943 ++I;
6944 if (I != E)
6945 Enc += ',';
6946 } while (I != E);
6947 if (FPT->isVariadic())
6948 Enc += ",va";
6949 } else {
6950 if (FPT->isVariadic())
6951 Enc += "va";
6952 else
6953 Enc += '0';
6954 }
6955 }
6956 Enc += ')';
6957 return true;
6958}
6959
6960/// Handles the type's qualifier before dispatching a call to handle specific
6961/// type encodings.
6962static bool appendType(SmallStringEnc &Enc, QualType QType,
6963 const CodeGen::CodeGenModule &CGM,
6964 TypeStringCache &TSC) {
6965
6966 QualType QT = QType.getCanonicalType();
6967
Robert Lytton6adb20f2014-06-05 09:06:21 +00006968 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6969 // The Qualifiers should be attached to the type rather than the array.
6970 // Thus we don't call appendQualifier() here.
6971 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6972
Robert Lytton844aeeb2014-05-02 09:33:20 +00006973 appendQualifier(Enc, QT);
6974
6975 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6976 return appendBuiltinType(Enc, BT);
6977
Robert Lytton844aeeb2014-05-02 09:33:20 +00006978 if (const PointerType *PT = QT->getAs<PointerType>())
6979 return appendPointerType(Enc, PT, CGM, TSC);
6980
6981 if (const EnumType *ET = QT->getAs<EnumType>())
6982 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6983
6984 if (const RecordType *RT = QT->getAsStructureType())
6985 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6986
6987 if (const RecordType *RT = QT->getAsUnionType())
6988 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6989
6990 if (const FunctionType *FT = QT->getAs<FunctionType>())
6991 return appendFunctionType(Enc, FT, CGM, TSC);
6992
6993 return false;
6994}
6995
6996static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6997 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6998 if (!D)
6999 return false;
7000
7001 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7002 if (FD->getLanguageLinkage() != CLanguageLinkage)
7003 return false;
7004 return appendType(Enc, FD->getType(), CGM, TSC);
7005 }
7006
7007 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7008 if (VD->getLanguageLinkage() != CLanguageLinkage)
7009 return false;
7010 QualType QT = VD->getType().getCanonicalType();
7011 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7012 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007013 // The Qualifiers should be attached to the type rather than the array.
7014 // Thus we don't call appendQualifier() here.
7015 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007016 }
7017 return appendType(Enc, QT, CGM, TSC);
7018 }
7019 return false;
7020}
7021
7022
Robert Lytton0e076492013-08-13 09:43:10 +00007023//===----------------------------------------------------------------------===//
7024// Driver code
7025//===----------------------------------------------------------------------===//
7026
Rafael Espindola9f834732014-09-19 01:54:22 +00007027const llvm::Triple &CodeGenModule::getTriple() const {
7028 return getTarget().getTriple();
7029}
7030
7031bool CodeGenModule::supportsCOMDAT() const {
7032 return !getTriple().isOSBinFormatMachO();
7033}
7034
Chris Lattner2b037972010-07-29 02:01:43 +00007035const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007036 if (TheTargetCodeGenInfo)
7037 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007038
John McCallc8e01702013-04-16 22:48:15 +00007039 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007040 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007041 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007042 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007043
Derek Schuff09338a22012-09-06 17:37:28 +00007044 case llvm::Triple::le32:
7045 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007046 case llvm::Triple::mips:
7047 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007048 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7049
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007050 case llvm::Triple::mips64:
7051 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007052 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7053
Tim Northover25e8a672014-05-24 12:51:25 +00007054 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007055 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007056 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007057 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007058 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007059
Tim Northover573cbee2014-05-24 12:52:07 +00007060 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007061 }
7062
Daniel Dunbard59655c2009-09-12 00:59:49 +00007063 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007064 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007065 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007066 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007067 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007068 if (Triple.getOS() == llvm::Triple::Win32) {
7069 TheTargetCodeGenInfo =
7070 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7071 return *TheTargetCodeGenInfo;
7072 }
7073
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007074 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007075 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007076 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007077 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007078 (CodeGenOpts.FloatABI != "soft" &&
7079 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007080 Kind = ARMABIInfo::AAPCS_VFP;
7081
Derek Schuff71658bd2015-01-29 00:47:04 +00007082 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007083 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007084
John McCallea8d8bb2010-03-11 00:10:12 +00007085 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007086 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007087 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007088 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007089 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007090 if (getTarget().getABI() == "elfv2")
7091 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007092 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007093
Ulrich Weigandb7122372014-07-21 00:48:09 +00007094 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007095 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007096 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007097 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007098 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007099 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007100 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007101 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007102 Kind = PPC64_SVR4_ABIInfo::ELFv1;
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 }
John McCallea8d8bb2010-03-11 00:10:12 +00007108
Peter Collingbournec947aae2012-05-20 23:28:41 +00007109 case llvm::Triple::nvptx:
7110 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007111 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007112
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007113 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007114 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007115
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007116 case llvm::Triple::systemz: {
7117 bool HasVector = getTarget().getABI() == "vector";
7118 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7119 HasVector));
7120 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007121
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007122 case llvm::Triple::tce:
7123 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7124
Eli Friedman33465822011-07-08 23:31:17 +00007125 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007126 bool IsDarwinVectorABI = Triple.isOSDarwin();
7127 bool IsSmallStructInRegABI =
7128 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007129 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007130
John McCall1fe2a8c2013-06-18 02:46:29 +00007131 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007132 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007133 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007134 IsDarwinVectorABI, IsSmallStructInRegABI,
7135 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007136 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007137 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007138 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007139 new X86_32TargetCodeGenInfo(Types,
7140 IsDarwinVectorABI, IsSmallStructInRegABI,
7141 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007142 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007143 }
Eli Friedman33465822011-07-08 23:31:17 +00007144 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007145
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007146 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007147 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007148
Chris Lattner04dc9572010-08-31 16:44:54 +00007149 switch (Triple.getOS()) {
7150 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007151 return *(TheTargetCodeGenInfo =
7152 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007153 case llvm::Triple::PS4:
7154 return *(TheTargetCodeGenInfo = new PS4TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007155 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007156 return *(TheTargetCodeGenInfo =
7157 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007158 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007159 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007160 case llvm::Triple::hexagon:
7161 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007162 case llvm::Triple::r600:
7163 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007164 case llvm::Triple::amdgcn:
7165 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007166 case llvm::Triple::sparcv9:
7167 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007168 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007169 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007170 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007171}