blob: e5ba200e1c573141a4ea64923e18a6e8406da31d [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
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000111bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
112 return false;
113}
114
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000115void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000116 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000117 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000118 switch (TheKind) {
119 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000120 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000121 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000122 Ty->print(OS);
123 else
124 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000125 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000126 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000127 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000128 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000129 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000130 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000131 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000132 case InAlloca:
133 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
134 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000135 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000136 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000137 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000138 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000139 break;
140 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000141 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000142 break;
143 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000144 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000145}
146
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000147TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
148
John McCall3480ef22011-08-30 01:42:09 +0000149// If someone can figure out a general rule for this, that would be great.
150// It's probably just doomed to be platform-dependent, though.
151unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
152 // Verified for:
153 // x86-64 FreeBSD, Linux, Darwin
154 // x86-32 FreeBSD, Linux, Darwin
155 // PowerPC Linux, Darwin
156 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000157 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000158 return 32;
159}
160
John McCalla729c622012-02-17 03:33:10 +0000161bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
162 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000163 // The following conventions are known to require this to be false:
164 // x86_stdcall
165 // MIPS
166 // For everything else, we just prefer false unless we opt out.
167 return false;
168}
169
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000170void
171TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
172 llvm::SmallString<24> &Opt) const {
173 // This assumes the user is passing a library name like "rt" instead of a
174 // filename like "librt.a/so", and that they don't care whether it's static or
175 // dynamic.
176 Opt = "-l";
177 Opt += Lib;
178}
179
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000180static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000181
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000182/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000183/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000184static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
185 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000186 if (FD->isUnnamedBitfield())
187 return true;
188
189 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000190
Eli Friedman0b3f2012011-11-18 03:47:20 +0000191 // Constant arrays of empty records count as empty, strip them off.
192 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000194 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
195 if (AT->getSize() == 0)
196 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000197 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000198 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000199
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000200 const RecordType *RT = FT->getAs<RecordType>();
201 if (!RT)
202 return false;
203
204 // C++ record fields are never empty, at least in the Itanium ABI.
205 //
206 // FIXME: We should use a predicate for whether this behavior is true in the
207 // current ABI.
208 if (isa<CXXRecordDecl>(RT->getDecl()))
209 return false;
210
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000211 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000212}
213
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000214/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215/// fields. Note that a structure with a flexible array member is not
216/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000217static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000218 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000219 if (!RT)
220 return 0;
221 const RecordDecl *RD = RT->getDecl();
222 if (RD->hasFlexibleArrayMember())
223 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000224
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000225 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000226 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000227 for (const auto &I : CXXRD->bases())
228 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000229 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000230
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000231 for (const auto *I : RD->fields())
232 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000233 return false;
234 return true;
235}
236
237/// isSingleElementStruct - Determine if a structure is a "single
238/// element struct", i.e. it has exactly one non-empty field or
239/// exactly one field which is itself a single element
240/// struct. Structures with flexible array members are never
241/// considered single element structs.
242///
243/// \return The field declaration for the single non-empty field, if
244/// it exists.
245static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000246 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000247 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000248 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000249
250 const RecordDecl *RD = RT->getDecl();
251 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000252 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000253
Craig Topper8a13c412014-05-21 05:09:00 +0000254 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000255
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000256 // If this is a C++ record, check the bases first.
257 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000258 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000259 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000260 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000261 continue;
262
263 // If we already found an element then this isn't a single-element struct.
264 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000265 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000266
267 // If this is non-empty and not a single element struct, the composite
268 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000269 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000270 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000271 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000272 }
273 }
274
275 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000276 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000277 QualType FT = FD->getType();
278
279 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000280 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000281 continue;
282
283 // If we already found an element then this isn't a single-element
284 // struct.
285 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000286 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000287
288 // Treat single element arrays as the element.
289 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
290 if (AT->getSize().getZExtValue() != 1)
291 break;
292 FT = AT->getElementType();
293 }
294
John McCalla1dee5302010-08-22 10:59:02 +0000295 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000296 Found = FT.getTypePtr();
297 } else {
298 Found = isSingleElementStruct(FT, Context);
299 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000300 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000301 }
302 }
303
Eli Friedmanee945342011-11-18 01:25:50 +0000304 // We don't consider a struct a single-element struct if it has
305 // padding beyond the element type.
306 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000307 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000308
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000309 return Found;
310}
311
312static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000313 // Treat complex types as the element type.
314 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
315 Ty = CTy->getElementType();
316
317 // Check for a type which we know has a simple scalar argument-passing
318 // convention without any padding. (We're specifically looking for 32
319 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000320 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000321 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000322 return false;
323
324 uint64_t Size = Context.getTypeSize(Ty);
325 return Size == 32 || Size == 64;
326}
327
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000328/// canExpandIndirectArgument - Test whether an argument type which is to be
329/// passed indirectly (on the stack) would have the equivalent layout if it was
330/// expanded into separate arguments. If so, we prefer to do the latter to avoid
331/// inhibiting optimizations.
332///
333// FIXME: This predicate is missing many cases, currently it just follows
334// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
335// should probably make this smarter, or better yet make the LLVM backend
336// capable of handling it.
337static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
338 // We can only expand structure types.
339 const RecordType *RT = Ty->getAs<RecordType>();
340 if (!RT)
341 return false;
342
343 // We can only expand (C) structures.
344 //
345 // FIXME: This needs to be generalized to handle classes as well.
346 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000347 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000348 return false;
349
Manman Ren27382782015-04-03 18:10:29 +0000350 // We try to expand CLike CXXRecordDecl.
351 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
352 if (!CXXRD->isCLike())
353 return false;
354 }
355
Eli Friedmane5c85622011-11-18 01:32:26 +0000356 uint64_t Size = 0;
357
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000358 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000359 if (!is32Or64BitBasicType(FD->getType(), Context))
360 return false;
361
362 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
363 // how to expand them yet, and the predicate for telling if a bitfield still
364 // counts as "basic" is more complicated than what we were doing previously.
365 if (FD->isBitField())
366 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000367
368 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000369 }
370
Eli Friedmane5c85622011-11-18 01:32:26 +0000371 // Make sure there are not any holes in the struct.
372 if (Size != Context.getTypeSize(Ty))
373 return false;
374
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000375 return true;
376}
377
378namespace {
379/// DefaultABIInfo - The default implementation for ABI specific
380/// details. This implementation provides information which results in
381/// self-consistent and sensible LLVM IR generation, but does not
382/// conform to any particular ABI.
383class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000384public:
385 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000386
Chris Lattner458b2aa2010-07-29 02:16:43 +0000387 ABIArgInfo classifyReturnType(QualType RetTy) const;
388 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000389
Craig Topper4f12f102014-03-12 06:41:41 +0000390 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000391 if (!getCXXABI().classifyReturnType(FI))
392 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000393 for (auto &I : FI.arguments())
394 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000395 }
396
Craig Topper4f12f102014-03-12 06:41:41 +0000397 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
398 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000399};
400
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000401class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
402public:
Chris Lattner2b037972010-07-29 02:01:43 +0000403 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
404 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000405};
406
407llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
408 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000409 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000410}
411
Chris Lattner458b2aa2010-07-29 02:16:43 +0000412ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000413 Ty = useFirstFieldIfTransparentUnion(Ty);
414
415 if (isAggregateTypeForABI(Ty)) {
416 // Records with non-trivial destructors/copy-constructors should not be
417 // passed by value.
418 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
419 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
420
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000421 return ABIArgInfo::getIndirect(0);
Reid Klecknerac385062015-05-18 22:46:30 +0000422 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000423
Chris Lattner9723d6c2010-03-11 18:19:55 +0000424 // Treat an enum type as its underlying type.
425 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
426 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000427
Chris Lattner9723d6c2010-03-11 18:19:55 +0000428 return (Ty->isPromotableIntegerType() ?
429 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000430}
431
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000432ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
433 if (RetTy->isVoidType())
434 return ABIArgInfo::getIgnore();
435
436 if (isAggregateTypeForABI(RetTy))
437 return ABIArgInfo::getIndirect(0);
438
439 // Treat an enum type as its underlying type.
440 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
441 RetTy = EnumTy->getDecl()->getIntegerType();
442
443 return (RetTy->isPromotableIntegerType() ?
444 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
445}
446
Derek Schuff09338a22012-09-06 17:37:28 +0000447//===----------------------------------------------------------------------===//
448// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000449//
450// This is a simplified version of the x86_32 ABI. Arguments and return values
451// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000452//===----------------------------------------------------------------------===//
453
454class PNaClABIInfo : public ABIInfo {
455 public:
456 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
457
458 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000459 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000460
Craig Topper4f12f102014-03-12 06:41:41 +0000461 void computeInfo(CGFunctionInfo &FI) const override;
462 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
463 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000464};
465
466class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
467 public:
468 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
469 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
470};
471
472void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000473 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000474 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
475
Reid Kleckner40ca9132014-05-13 22:05:45 +0000476 for (auto &I : FI.arguments())
477 I.info = classifyArgumentType(I.type);
478}
Derek Schuff09338a22012-09-06 17:37:28 +0000479
480llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
481 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000482 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000483}
484
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000485/// \brief Classify argument of given type \p Ty.
486ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000487 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000488 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000489 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000490 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000491 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
492 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000493 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000494 } else if (Ty->isFloatingType()) {
495 // Floating-point types don't go inreg.
496 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000497 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000498
499 return (Ty->isPromotableIntegerType() ?
500 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000501}
502
503ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
504 if (RetTy->isVoidType())
505 return ABIArgInfo::getIgnore();
506
Eli Benderskye20dad62013-04-04 22:49:35 +0000507 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000508 if (isAggregateTypeForABI(RetTy))
509 return ABIArgInfo::getIndirect(0);
510
511 // Treat an enum type as its underlying type.
512 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
513 RetTy = EnumTy->getDecl()->getIntegerType();
514
515 return (RetTy->isPromotableIntegerType() ?
516 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
517}
518
Chad Rosier651c1832013-03-25 21:00:27 +0000519/// IsX86_MMXType - Return true if this is an MMX type.
520bool IsX86_MMXType(llvm::Type *IRType) {
521 // 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 +0000522 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
523 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
524 IRType->getScalarSizeInBits() != 64;
525}
526
Jay Foad7c57be32011-07-11 09:56:20 +0000527static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000528 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000529 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000530 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
531 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
532 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000533 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000534 }
535
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000536 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000537 }
538
539 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000540 return Ty;
541}
542
Reid Kleckner80944df2014-10-31 22:00:51 +0000543/// Returns true if this type can be passed in SSE registers with the
544/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
545static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
546 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
547 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
548 return true;
549 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
550 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
551 // registers specially.
552 unsigned VecSize = Context.getTypeSize(VT);
553 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
554 return true;
555 }
556 return false;
557}
558
559/// Returns true if this aggregate is small enough to be passed in SSE registers
560/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
561static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
562 return NumMembers <= 4;
563}
564
Chris Lattner0cf24192010-06-28 20:05:43 +0000565//===----------------------------------------------------------------------===//
566// X86-32 ABI Implementation
567//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000568
Reid Kleckner661f35b2014-01-18 01:12:41 +0000569/// \brief Similar to llvm::CCState, but for Clang.
570struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000571 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000572
573 unsigned CC;
574 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000575 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000576};
577
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578/// X86_32ABIInfo - The X86-32 ABI information.
579class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000580 enum Class {
581 Integer,
582 Float
583 };
584
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000585 static const unsigned MinABIStackAlignInBytes = 4;
586
David Chisnallde3a0692009-08-17 23:08:21 +0000587 bool IsDarwinVectorABI;
588 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000589 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000590 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000591
592 static bool isRegisterSize(unsigned Size) {
593 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
594 }
595
Reid Kleckner80944df2014-10-31 22:00:51 +0000596 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
597 // FIXME: Assumes vectorcall is in use.
598 return isX86VectorTypeForVectorCall(getContext(), Ty);
599 }
600
601 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
602 uint64_t NumMembers) const override {
603 // FIXME: Assumes vectorcall is in use.
604 return isX86VectorCallAggregateSmallEnough(NumMembers);
605 }
606
Reid Kleckner40ca9132014-05-13 22:05:45 +0000607 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000608
Daniel Dunbar557893d2010-04-21 19:10:51 +0000609 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
610 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000611 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
612
613 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000614
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000615 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000616 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000617
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000618 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000619 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000620 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
621 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000622
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000623 /// \brief Rewrite the function info so that all memory arguments use
624 /// inalloca.
625 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
626
627 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
628 unsigned &StackOffset, ABIArgInfo &Info,
629 QualType Type) const;
630
Rafael Espindola75419dc2012-07-23 23:30:29 +0000631public:
632
Craig Topper4f12f102014-03-12 06:41:41 +0000633 void computeInfo(CGFunctionInfo &FI) const override;
634 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
635 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000636
Chad Rosier651c1832013-03-25 21:00:27 +0000637 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000638 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000639 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000640 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000641};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000642
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000643class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
644public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000645 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000646 bool d, bool p, bool w, unsigned r)
647 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000648
John McCall1fe2a8c2013-06-18 02:46:29 +0000649 static bool isStructReturnInRegABI(
650 const llvm::Triple &Triple, const CodeGenOptions &Opts);
651
Eric Christopher162c91c2015-06-05 22:03:00 +0000652 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000653 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000654
Craig Topper4f12f102014-03-12 06:41:41 +0000655 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000656 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000657 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000658 return 4;
659 }
660
661 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000662 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000663
Jay Foad7c57be32011-07-11 09:56:20 +0000664 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000665 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000666 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000667 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
668 }
669
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000670 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
671 std::string &Constraints,
672 std::vector<llvm::Type *> &ResultRegTypes,
673 std::vector<llvm::Type *> &ResultTruncRegTypes,
674 std::vector<LValue> &ResultRegDests,
675 std::string &AsmString,
676 unsigned NumOutputs) const override;
677
Craig Topper4f12f102014-03-12 06:41:41 +0000678 llvm::Constant *
679 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000680 unsigned Sig = (0xeb << 0) | // jmp rel8
681 (0x06 << 8) | // .+0x08
682 ('F' << 16) |
683 ('T' << 24);
684 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
685 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000686};
687
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000688}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000689
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000690/// Rewrite input constraint references after adding some output constraints.
691/// In the case where there is one output and one input and we add one output,
692/// we need to replace all operand references greater than or equal to 1:
693/// mov $0, $1
694/// mov eax, $1
695/// The result will be:
696/// mov $0, $2
697/// mov eax, $2
698static void rewriteInputConstraintReferences(unsigned FirstIn,
699 unsigned NumNewOuts,
700 std::string &AsmString) {
701 std::string Buf;
702 llvm::raw_string_ostream OS(Buf);
703 size_t Pos = 0;
704 while (Pos < AsmString.size()) {
705 size_t DollarStart = AsmString.find('$', Pos);
706 if (DollarStart == std::string::npos)
707 DollarStart = AsmString.size();
708 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
709 if (DollarEnd == std::string::npos)
710 DollarEnd = AsmString.size();
711 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
712 Pos = DollarEnd;
713 size_t NumDollars = DollarEnd - DollarStart;
714 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
715 // We have an operand reference.
716 size_t DigitStart = Pos;
717 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
718 if (DigitEnd == std::string::npos)
719 DigitEnd = AsmString.size();
720 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
721 unsigned OperandIndex;
722 if (!OperandStr.getAsInteger(10, OperandIndex)) {
723 if (OperandIndex >= FirstIn)
724 OperandIndex += NumNewOuts;
725 OS << OperandIndex;
726 } else {
727 OS << OperandStr;
728 }
729 Pos = DigitEnd;
730 }
731 }
732 AsmString = std::move(OS.str());
733}
734
735/// Add output constraints for EAX:EDX because they are return registers.
736void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
737 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
738 std::vector<llvm::Type *> &ResultRegTypes,
739 std::vector<llvm::Type *> &ResultTruncRegTypes,
740 std::vector<LValue> &ResultRegDests, std::string &AsmString,
741 unsigned NumOutputs) const {
742 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
743
744 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
745 // larger.
746 if (!Constraints.empty())
747 Constraints += ',';
748 if (RetWidth <= 32) {
749 Constraints += "={eax}";
750 ResultRegTypes.push_back(CGF.Int32Ty);
751 } else {
752 // Use the 'A' constraint for EAX:EDX.
753 Constraints += "=A";
754 ResultRegTypes.push_back(CGF.Int64Ty);
755 }
756
757 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
758 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
759 ResultTruncRegTypes.push_back(CoerceTy);
760
761 // Coerce the integer by bitcasting the return slot pointer.
762 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
763 CoerceTy->getPointerTo()));
764 ResultRegDests.push_back(ReturnSlot);
765
766 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
767}
768
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000769/// shouldReturnTypeInRegister - Determine if the given type should be
770/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000771bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
772 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000773 uint64_t Size = Context.getTypeSize(Ty);
774
775 // Type must be register sized.
776 if (!isRegisterSize(Size))
777 return false;
778
779 if (Ty->isVectorType()) {
780 // 64- and 128- bit vectors inside structures are not returned in
781 // registers.
782 if (Size == 64 || Size == 128)
783 return false;
784
785 return true;
786 }
787
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000788 // If this is a builtin, pointer, enum, complex type, member pointer, or
789 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000790 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000791 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000792 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000793 return true;
794
795 // Arrays are treated like records.
796 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000797 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000798
799 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000800 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000801 if (!RT) return false;
802
Anders Carlsson40446e82010-01-27 03:25:19 +0000803 // FIXME: Traverse bases here too.
804
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000805 // Structure types are passed in register if all fields would be
806 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000807 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000808 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000809 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000810 continue;
811
812 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000813 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000814 return false;
815 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000816 return true;
817}
818
Reid Kleckner661f35b2014-01-18 01:12:41 +0000819ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
820 // If the return value is indirect, then the hidden argument is consuming one
821 // integer register.
822 if (State.FreeRegs) {
823 --State.FreeRegs;
824 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
825 }
826 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
827}
828
Eric Christopher7565e0d2015-05-29 23:09:49 +0000829ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
830 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000831 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000832 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000833
Reid Kleckner80944df2014-10-31 22:00:51 +0000834 const Type *Base = nullptr;
835 uint64_t NumElts = 0;
836 if (State.CC == llvm::CallingConv::X86_VectorCall &&
837 isHomogeneousAggregate(RetTy, Base, NumElts)) {
838 // The LLVM struct type for such an aggregate should lower properly.
839 return ABIArgInfo::getDirect();
840 }
841
Chris Lattner458b2aa2010-07-29 02:16:43 +0000842 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000843 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000844 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000845 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000846
847 // 128-bit vectors are a special case; they are returned in
848 // registers and we need to make sure to pick a type the LLVM
849 // backend will like.
850 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000851 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000852 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000853
854 // Always return in register if it fits in a general purpose
855 // register, or if it is 64 bits and has a single element.
856 if ((Size == 8 || Size == 16 || Size == 32) ||
857 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000858 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000859 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000860
Reid Kleckner661f35b2014-01-18 01:12:41 +0000861 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000862 }
863
864 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000865 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000866
John McCalla1dee5302010-08-22 10:59:02 +0000867 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000868 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000869 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000870 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000871 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000872 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000873
David Chisnallde3a0692009-08-17 23:08:21 +0000874 // If specified, structs and unions are always indirect.
875 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000876 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000877
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000878 // Small structures which are register sized are generally returned
879 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000880 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000881 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000882
883 // As a special-case, if the struct is a "single-element" struct, and
884 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000885 // floating-point register. (MSVC does not apply this special case.)
886 // We apply a similar transformation for pointer types to improve the
887 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000888 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000889 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000890 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000891 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
892
893 // FIXME: We should be able to narrow this integer in cases with dead
894 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000895 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000896 }
897
Reid Kleckner661f35b2014-01-18 01:12:41 +0000898 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000899 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000900
Chris Lattner458b2aa2010-07-29 02:16:43 +0000901 // Treat an enum type as its underlying type.
902 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
903 RetTy = EnumTy->getDecl()->getIntegerType();
904
905 return (RetTy->isPromotableIntegerType() ?
906 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000907}
908
Eli Friedman7919bea2012-06-05 19:40:46 +0000909static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
910 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
911}
912
Daniel Dunbared23de32010-09-16 20:42:00 +0000913static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
914 const RecordType *RT = Ty->getAs<RecordType>();
915 if (!RT)
916 return 0;
917 const RecordDecl *RD = RT->getDecl();
918
919 // If this is a C++ record, check the bases first.
920 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000921 for (const auto &I : CXXRD->bases())
922 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000923 return false;
924
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000925 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000926 QualType FT = i->getType();
927
Eli Friedman7919bea2012-06-05 19:40:46 +0000928 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000929 return true;
930
931 if (isRecordWithSSEVectorType(Context, FT))
932 return true;
933 }
934
935 return false;
936}
937
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000938unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
939 unsigned Align) const {
940 // Otherwise, if the alignment is less than or equal to the minimum ABI
941 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000942 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000943 return 0; // Use default alignment.
944
945 // On non-Darwin, the stack type alignment is always 4.
946 if (!IsDarwinVectorABI) {
947 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000948 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000949 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000950
Daniel Dunbared23de32010-09-16 20:42:00 +0000951 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000952 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
953 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000954 return 16;
955
956 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000957}
958
Rafael Espindola703c47f2012-10-19 05:04:37 +0000959ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000960 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000961 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000962 if (State.FreeRegs) {
963 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000964 return ABIArgInfo::getIndirectInReg(0, false);
965 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000966 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000967 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000968
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000969 // Compute the byval alignment.
970 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
971 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
972 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000973 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000974
975 // If the stack alignment is less than the type alignment, realign the
976 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000977 bool Realign = TypeAlign > StackAlign;
978 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000979}
980
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000981X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
982 const Type *T = isSingleElementStruct(Ty, getContext());
983 if (!T)
984 T = Ty.getTypePtr();
985
986 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
987 BuiltinType::Kind K = BT->getKind();
988 if (K == BuiltinType::Float || K == BuiltinType::Double)
989 return Float;
990 }
991 return Integer;
992}
993
Reid Kleckner661f35b2014-01-18 01:12:41 +0000994bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
995 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000996 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000997 Class C = classify(Ty);
998 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000999 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001000
Rafael Espindola077dd592012-10-24 01:58:58 +00001001 unsigned Size = getContext().getTypeSize(Ty);
1002 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001003
1004 if (SizeInRegs == 0)
1005 return false;
1006
Reid Kleckner661f35b2014-01-18 01:12:41 +00001007 if (SizeInRegs > State.FreeRegs) {
1008 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001009 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001010 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001011
Reid Kleckner661f35b2014-01-18 01:12:41 +00001012 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001013
Reid Kleckner80944df2014-10-31 22:00:51 +00001014 if (State.CC == llvm::CallingConv::X86_FastCall ||
1015 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001016 if (Size > 32)
1017 return false;
1018
1019 if (Ty->isIntegralOrEnumerationType())
1020 return true;
1021
1022 if (Ty->isPointerType())
1023 return true;
1024
1025 if (Ty->isReferenceType())
1026 return true;
1027
Reid Kleckner661f35b2014-01-18 01:12:41 +00001028 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001029 NeedsPadding = true;
1030
Rafael Espindola077dd592012-10-24 01:58:58 +00001031 return false;
1032 }
1033
Rafael Espindola703c47f2012-10-19 05:04:37 +00001034 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001035}
1036
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001037ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1038 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001039 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001040
Reid Klecknerb1be6832014-11-15 01:41:41 +00001041 Ty = useFirstFieldIfTransparentUnion(Ty);
1042
Reid Kleckner80944df2014-10-31 22:00:51 +00001043 // Check with the C++ ABI first.
1044 const RecordType *RT = Ty->getAs<RecordType>();
1045 if (RT) {
1046 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1047 if (RAA == CGCXXABI::RAA_Indirect) {
1048 return getIndirectResult(Ty, false, State);
1049 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1050 // The field index doesn't matter, we'll fix it up later.
1051 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1052 }
1053 }
1054
1055 // vectorcall adds the concept of a homogenous vector aggregate, similar
1056 // to other targets.
1057 const Type *Base = nullptr;
1058 uint64_t NumElts = 0;
1059 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1060 isHomogeneousAggregate(Ty, Base, NumElts)) {
1061 if (State.FreeSSERegs >= NumElts) {
1062 State.FreeSSERegs -= NumElts;
1063 if (Ty->isBuiltinType() || Ty->isVectorType())
1064 return ABIArgInfo::getDirect();
1065 return ABIArgInfo::getExpand();
1066 }
1067 return getIndirectResult(Ty, /*ByVal=*/false, State);
1068 }
1069
1070 if (isAggregateTypeForABI(Ty)) {
1071 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001072 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001073 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001074 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001075
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001076 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001077 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001078 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001079 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001080
Eli Friedman9f061a32011-11-18 00:28:11 +00001081 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001082 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001083 return ABIArgInfo::getIgnore();
1084
Rafael Espindolafad28de2012-10-24 01:59:00 +00001085 llvm::LLVMContext &LLVMContext = getVMContext();
1086 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1087 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001088 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001089 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001090 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001091 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1092 return ABIArgInfo::getDirectInReg(Result);
1093 }
Craig Topper8a13c412014-05-21 05:09:00 +00001094 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001095
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001096 // Expand small (<= 128-bit) record types when we know that the stack layout
1097 // of those arguments will match the struct. This is important because the
1098 // LLVM backend isn't smart enough to remove byval, which inhibits many
1099 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001100 if (getContext().getTypeSize(Ty) <= 4*32 &&
1101 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001102 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001103 State.CC == llvm::CallingConv::X86_FastCall ||
1104 State.CC == llvm::CallingConv::X86_VectorCall,
1105 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001106
Reid Kleckner661f35b2014-01-18 01:12:41 +00001107 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001108 }
1109
Chris Lattnerd774ae92010-08-26 20:05:13 +00001110 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001111 // On Darwin, some vectors are passed in memory, we handle this by passing
1112 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001113 if (IsDarwinVectorABI) {
1114 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001115 if ((Size == 8 || Size == 16 || Size == 32) ||
1116 (Size == 64 && VT->getNumElements() == 1))
1117 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1118 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001119 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001120
Chad Rosier651c1832013-03-25 21:00:27 +00001121 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1122 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001123
Chris Lattnerd774ae92010-08-26 20:05:13 +00001124 return ABIArgInfo::getDirect();
1125 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001126
1127
Chris Lattner458b2aa2010-07-29 02:16:43 +00001128 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1129 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001130
Rafael Espindolafad28de2012-10-24 01:59:00 +00001131 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001132 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001133
1134 if (Ty->isPromotableIntegerType()) {
1135 if (InReg)
1136 return ABIArgInfo::getExtendInReg();
1137 return ABIArgInfo::getExtend();
1138 }
1139 if (InReg)
1140 return ABIArgInfo::getDirectInReg();
1141 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001142}
1143
Rafael Espindolaa6472962012-07-24 00:01:07 +00001144void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001145 CCState State(FI.getCallingConvention());
1146 if (State.CC == llvm::CallingConv::X86_FastCall)
1147 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001148 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1149 State.FreeRegs = 2;
1150 State.FreeSSERegs = 6;
1151 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001152 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001153 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001154 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001155
Reid Kleckner677539d2014-07-10 01:58:55 +00001156 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001157 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001158 } else if (FI.getReturnInfo().isIndirect()) {
1159 // The C++ ABI is not aware of register usage, so we have to check if the
1160 // return value was sret and put it in a register ourselves if appropriate.
1161 if (State.FreeRegs) {
1162 --State.FreeRegs; // The sret parameter consumes a register.
1163 FI.getReturnInfo().setInReg(true);
1164 }
1165 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001166
Peter Collingbournef7706832014-12-12 23:41:25 +00001167 // The chain argument effectively gives us another free register.
1168 if (FI.isChainCall())
1169 ++State.FreeRegs;
1170
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001171 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001172 for (auto &I : FI.arguments()) {
1173 I.info = classifyArgumentType(I.type, State);
1174 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001175 }
1176
1177 // If we needed to use inalloca for any argument, do a second pass and rewrite
1178 // all the memory arguments to use inalloca.
1179 if (UsedInAlloca)
1180 rewriteWithInAlloca(FI);
1181}
1182
1183void
1184X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1185 unsigned &StackOffset,
1186 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001187 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1188 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1189 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1190 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1191
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001192 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1193 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001194 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001195 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001196 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001197 unsigned NumBytes = StackOffset - OldOffset;
1198 assert(NumBytes);
1199 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1200 Ty = llvm::ArrayType::get(Ty, NumBytes);
1201 FrameFields.push_back(Ty);
1202 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001203}
1204
Reid Kleckner852361d2014-07-26 00:12:26 +00001205static bool isArgInAlloca(const ABIArgInfo &Info) {
1206 // Leave ignored and inreg arguments alone.
1207 switch (Info.getKind()) {
1208 case ABIArgInfo::InAlloca:
1209 return true;
1210 case ABIArgInfo::Indirect:
1211 assert(Info.getIndirectByVal());
1212 return true;
1213 case ABIArgInfo::Ignore:
1214 return false;
1215 case ABIArgInfo::Direct:
1216 case ABIArgInfo::Extend:
1217 case ABIArgInfo::Expand:
1218 if (Info.getInReg())
1219 return false;
1220 return true;
1221 }
1222 llvm_unreachable("invalid enum");
1223}
1224
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001225void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1226 assert(IsWin32StructABI && "inalloca only supported on win32");
1227
1228 // Build a packed struct type for all of the arguments in memory.
1229 SmallVector<llvm::Type *, 6> FrameFields;
1230
1231 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001232 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1233
1234 // Put 'this' into the struct before 'sret', if necessary.
1235 bool IsThisCall =
1236 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1237 ABIArgInfo &Ret = FI.getReturnInfo();
1238 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1239 isArgInAlloca(I->info)) {
1240 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1241 ++I;
1242 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001243
1244 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001245 if (Ret.isIndirect() && !Ret.getInReg()) {
1246 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1247 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001248 // On Windows, the hidden sret parameter is always returned in eax.
1249 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001250 }
1251
1252 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001253 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001254 ++I;
1255
1256 // Put arguments passed in memory into the struct.
1257 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001258 if (isArgInAlloca(I->info))
1259 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001260 }
1261
1262 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1263 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001264}
1265
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001266llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1267 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001268 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001269
1270 CGBuilderTy &Builder = CGF.Builder;
1271 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1272 "ap");
1273 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001274
1275 // Compute if the address needs to be aligned
1276 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1277 Align = getTypeStackAlignInBytes(Ty, Align);
1278 Align = std::max(Align, 4U);
1279 if (Align > 4) {
1280 // addr = (addr + align - 1) & -align;
1281 llvm::Value *Offset =
1282 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1283 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1284 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1285 CGF.Int32Ty);
1286 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1287 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1288 Addr->getType(),
1289 "ap.cur.aligned");
1290 }
1291
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001292 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001293 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001294 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1295
1296 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001297 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001298 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001299 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001300 "ap.next");
1301 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1302
1303 return AddrTyped;
1304}
1305
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001306bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1307 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1308 assert(Triple.getArch() == llvm::Triple::x86);
1309
1310 switch (Opts.getStructReturnConvention()) {
1311 case CodeGenOptions::SRCK_Default:
1312 break;
1313 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1314 return false;
1315 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1316 return true;
1317 }
1318
1319 if (Triple.isOSDarwin())
1320 return true;
1321
1322 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001323 case llvm::Triple::DragonFly:
1324 case llvm::Triple::FreeBSD:
1325 case llvm::Triple::OpenBSD:
1326 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001327 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001328 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001329 default:
1330 return false;
1331 }
1332}
1333
Eric Christopher162c91c2015-06-05 22:03:00 +00001334void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001335 llvm::GlobalValue *GV,
1336 CodeGen::CodeGenModule &CGM) const {
1337 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1338 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1339 // Get the LLVM function.
1340 llvm::Function *Fn = cast<llvm::Function>(GV);
1341
1342 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001343 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001344 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001345 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1346 llvm::AttributeSet::get(CGM.getLLVMContext(),
1347 llvm::AttributeSet::FunctionIndex,
1348 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001349 }
1350 }
1351}
1352
John McCallbeec5a02010-03-06 00:35:14 +00001353bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1354 CodeGen::CodeGenFunction &CGF,
1355 llvm::Value *Address) const {
1356 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001357
Chris Lattnerece04092012-02-07 00:39:47 +00001358 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001359
John McCallbeec5a02010-03-06 00:35:14 +00001360 // 0-7 are the eight integer registers; the order is different
1361 // on Darwin (for EH), but the range is the same.
1362 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001363 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001364
John McCallc8e01702013-04-16 22:48:15 +00001365 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001366 // 12-16 are st(0..4). Not sure why we stop at 4.
1367 // These have size 16, which is sizeof(long double) on
1368 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001369 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001370 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001371
John McCallbeec5a02010-03-06 00:35:14 +00001372 } else {
1373 // 9 is %eflags, which doesn't get a size on Darwin for some
1374 // reason.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001375 Builder.CreateStore(
1376 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9));
John McCallbeec5a02010-03-06 00:35:14 +00001377
1378 // 11-16 are st(0..5). Not sure why we stop at 5.
1379 // These have size 12, which is sizeof(long double) on
1380 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001381 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001382 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1383 }
John McCallbeec5a02010-03-06 00:35:14 +00001384
1385 return false;
1386}
1387
Chris Lattner0cf24192010-06-28 20:05:43 +00001388//===----------------------------------------------------------------------===//
1389// X86-64 ABI Implementation
1390//===----------------------------------------------------------------------===//
1391
1392
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001393namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001394/// The AVX ABI level for X86 targets.
1395enum class X86AVXABILevel {
1396 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001397 AVX,
1398 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001399};
1400
1401/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1402static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1403 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001404 case X86AVXABILevel::AVX512:
1405 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001406 case X86AVXABILevel::AVX:
1407 return 256;
1408 case X86AVXABILevel::None:
1409 return 128;
1410 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001411 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001412}
1413
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001414/// X86_64ABIInfo - The X86_64 ABI information.
1415class X86_64ABIInfo : public ABIInfo {
1416 enum Class {
1417 Integer = 0,
1418 SSE,
1419 SSEUp,
1420 X87,
1421 X87Up,
1422 ComplexX87,
1423 NoClass,
1424 Memory
1425 };
1426
1427 /// merge - Implement the X86_64 ABI merging algorithm.
1428 ///
1429 /// Merge an accumulating classification \arg Accum with a field
1430 /// classification \arg Field.
1431 ///
1432 /// \param Accum - The accumulating classification. This should
1433 /// always be either NoClass or the result of a previous merge
1434 /// call. In addition, this should never be Memory (the caller
1435 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001436 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001437
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001438 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1439 ///
1440 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1441 /// final MEMORY or SSE classes when necessary.
1442 ///
1443 /// \param AggregateSize - The size of the current aggregate in
1444 /// the classification process.
1445 ///
1446 /// \param Lo - The classification for the parts of the type
1447 /// residing in the low word of the containing object.
1448 ///
1449 /// \param Hi - The classification for the parts of the type
1450 /// residing in the higher words of the containing object.
1451 ///
1452 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1453
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001454 /// classify - Determine the x86_64 register classes in which the
1455 /// given type T should be passed.
1456 ///
1457 /// \param Lo - The classification for the parts of the type
1458 /// residing in the low word of the containing object.
1459 ///
1460 /// \param Hi - The classification for the parts of the type
1461 /// residing in the high word of the containing object.
1462 ///
1463 /// \param OffsetBase - The bit offset of this type in the
1464 /// containing object. Some parameters are classified different
1465 /// depending on whether they straddle an eightbyte boundary.
1466 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001467 /// \param isNamedArg - Whether the argument in question is a "named"
1468 /// argument, as used in AMD64-ABI 3.5.7.
1469 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001470 /// If a word is unused its result will be NoClass; if a type should
1471 /// be passed in Memory then at least the classification of \arg Lo
1472 /// will be Memory.
1473 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001474 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001475 ///
1476 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1477 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001478 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1479 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001480
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001481 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001482 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1483 unsigned IROffset, QualType SourceTy,
1484 unsigned SourceOffset) const;
1485 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1486 unsigned IROffset, QualType SourceTy,
1487 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001488
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001489 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001490 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001491 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001492
1493 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001494 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001495 ///
1496 /// \param freeIntRegs - The number of free integer registers remaining
1497 /// available.
1498 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001499
Chris Lattner458b2aa2010-07-29 02:16:43 +00001500 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001501
Bill Wendling5cd41c42010-10-18 03:41:31 +00001502 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001503 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001504 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001505 unsigned &neededSSE,
1506 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001507
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001508 bool IsIllegalVectorType(QualType Ty) const;
1509
John McCalle0fda732011-04-21 01:20:55 +00001510 /// The 0.98 ABI revision clarified a lot of ambiguities,
1511 /// unfortunately in ways that were not always consistent with
1512 /// certain previous compilers. In particular, platforms which
1513 /// required strict binary compatibility with older versions of GCC
1514 /// may need to exempt themselves.
1515 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001516 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001517 }
1518
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001519 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001520 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1521 // 64-bit hardware.
1522 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001523
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001524public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001525 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1526 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001527 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001528 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001529
John McCalla729c622012-02-17 03:33:10 +00001530 bool isPassedUsingAVXType(QualType type) const {
1531 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001532 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001533 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1534 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001535 if (info.isDirect()) {
1536 llvm::Type *ty = info.getCoerceToType();
1537 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1538 return (vectorTy->getBitWidth() > 128);
1539 }
1540 return false;
1541 }
1542
Craig Topper4f12f102014-03-12 06:41:41 +00001543 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001544
Craig Topper4f12f102014-03-12 06:41:41 +00001545 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1546 CodeGenFunction &CGF) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001547
1548 bool has64BitPointers() const {
1549 return Has64BitPointers;
1550 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001551};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001552
Chris Lattner04dc9572010-08-31 16:44:54 +00001553/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001554class WinX86_64ABIInfo : public ABIInfo {
1555
Reid Kleckner80944df2014-10-31 22:00:51 +00001556 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1557 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001558
Chris Lattner04dc9572010-08-31 16:44:54 +00001559public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001560 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1561
Craig Topper4f12f102014-03-12 06:41:41 +00001562 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001563
Craig Topper4f12f102014-03-12 06:41:41 +00001564 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1565 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001566
1567 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1568 // FIXME: Assumes vectorcall is in use.
1569 return isX86VectorTypeForVectorCall(getContext(), Ty);
1570 }
1571
1572 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1573 uint64_t NumMembers) const override {
1574 // FIXME: Assumes vectorcall is in use.
1575 return isX86VectorCallAggregateSmallEnough(NumMembers);
1576 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001577};
1578
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001579class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1580public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001581 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001582 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001583
John McCalla729c622012-02-17 03:33:10 +00001584 const X86_64ABIInfo &getABIInfo() const {
1585 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1586 }
1587
Craig Topper4f12f102014-03-12 06:41:41 +00001588 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001589 return 7;
1590 }
1591
1592 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001593 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001594 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001595
John McCall943fae92010-05-27 06:19:26 +00001596 // 0-15 are the 16 integer registers.
1597 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001598 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001599 return false;
1600 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001601
Jay Foad7c57be32011-07-11 09:56:20 +00001602 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001603 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001604 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001605 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1606 }
1607
John McCalla729c622012-02-17 03:33:10 +00001608 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001609 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001610 // The default CC on x86-64 sets %al to the number of SSA
1611 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001612 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001613 // that when AVX types are involved: the ABI explicitly states it is
1614 // undefined, and it doesn't work in practice because of how the ABI
1615 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001616 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001617 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001618 for (CallArgList::const_iterator
1619 it = args.begin(), ie = args.end(); it != ie; ++it) {
1620 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1621 HasAVXType = true;
1622 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001623 }
1624 }
John McCalla729c622012-02-17 03:33:10 +00001625
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001626 if (!HasAVXType)
1627 return true;
1628 }
John McCallcbc038a2011-09-21 08:08:30 +00001629
John McCalla729c622012-02-17 03:33:10 +00001630 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001631 }
1632
Craig Topper4f12f102014-03-12 06:41:41 +00001633 llvm::Constant *
1634 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001635 unsigned Sig;
1636 if (getABIInfo().has64BitPointers())
1637 Sig = (0xeb << 0) | // jmp rel8
1638 (0x0a << 8) | // .+0x0c
1639 ('F' << 16) |
1640 ('T' << 24);
1641 else
1642 Sig = (0xeb << 0) | // jmp rel8
1643 (0x06 << 8) | // .+0x08
1644 ('F' << 16) |
1645 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001646 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1647 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001648};
1649
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001650class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1651public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001652 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1653 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001654
1655 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001656 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001657 Opt = "\01";
1658 Opt += Lib;
1659 }
1660};
1661
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001662static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001663 // If the argument does not end in .lib, automatically add the suffix.
1664 // If the argument contains a space, enclose it in quotes.
1665 // This matches the behavior of MSVC.
1666 bool Quote = (Lib.find(" ") != StringRef::npos);
1667 std::string ArgStr = Quote ? "\"" : "";
1668 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001669 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001670 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001671 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001672 return ArgStr;
1673}
1674
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001675class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1676public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001677 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1678 bool d, bool p, bool w, unsigned RegParms)
1679 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001680
Eric Christopher162c91c2015-06-05 22:03:00 +00001681 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001682 CodeGen::CodeGenModule &CGM) const override;
1683
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001684 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001685 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001686 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001687 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001688 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001689
1690 void getDetectMismatchOption(llvm::StringRef Name,
1691 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001692 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001693 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001694 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001695};
1696
Hans Wennborg77dc2362015-01-20 19:45:50 +00001697static void addStackProbeSizeTargetAttribute(const Decl *D,
1698 llvm::GlobalValue *GV,
1699 CodeGen::CodeGenModule &CGM) {
1700 if (isa<FunctionDecl>(D)) {
1701 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1702 llvm::Function *Fn = cast<llvm::Function>(GV);
1703
Eric Christopher7565e0d2015-05-29 23:09:49 +00001704 Fn->addFnAttr("stack-probe-size",
1705 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00001706 }
1707 }
1708}
1709
Eric Christopher162c91c2015-06-05 22:03:00 +00001710void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001711 llvm::GlobalValue *GV,
1712 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001713 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001714
1715 addStackProbeSizeTargetAttribute(D, GV, CGM);
1716}
1717
Chris Lattner04dc9572010-08-31 16:44:54 +00001718class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1719public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001720 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1721 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001722 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001723
Eric Christopher162c91c2015-06-05 22:03:00 +00001724 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001725 CodeGen::CodeGenModule &CGM) const override;
1726
Craig Topper4f12f102014-03-12 06:41:41 +00001727 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001728 return 7;
1729 }
1730
1731 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001732 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001733 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001734
Chris Lattner04dc9572010-08-31 16:44:54 +00001735 // 0-15 are the 16 integer registers.
1736 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001737 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001738 return false;
1739 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001740
1741 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001742 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001743 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001744 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001745 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001746
1747 void getDetectMismatchOption(llvm::StringRef Name,
1748 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001749 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001750 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001751 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001752};
1753
Eric Christopher162c91c2015-06-05 22:03:00 +00001754void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001755 llvm::GlobalValue *GV,
1756 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001757 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001758
1759 addStackProbeSizeTargetAttribute(D, GV, CGM);
1760}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001761}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001762
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001763void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1764 Class &Hi) const {
1765 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1766 //
1767 // (a) If one of the classes is Memory, the whole argument is passed in
1768 // memory.
1769 //
1770 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1771 // memory.
1772 //
1773 // (c) If the size of the aggregate exceeds two eightbytes and the first
1774 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1775 // argument is passed in memory. NOTE: This is necessary to keep the
1776 // ABI working for processors that don't support the __m256 type.
1777 //
1778 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1779 //
1780 // Some of these are enforced by the merging logic. Others can arise
1781 // only with unions; for example:
1782 // union { _Complex double; unsigned; }
1783 //
1784 // Note that clauses (b) and (c) were added in 0.98.
1785 //
1786 if (Hi == Memory)
1787 Lo = Memory;
1788 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1789 Lo = Memory;
1790 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1791 Lo = Memory;
1792 if (Hi == SSEUp && Lo != SSE)
1793 Hi = SSE;
1794}
1795
Chris Lattnerd776fb12010-06-28 21:43:59 +00001796X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001797 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1798 // classified recursively so that always two fields are
1799 // considered. The resulting class is calculated according to
1800 // the classes of the fields in the eightbyte:
1801 //
1802 // (a) If both classes are equal, this is the resulting class.
1803 //
1804 // (b) If one of the classes is NO_CLASS, the resulting class is
1805 // the other class.
1806 //
1807 // (c) If one of the classes is MEMORY, the result is the MEMORY
1808 // class.
1809 //
1810 // (d) If one of the classes is INTEGER, the result is the
1811 // INTEGER.
1812 //
1813 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1814 // MEMORY is used as class.
1815 //
1816 // (f) Otherwise class SSE is used.
1817
1818 // Accum should never be memory (we should have returned) or
1819 // ComplexX87 (because this cannot be passed in a structure).
1820 assert((Accum != Memory && Accum != ComplexX87) &&
1821 "Invalid accumulated classification during merge.");
1822 if (Accum == Field || Field == NoClass)
1823 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001824 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001825 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001826 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001827 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001828 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001829 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001830 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1831 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001832 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001833 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001834}
1835
Chris Lattner5c740f12010-06-30 19:14:05 +00001836void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001837 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001838 // FIXME: This code can be simplified by introducing a simple value class for
1839 // Class pairs with appropriate constructor methods for the various
1840 // situations.
1841
1842 // FIXME: Some of the split computations are wrong; unaligned vectors
1843 // shouldn't be passed in registers for example, so there is no chance they
1844 // can straddle an eightbyte. Verify & simplify.
1845
1846 Lo = Hi = NoClass;
1847
1848 Class &Current = OffsetBase < 64 ? Lo : Hi;
1849 Current = Memory;
1850
John McCall9dd450b2009-09-21 23:43:11 +00001851 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001852 BuiltinType::Kind k = BT->getKind();
1853
1854 if (k == BuiltinType::Void) {
1855 Current = NoClass;
1856 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1857 Lo = Integer;
1858 Hi = Integer;
1859 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1860 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001861 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1862 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001863 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001864 Current = SSE;
1865 } else if (k == BuiltinType::LongDouble) {
1866 Lo = X87;
1867 Hi = X87Up;
1868 }
1869 // FIXME: _Decimal32 and _Decimal64 are SSE.
1870 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001871 return;
1872 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001873
Chris Lattnerd776fb12010-06-28 21:43:59 +00001874 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001875 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001876 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001877 return;
1878 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001879
Chris Lattnerd776fb12010-06-28 21:43:59 +00001880 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001881 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001882 return;
1883 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001884
Chris Lattnerd776fb12010-06-28 21:43:59 +00001885 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001886 if (Ty->isMemberFunctionPointerType()) {
1887 if (Has64BitPointers) {
1888 // If Has64BitPointers, this is an {i64, i64}, so classify both
1889 // Lo and Hi now.
1890 Lo = Hi = Integer;
1891 } else {
1892 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1893 // straddles an eightbyte boundary, Hi should be classified as well.
1894 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1895 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1896 if (EB_FuncPtr != EB_ThisAdj) {
1897 Lo = Hi = Integer;
1898 } else {
1899 Current = Integer;
1900 }
1901 }
1902 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001903 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001904 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001905 return;
1906 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001907
Chris Lattnerd776fb12010-06-28 21:43:59 +00001908 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001909 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001910 if (Size == 32) {
1911 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1912 // float> as integer.
1913 Current = Integer;
1914
1915 // If this type crosses an eightbyte boundary, it should be
1916 // split.
1917 uint64_t EB_Real = (OffsetBase) / 64;
1918 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1919 if (EB_Real != EB_Imag)
1920 Hi = Lo;
1921 } else if (Size == 64) {
1922 // gcc passes <1 x double> in memory. :(
1923 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1924 return;
1925
1926 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001927 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001928 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1929 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1930 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001931 Current = Integer;
1932 else
1933 Current = SSE;
1934
1935 // If this type crosses an eightbyte boundary, it should be
1936 // split.
1937 if (OffsetBase && OffsetBase != 64)
1938 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001939 } else if (Size == 128 ||
1940 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001941 // Arguments of 256-bits are split into four eightbyte chunks. The
1942 // least significant one belongs to class SSE and all the others to class
1943 // SSEUP. The original Lo and Hi design considers that types can't be
1944 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1945 // This design isn't correct for 256-bits, but since there're no cases
1946 // where the upper parts would need to be inspected, avoid adding
1947 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001948 //
1949 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1950 // registers if they are "named", i.e. not part of the "..." of a
1951 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001952 //
1953 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
1954 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001955 Lo = SSE;
1956 Hi = SSEUp;
1957 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001958 return;
1959 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001960
Chris Lattnerd776fb12010-06-28 21:43:59 +00001961 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001962 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001963
Chris Lattner2b037972010-07-29 02:01:43 +00001964 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001965 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001966 if (Size <= 64)
1967 Current = Integer;
1968 else if (Size <= 128)
1969 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001970 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001971 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001972 else if (ET == getContext().DoubleTy ||
1973 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001974 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001975 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001976 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001977 Current = ComplexX87;
1978
1979 // If this complex type crosses an eightbyte boundary then it
1980 // should be split.
1981 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001982 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001983 if (Hi == NoClass && EB_Real != EB_Imag)
1984 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001985
Chris Lattnerd776fb12010-06-28 21:43:59 +00001986 return;
1987 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001988
Chris Lattner2b037972010-07-29 02:01:43 +00001989 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001990 // Arrays are treated like structures.
1991
Chris Lattner2b037972010-07-29 02:01:43 +00001992 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001993
1994 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001995 // than four eightbytes, ..., it has class MEMORY.
1996 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001997 return;
1998
1999 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2000 // fields, it has class MEMORY.
2001 //
2002 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002003 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002004 return;
2005
2006 // Otherwise implement simplified merge. We could be smarter about
2007 // this, but it isn't worth it and would be harder to verify.
2008 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002009 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002010 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002011
2012 // The only case a 256-bit wide vector could be used is when the array
2013 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2014 // to work for sizes wider than 128, early check and fallback to memory.
2015 if (Size > 128 && EltSize != 256)
2016 return;
2017
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002018 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2019 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002020 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002021 Lo = merge(Lo, FieldLo);
2022 Hi = merge(Hi, FieldHi);
2023 if (Lo == Memory || Hi == Memory)
2024 break;
2025 }
2026
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002027 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002028 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002029 return;
2030 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002031
Chris Lattnerd776fb12010-06-28 21:43:59 +00002032 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002033 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002034
2035 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002036 // than four eightbytes, ..., it has class MEMORY.
2037 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002038 return;
2039
Anders Carlsson20759ad2009-09-16 15:53:40 +00002040 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2041 // copy constructor or a non-trivial destructor, it is passed by invisible
2042 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002043 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002044 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002045
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002046 const RecordDecl *RD = RT->getDecl();
2047
2048 // Assume variable sized types are passed in memory.
2049 if (RD->hasFlexibleArrayMember())
2050 return;
2051
Chris Lattner2b037972010-07-29 02:01:43 +00002052 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002053
2054 // Reset Lo class, this will be recomputed.
2055 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002056
2057 // If this is a C++ record, classify the bases first.
2058 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002059 for (const auto &I : CXXRD->bases()) {
2060 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002061 "Unexpected base class!");
2062 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002063 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002064
2065 // Classify this field.
2066 //
2067 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2068 // single eightbyte, each is classified separately. Each eightbyte gets
2069 // initialized to class NO_CLASS.
2070 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002071 uint64_t Offset =
2072 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002073 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002074 Lo = merge(Lo, FieldLo);
2075 Hi = merge(Hi, FieldHi);
2076 if (Lo == Memory || Hi == Memory)
2077 break;
2078 }
2079 }
2080
2081 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002082 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002083 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002084 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002085 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2086 bool BitField = i->isBitField();
2087
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002088 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2089 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002090 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002091 // The only case a 256-bit wide vector could be used is when the struct
2092 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2093 // to work for sizes wider than 128, early check and fallback to memory.
2094 //
2095 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2096 Lo = Memory;
2097 return;
2098 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002099 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002100 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002101 Lo = Memory;
2102 return;
2103 }
2104
2105 // Classify this field.
2106 //
2107 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2108 // exceeds a single eightbyte, each is classified
2109 // separately. Each eightbyte gets initialized to class
2110 // NO_CLASS.
2111 Class FieldLo, FieldHi;
2112
2113 // Bit-fields require special handling, they do not force the
2114 // structure to be passed in memory even if unaligned, and
2115 // therefore they can straddle an eightbyte.
2116 if (BitField) {
2117 // Ignore padding bit-fields.
2118 if (i->isUnnamedBitfield())
2119 continue;
2120
2121 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002122 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002123
2124 uint64_t EB_Lo = Offset / 64;
2125 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002126
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002127 if (EB_Lo) {
2128 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2129 FieldLo = NoClass;
2130 FieldHi = Integer;
2131 } else {
2132 FieldLo = Integer;
2133 FieldHi = EB_Hi ? Integer : NoClass;
2134 }
2135 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002136 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002137 Lo = merge(Lo, FieldLo);
2138 Hi = merge(Hi, FieldHi);
2139 if (Lo == Memory || Hi == Memory)
2140 break;
2141 }
2142
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002143 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002144 }
2145}
2146
Chris Lattner22a931e2010-06-29 06:01:59 +00002147ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002148 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2149 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002150 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002151 // Treat an enum type as its underlying type.
2152 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2153 Ty = EnumTy->getDecl()->getIntegerType();
2154
2155 return (Ty->isPromotableIntegerType() ?
2156 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2157 }
2158
2159 return ABIArgInfo::getIndirect(0);
2160}
2161
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002162bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2163 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2164 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002165 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002166 if (Size <= 64 || Size > LargestVector)
2167 return true;
2168 }
2169
2170 return false;
2171}
2172
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002173ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2174 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002175 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2176 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002177 //
2178 // This assumption is optimistic, as there could be free registers available
2179 // when we need to pass this argument in memory, and LLVM could try to pass
2180 // the argument in the free register. This does not seem to happen currently,
2181 // but this code would be much safer if we could mark the argument with
2182 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002183 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002184 // Treat an enum type as its underlying type.
2185 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2186 Ty = EnumTy->getDecl()->getIntegerType();
2187
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002188 return (Ty->isPromotableIntegerType() ?
2189 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002190 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002191
Mark Lacey3825e832013-10-06 01:33:34 +00002192 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002193 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002194
Chris Lattner44c2b902011-05-22 23:21:23 +00002195 // Compute the byval alignment. We specify the alignment of the byval in all
2196 // cases so that the mid-level optimizer knows the alignment of the byval.
2197 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002198
2199 // Attempt to avoid passing indirect results using byval when possible. This
2200 // is important for good codegen.
2201 //
2202 // We do this by coercing the value into a scalar type which the backend can
2203 // handle naturally (i.e., without using byval).
2204 //
2205 // For simplicity, we currently only do this when we have exhausted all of the
2206 // free integer registers. Doing this when there are free integer registers
2207 // would require more care, as we would have to ensure that the coerced value
2208 // did not claim the unused register. That would require either reording the
2209 // arguments to the function (so that any subsequent inreg values came first),
2210 // or only doing this optimization when there were no following arguments that
2211 // might be inreg.
2212 //
2213 // We currently expect it to be rare (particularly in well written code) for
2214 // arguments to be passed on the stack when there are still free integer
2215 // registers available (this would typically imply large structs being passed
2216 // by value), so this seems like a fair tradeoff for now.
2217 //
2218 // We can revisit this if the backend grows support for 'onstack' parameter
2219 // attributes. See PR12193.
2220 if (freeIntRegs == 0) {
2221 uint64_t Size = getContext().getTypeSize(Ty);
2222
2223 // If this type fits in an eightbyte, coerce it into the matching integral
2224 // type, which will end up on the stack (with alignment 8).
2225 if (Align == 8 && Size <= 64)
2226 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2227 Size));
2228 }
2229
Chris Lattner44c2b902011-05-22 23:21:23 +00002230 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002231}
2232
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002233/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2234/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002235llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002236 // Wrapper structs/arrays that only contain vectors are passed just like
2237 // vectors; strip them off if present.
2238 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2239 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002240
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002241 llvm::Type *IRType = CGT.ConvertType(Ty);
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002242 if(isa<llvm::VectorType>(IRType))
2243 return IRType;
2244
2245 // We couldn't find the preferred IR vector type for 'Ty'.
2246 uint64_t Size = getContext().getTypeSize(Ty);
2247 assert((Size == 128 || Size == 256) && "Invalid type found!");
2248
2249 // Return a LLVM IR vector type based on the size of 'Ty'.
2250 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2251 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002252}
2253
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002254/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2255/// is known to either be off the end of the specified type or being in
2256/// alignment padding. The user type specified is known to be at most 128 bits
2257/// in size, and have passed through X86_64ABIInfo::classify with a successful
2258/// classification that put one of the two halves in the INTEGER class.
2259///
2260/// It is conservatively correct to return false.
2261static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2262 unsigned EndBit, ASTContext &Context) {
2263 // If the bytes being queried are off the end of the type, there is no user
2264 // data hiding here. This handles analysis of builtins, vectors and other
2265 // types that don't contain interesting padding.
2266 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2267 if (TySize <= StartBit)
2268 return true;
2269
Chris Lattner98076a22010-07-29 07:43:55 +00002270 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2271 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2272 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2273
2274 // Check each element to see if the element overlaps with the queried range.
2275 for (unsigned i = 0; i != NumElts; ++i) {
2276 // If the element is after the span we care about, then we're done..
2277 unsigned EltOffset = i*EltSize;
2278 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002279
Chris Lattner98076a22010-07-29 07:43:55 +00002280 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2281 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2282 EndBit-EltOffset, Context))
2283 return false;
2284 }
2285 // If it overlaps no elements, then it is safe to process as padding.
2286 return true;
2287 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002288
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002289 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2290 const RecordDecl *RD = RT->getDecl();
2291 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002292
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002293 // If this is a C++ record, check the bases first.
2294 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002295 for (const auto &I : CXXRD->bases()) {
2296 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002297 "Unexpected base class!");
2298 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002299 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002300
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002301 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002302 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002303 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002304
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002305 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002306 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002307 EndBit-BaseOffset, Context))
2308 return false;
2309 }
2310 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002311
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002312 // Verify that no field has data that overlaps the region of interest. Yes
2313 // this could be sped up a lot by being smarter about queried fields,
2314 // however we're only looking at structs up to 16 bytes, so we don't care
2315 // much.
2316 unsigned idx = 0;
2317 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2318 i != e; ++i, ++idx) {
2319 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002320
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002321 // If we found a field after the region we care about, then we're done.
2322 if (FieldOffset >= EndBit) break;
2323
2324 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2325 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2326 Context))
2327 return false;
2328 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002329
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002330 // If nothing in this record overlapped the area of interest, then we're
2331 // clean.
2332 return true;
2333 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002334
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002335 return false;
2336}
2337
Chris Lattnere556a712010-07-29 18:39:32 +00002338/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2339/// float member at the specified offset. For example, {int,{float}} has a
2340/// float at offset 4. It is conservatively correct for this routine to return
2341/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002342static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002343 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002344 // Base case if we find a float.
2345 if (IROffset == 0 && IRType->isFloatTy())
2346 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002347
Chris Lattnere556a712010-07-29 18:39:32 +00002348 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002349 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002350 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2351 unsigned Elt = SL->getElementContainingOffset(IROffset);
2352 IROffset -= SL->getElementOffset(Elt);
2353 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2354 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002355
Chris Lattnere556a712010-07-29 18:39:32 +00002356 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002357 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2358 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002359 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2360 IROffset -= IROffset/EltSize*EltSize;
2361 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2362 }
2363
2364 return false;
2365}
2366
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002367
2368/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2369/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002370llvm::Type *X86_64ABIInfo::
2371GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002372 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002373 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002374 // pass as float if the last 4 bytes is just padding. This happens for
2375 // structs that contain 3 floats.
2376 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2377 SourceOffset*8+64, getContext()))
2378 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002379
Chris Lattnere556a712010-07-29 18:39:32 +00002380 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2381 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2382 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002383 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2384 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002385 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002386
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002387 return llvm::Type::getDoubleTy(getVMContext());
2388}
2389
2390
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002391/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2392/// an 8-byte GPR. This means that we either have a scalar or we are talking
2393/// about the high or low part of an up-to-16-byte struct. This routine picks
2394/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002395/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2396/// etc).
2397///
2398/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2399/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2400/// the 8-byte value references. PrefType may be null.
2401///
Alp Toker9907f082014-07-09 14:06:35 +00002402/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002403/// an offset into this that we're processing (which is always either 0 or 8).
2404///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002405llvm::Type *X86_64ABIInfo::
2406GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002407 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002408 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2409 // returning an 8-byte unit starting with it. See if we can safely use it.
2410 if (IROffset == 0) {
2411 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002412 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2413 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002414 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002415
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002416 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2417 // goodness in the source type is just tail padding. This is allowed to
2418 // kick in for struct {double,int} on the int, but not on
2419 // struct{double,int,int} because we wouldn't return the second int. We
2420 // have to do this analysis on the source type because we can't depend on
2421 // unions being lowered a specific way etc.
2422 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002423 IRType->isIntegerTy(32) ||
2424 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2425 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2426 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002427
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002428 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2429 SourceOffset*8+64, getContext()))
2430 return IRType;
2431 }
2432 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002433
Chris Lattner2192fe52011-07-18 04:24:23 +00002434 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002435 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002436 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002437 if (IROffset < SL->getSizeInBytes()) {
2438 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2439 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002440
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002441 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2442 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002443 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002444 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002445
Chris Lattner2192fe52011-07-18 04:24:23 +00002446 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002447 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002448 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002449 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002450 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2451 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002452 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002453
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002454 // Okay, we don't have any better idea of what to pass, so we pass this in an
2455 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002456 unsigned TySizeInBytes =
2457 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002458
Chris Lattner3f763422010-07-29 17:34:39 +00002459 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002460
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002461 // It is always safe to classify this as an integer type up to i64 that
2462 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002463 return llvm::IntegerType::get(getVMContext(),
2464 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002465}
2466
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002467
2468/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2469/// be used as elements of a two register pair to pass or return, return a
2470/// first class aggregate to represent them. For example, if the low part of
2471/// a by-value argument should be passed as i32* and the high part as float,
2472/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002473static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002474GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002475 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002476 // In order to correctly satisfy the ABI, we need to the high part to start
2477 // at offset 8. If the high and low parts we inferred are both 4-byte types
2478 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2479 // the second element at offset 8. Check for this:
2480 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2481 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002482 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002483 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002484
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002485 // To handle this, we have to increase the size of the low part so that the
2486 // second element will start at an 8 byte offset. We can't increase the size
2487 // of the second element because it might make us access off the end of the
2488 // struct.
2489 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002490 // There are usually two sorts of types the ABI generation code can produce
2491 // for the low part of a pair that aren't 8 bytes in size: float or
2492 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2493 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002494 // Promote these to a larger type.
2495 if (Lo->isFloatTy())
2496 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2497 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002498 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2499 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002500 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2501 }
2502 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002503
Reid Kleckneree7cf842014-12-01 22:02:27 +00002504 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002505
2506
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002507 // Verify that the second element is at an 8-byte offset.
2508 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2509 "Invalid x86-64 argument pair!");
2510 return Result;
2511}
2512
Chris Lattner31faff52010-07-28 23:06:14 +00002513ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002514classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002515 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2516 // classification algorithm.
2517 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002518 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002519
2520 // Check some invariants.
2521 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002522 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2523
Craig Topper8a13c412014-05-21 05:09:00 +00002524 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002525 switch (Lo) {
2526 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002527 if (Hi == NoClass)
2528 return ABIArgInfo::getIgnore();
2529 // If the low part is just padding, it takes no register, leave ResType
2530 // null.
2531 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2532 "Unknown missing lo part");
2533 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002534
2535 case SSEUp:
2536 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002537 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002538
2539 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2540 // hidden argument.
2541 case Memory:
2542 return getIndirectReturnResult(RetTy);
2543
2544 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2545 // available register of the sequence %rax, %rdx is used.
2546 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002547 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002548
Chris Lattner1f3a0632010-07-29 21:42:50 +00002549 // If we have a sign or zero extended integer, make sure to return Extend
2550 // so that the parameter gets the right LLVM IR attributes.
2551 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2552 // Treat an enum type as its underlying type.
2553 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2554 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002555
Chris Lattner1f3a0632010-07-29 21:42:50 +00002556 if (RetTy->isIntegralOrEnumerationType() &&
2557 RetTy->isPromotableIntegerType())
2558 return ABIArgInfo::getExtend();
2559 }
Chris Lattner31faff52010-07-28 23:06:14 +00002560 break;
2561
2562 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2563 // available SSE register of the sequence %xmm0, %xmm1 is used.
2564 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002565 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002566 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002567
2568 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2569 // returned on the X87 stack in %st0 as 80-bit x87 number.
2570 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002571 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002572 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002573
2574 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2575 // part of the value is returned in %st0 and the imaginary part in
2576 // %st1.
2577 case ComplexX87:
2578 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002579 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002580 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002581 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002582 break;
2583 }
2584
Craig Topper8a13c412014-05-21 05:09:00 +00002585 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002586 switch (Hi) {
2587 // Memory was handled previously and X87 should
2588 // never occur as a hi class.
2589 case Memory:
2590 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002591 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002592
2593 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002594 case NoClass:
2595 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002596
Chris Lattner52b3c132010-09-01 00:20:33 +00002597 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002598 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002599 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2600 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002601 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002602 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002603 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002604 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2605 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002606 break;
2607
2608 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002609 // is passed in the next available eightbyte chunk if the last used
2610 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002611 //
Chris Lattner57540c52011-04-15 05:22:18 +00002612 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002613 case SSEUp:
2614 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002615 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002616 break;
2617
2618 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2619 // returned together with the previous X87 value in %st0.
2620 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002621 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002622 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002623 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002624 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002625 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002626 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002627 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2628 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002629 }
Chris Lattner31faff52010-07-28 23:06:14 +00002630 break;
2631 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002632
Chris Lattner52b3c132010-09-01 00:20:33 +00002633 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002634 // known to pass in the high eightbyte of the result. We do this by forming a
2635 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002636 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002637 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002638
Chris Lattner1f3a0632010-07-29 21:42:50 +00002639 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002640}
2641
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002642ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002643 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2644 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002645 const
2646{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002647 Ty = useFirstFieldIfTransparentUnion(Ty);
2648
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002649 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002650 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002651
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002652 // Check some invariants.
2653 // FIXME: Enforce these by construction.
2654 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002655 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2656
2657 neededInt = 0;
2658 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002659 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002660 switch (Lo) {
2661 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002662 if (Hi == NoClass)
2663 return ABIArgInfo::getIgnore();
2664 // If the low part is just padding, it takes no register, leave ResType
2665 // null.
2666 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2667 "Unknown missing lo part");
2668 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002669
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002670 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2671 // on the stack.
2672 case Memory:
2673
2674 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2675 // COMPLEX_X87, it is passed in memory.
2676 case X87:
2677 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002678 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002679 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002680 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002681
2682 case SSEUp:
2683 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002684 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685
2686 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2687 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2688 // and %r9 is used.
2689 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002690 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002691
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002692 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002693 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002694
2695 // If we have a sign or zero extended integer, make sure to return Extend
2696 // so that the parameter gets the right LLVM IR attributes.
2697 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2698 // Treat an enum type as its underlying type.
2699 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2700 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002701
Chris Lattner1f3a0632010-07-29 21:42:50 +00002702 if (Ty->isIntegralOrEnumerationType() &&
2703 Ty->isPromotableIntegerType())
2704 return ABIArgInfo::getExtend();
2705 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002706
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707 break;
2708
2709 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2710 // available SSE register is used, the registers are taken in the
2711 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002712 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002713 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002714 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002715 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002716 break;
2717 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002718 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002719
Craig Topper8a13c412014-05-21 05:09:00 +00002720 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002721 switch (Hi) {
2722 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002723 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002724 // which is passed in memory.
2725 case Memory:
2726 case X87:
2727 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002728 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002729
2730 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002731
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002732 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002733 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002734 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002735 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002736
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002737 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2738 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002739 break;
2740
2741 // X87Up generally doesn't occur here (long double is passed in
2742 // memory), except in situations involving unions.
2743 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002744 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002745 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002746
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002747 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2748 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002749
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002750 ++neededSSE;
2751 break;
2752
2753 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2754 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002755 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002756 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002757 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002758 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002759 break;
2760 }
2761
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002762 // If a high part was specified, merge it together with the low part. It is
2763 // known to pass in the high eightbyte of the result. We do this by forming a
2764 // first class struct aggregate with the high and low part: {low, high}
2765 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002766 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002767
Chris Lattner1f3a0632010-07-29 21:42:50 +00002768 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002769}
2770
Chris Lattner22326a12010-07-29 02:31:05 +00002771void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002772
Reid Kleckner40ca9132014-05-13 22:05:45 +00002773 if (!getCXXABI().classifyReturnType(FI))
2774 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002775
2776 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002777 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002778
2779 // If the return value is indirect, then the hidden argument is consuming one
2780 // integer register.
2781 if (FI.getReturnInfo().isIndirect())
2782 --freeIntRegs;
2783
Peter Collingbournef7706832014-12-12 23:41:25 +00002784 // The chain argument effectively gives us another free register.
2785 if (FI.isChainCall())
2786 ++freeIntRegs;
2787
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002788 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002789 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2790 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002791 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002792 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002793 it != ie; ++it, ++ArgNo) {
2794 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002795
Bill Wendling9987c0e2010-10-18 23:51:38 +00002796 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002797 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002798 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002799
2800 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2801 // eightbyte of an argument, the whole argument is passed on the
2802 // stack. If registers have already been assigned for some
2803 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002804 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002805 freeIntRegs -= neededInt;
2806 freeSSERegs -= neededSSE;
2807 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002808 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002809 }
2810 }
2811}
2812
2813static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2814 QualType Ty,
2815 CodeGenFunction &CGF) {
David Blaikie2e804282015-04-05 22:47:07 +00002816 llvm::Value *overflow_arg_area_p = CGF.Builder.CreateStructGEP(
2817 nullptr, VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002818 llvm::Value *overflow_arg_area =
2819 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2820
2821 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2822 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002823 // It isn't stated explicitly in the standard, but in practice we use
2824 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002825 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2826 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002827 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002828 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002829 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002830 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2831 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002832 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002833 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002834 overflow_arg_area =
2835 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2836 overflow_arg_area->getType(),
2837 "overflow_arg_area.align");
2838 }
2839
2840 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002841 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002842 llvm::Value *Res =
2843 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002844 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002845
2846 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2847 // l->overflow_arg_area + sizeof(type).
2848 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2849 // an 8 byte boundary.
2850
2851 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002852 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002853 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002854 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2855 "overflow_arg_area.next");
2856 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2857
2858 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2859 return Res;
2860}
2861
2862llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2863 CodeGenFunction &CGF) const {
2864 // Assume that va_list type is correct; should be pointer to LLVM type:
2865 // struct {
2866 // i32 gp_offset;
2867 // i32 fp_offset;
2868 // i8* overflow_arg_area;
2869 // i8* reg_save_area;
2870 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002871 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002872
Chris Lattner9723d6c2010-03-11 18:19:55 +00002873 Ty = CGF.getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00002874 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002875 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002876
2877 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2878 // in the registers. If not go to step 7.
2879 if (!neededInt && !neededSSE)
2880 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2881
2882 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2883 // general purpose registers needed to pass type and num_fp to hold
2884 // the number of floating point registers needed.
2885
2886 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2887 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2888 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2889 //
2890 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2891 // register save space).
2892
Craig Topper8a13c412014-05-21 05:09:00 +00002893 llvm::Value *InRegs = nullptr;
2894 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2895 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002896 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002897 gp_offset_p =
2898 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002899 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002900 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2901 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002902 }
2903
2904 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002905 fp_offset_p =
2906 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002907 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2908 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002909 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2910 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002911 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2912 }
2913
2914 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2915 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2916 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2917 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2918
2919 // Emit code to load the value if it was passed in registers.
2920
2921 CGF.EmitBlock(InRegBlock);
2922
2923 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2924 // an offset of l->gp_offset and/or l->fp_offset. This may require
2925 // copying to a temporary location in case the parameter is passed
2926 // in different register classes or requires an alignment greater
2927 // than 8 for general purpose registers and 16 for XMM registers.
2928 //
2929 // FIXME: This really results in shameful code when we end up needing to
2930 // collect arguments from different places; often what should result in a
2931 // simple assembling of a structure from scattered addresses has many more
2932 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002933 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
David Blaikie1ed728c2015-04-05 22:45:47 +00002934 llvm::Value *RegAddr = CGF.Builder.CreateLoad(
2935 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3), "reg_save_area");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002936 if (neededInt && neededSSE) {
2937 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002938 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002939 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002940 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2941 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002942 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002943 llvm::Type *TyLo = ST->getElementType(0);
2944 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002945 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002946 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002947 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2948 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002949 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2950 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002951 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2952 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002953 llvm::Value *V =
2954 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
David Blaikie1ed728c2015-04-05 22:45:47 +00002955 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002956 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
David Blaikie1ed728c2015-04-05 22:45:47 +00002957 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002958
Owen Anderson170229f2009-07-14 23:10:40 +00002959 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002960 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002961 } else if (neededInt) {
2962 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2963 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002964 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002965
2966 // Copy to a temporary if necessary to ensure the appropriate alignment.
2967 std::pair<CharUnits, CharUnits> SizeAlign =
2968 CGF.getContext().getTypeInfoInChars(Ty);
2969 uint64_t TySize = SizeAlign.first.getQuantity();
2970 unsigned TyAlign = SizeAlign.second.getQuantity();
2971 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002972 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2973 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2974 RegAddr = Tmp;
2975 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002976 } else if (neededSSE == 1) {
2977 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2978 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2979 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002980 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002981 assert(neededSSE == 2 && "Invalid number of needed registers!");
2982 // SSE registers are spaced 16 bytes apart in the register save
2983 // area, we need to collect the two eightbytes together.
2984 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002985 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002986 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002987 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002988 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00002989 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002990 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2991 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002992 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2993 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002994 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Chris Lattner0cf24192010-06-28 20:05:43 +00002995 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2996 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002997 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Chris Lattner0cf24192010-06-28 20:05:43 +00002998 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2999 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003000 }
3001
3002 // AMD64-ABI 3.5.7p5: Step 5. Set:
3003 // l->gp_offset = l->gp_offset + num_gp * 8
3004 // l->fp_offset = l->fp_offset + num_fp * 16.
3005 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003006 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003007 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3008 gp_offset_p);
3009 }
3010 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003011 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003012 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3013 fp_offset_p);
3014 }
3015 CGF.EmitBranch(ContBlock);
3016
3017 // Emit code to load the value if it was passed in memory.
3018
3019 CGF.EmitBlock(InMemBlock);
3020 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
3021
3022 // Return the appropriate result.
3023
3024 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00003025 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003026 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003027 ResAddr->addIncoming(RegAddr, InRegBlock);
3028 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003029 return ResAddr;
3030}
3031
Reid Kleckner80944df2014-10-31 22:00:51 +00003032ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3033 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003034
3035 if (Ty->isVoidType())
3036 return ABIArgInfo::getIgnore();
3037
3038 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3039 Ty = EnumTy->getDecl()->getIntegerType();
3040
Reid Kleckner80944df2014-10-31 22:00:51 +00003041 TypeInfo Info = getContext().getTypeInfo(Ty);
3042 uint64_t Width = Info.Width;
3043 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003044
Reid Kleckner9005f412014-05-02 00:51:20 +00003045 const RecordType *RT = Ty->getAs<RecordType>();
3046 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003047 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003048 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003049 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3050 }
3051
3052 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003053 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3054
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003055 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003056 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003057 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003058 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003059 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003060
Reid Kleckner80944df2014-10-31 22:00:51 +00003061 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3062 // other targets.
3063 const Type *Base = nullptr;
3064 uint64_t NumElts = 0;
3065 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3066 if (FreeSSERegs >= NumElts) {
3067 FreeSSERegs -= NumElts;
3068 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3069 return ABIArgInfo::getDirect();
3070 return ABIArgInfo::getExpand();
3071 }
3072 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3073 }
3074
3075
Reid Klecknerec87fec2014-05-02 01:17:12 +00003076 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003077 // If the member pointer is represented by an LLVM int or ptr, pass it
3078 // directly.
3079 llvm::Type *LLTy = CGT.ConvertType(Ty);
3080 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3081 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003082 }
3083
Michael Kuperstein4f818702015-02-24 09:35:58 +00003084 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003085 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3086 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003087 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003088 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003089
Reid Kleckner9005f412014-05-02 00:51:20 +00003090 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003091 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003092 }
3093
Julien Lerouge10dcff82014-08-27 00:36:55 +00003094 // Bool type is always extended to the ABI, other builtin types are not
3095 // extended.
3096 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3097 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003098 return ABIArgInfo::getExtend();
3099
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003100 return ABIArgInfo::getDirect();
3101}
3102
3103void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003104 bool IsVectorCall =
3105 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003106
Reid Kleckner80944df2014-10-31 22:00:51 +00003107 // We can use up to 4 SSE return registers with vectorcall.
3108 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3109 if (!getCXXABI().classifyReturnType(FI))
3110 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3111
3112 // We can use up to 6 SSE register parameters with vectorcall.
3113 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003114 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003115 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003116}
3117
Chris Lattner04dc9572010-08-31 16:44:54 +00003118llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3119 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003120 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003121
Chris Lattner04dc9572010-08-31 16:44:54 +00003122 CGBuilderTy &Builder = CGF.Builder;
3123 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3124 "ap");
3125 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3126 llvm::Type *PTy =
3127 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3128 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3129
3130 uint64_t Offset =
3131 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3132 llvm::Value *NextAddr =
3133 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3134 "ap.next");
3135 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3136
3137 return AddrTyped;
3138}
Chris Lattner0cf24192010-06-28 20:05:43 +00003139
John McCallea8d8bb2010-03-11 00:10:12 +00003140// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003141namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003142/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3143class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003144public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003145 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3146
3147 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3148 CodeGenFunction &CGF) const override;
3149};
3150
3151class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3152public:
Eric Christopher7565e0d2015-05-29 23:09:49 +00003153 PPC32TargetCodeGenInfo(CodeGenTypes &CGT)
3154 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003155
Craig Topper4f12f102014-03-12 06:41:41 +00003156 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003157 // This is recovered from gcc output.
3158 return 1; // r1 is the dedicated stack pointer
3159 }
3160
3161 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003162 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003163};
3164
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003165}
John McCallea8d8bb2010-03-11 00:10:12 +00003166
Roman Divacky8a12d842014-11-03 18:32:54 +00003167llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3168 QualType Ty,
3169 CodeGenFunction &CGF) const {
3170 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3171 // TODO: Implement this. For now ignore.
3172 (void)CTy;
3173 return nullptr;
3174 }
3175
3176 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003177 bool isInt =
3178 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003179 llvm::Type *CharPtr = CGF.Int8PtrTy;
3180 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3181
3182 CGBuilderTy &Builder = CGF.Builder;
3183 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3184 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003185 llvm::Value *FPRPtrAsInt =
3186 Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
Roman Divacky8a12d842014-11-03 18:32:54 +00003187 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003188 llvm::Value *OverflowAreaPtrAsInt =
3189 Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3190 llvm::Value *OverflowAreaPtr =
3191 Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3192 llvm::Value *RegsaveAreaPtrAsInt =
3193 Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3194 llvm::Value *RegsaveAreaPtr =
3195 Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
Roman Divacky8a12d842014-11-03 18:32:54 +00003196 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3197 // Align GPR when TY is i64.
3198 if (isI64) {
3199 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3200 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3201 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3202 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3203 }
3204 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
Eric Christopher7565e0d2015-05-29 23:09:49 +00003205 llvm::Value *OverflowArea =
3206 Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3207 llvm::Value *OverflowAreaAsInt =
3208 Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3209 llvm::Value *RegsaveArea =
3210 Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3211 llvm::Value *RegsaveAreaAsInt =
3212 Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
Roman Divacky8a12d842014-11-03 18:32:54 +00003213
Eric Christopher7565e0d2015-05-29 23:09:49 +00003214 llvm::Value *CC =
3215 Builder.CreateICmpULT(isInt ? GPR : FPR, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003216
Eric Christopher7565e0d2015-05-29 23:09:49 +00003217 llvm::Value *RegConstant =
3218 Builder.CreateMul(isInt ? GPR : FPR, Builder.getInt8(isInt ? 4 : 8));
Roman Divacky8a12d842014-11-03 18:32:54 +00003219
Eric Christopher7565e0d2015-05-29 23:09:49 +00003220 llvm::Value *OurReg = Builder.CreateAdd(
3221 RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003222
3223 if (Ty->isFloatingType())
3224 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3225
3226 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3227 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3228 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3229
3230 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3231
3232 CGF.EmitBlock(UsingRegs);
3233
3234 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3235 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3236 // Increase the GPR/FPR indexes.
3237 if (isInt) {
3238 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3239 Builder.CreateStore(GPR, GPRPtr);
3240 } else {
3241 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3242 Builder.CreateStore(FPR, FPRPtr);
3243 }
3244 CGF.EmitBranch(Cont);
3245
3246 CGF.EmitBlock(UsingOverflow);
3247
3248 // Increase the overflow area.
3249 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003250 OverflowAreaAsInt =
3251 Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3252 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr),
3253 OverflowAreaPtr);
Roman Divacky8a12d842014-11-03 18:32:54 +00003254 CGF.EmitBranch(Cont);
3255
3256 CGF.EmitBlock(Cont);
3257
3258 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3259 Result->addIncoming(Result1, UsingRegs);
3260 Result->addIncoming(Result2, UsingOverflow);
3261
3262 if (Ty->isAggregateType()) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00003263 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003264 return Builder.CreateLoad(AGGPtr, false, "aggr");
3265 }
3266
3267 return Result;
3268}
3269
John McCallea8d8bb2010-03-11 00:10:12 +00003270bool
3271PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3272 llvm::Value *Address) const {
3273 // This is calculated from the LLVM and GCC tables and verified
3274 // against gcc output. AFAIK all ABIs use the same encoding.
3275
3276 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003277
Chris Lattnerece04092012-02-07 00:39:47 +00003278 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003279 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3280 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3281 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3282
3283 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003284 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003285
3286 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003287 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003288
3289 // 64-76 are various 4-byte special-purpose registers:
3290 // 64: mq
3291 // 65: lr
3292 // 66: ctr
3293 // 67: ap
3294 // 68-75 cr0-7
3295 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003296 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003297
3298 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003299 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003300
3301 // 109: vrsave
3302 // 110: vscr
3303 // 111: spe_acc
3304 // 112: spefscr
3305 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003306 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003307
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003308 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003309}
3310
Roman Divackyd966e722012-05-09 18:22:46 +00003311// PowerPC-64
3312
3313namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003314/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3315class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003316public:
3317 enum ABIKind {
3318 ELFv1 = 0,
3319 ELFv2
3320 };
3321
3322private:
3323 static const unsigned GPRBits = 64;
3324 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003325 bool HasQPX;
3326
3327 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3328 // will be passed in a QPX register.
3329 bool IsQPXVectorTy(const Type *Ty) const {
3330 if (!HasQPX)
3331 return false;
3332
3333 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3334 unsigned NumElements = VT->getNumElements();
3335 if (NumElements == 1)
3336 return false;
3337
3338 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3339 if (getContext().getTypeSize(Ty) <= 256)
3340 return true;
3341 } else if (VT->getElementType()->
3342 isSpecificBuiltinType(BuiltinType::Float)) {
3343 if (getContext().getTypeSize(Ty) <= 128)
3344 return true;
3345 }
3346 }
3347
3348 return false;
3349 }
3350
3351 bool IsQPXVectorTy(QualType Ty) const {
3352 return IsQPXVectorTy(Ty.getTypePtr());
3353 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003354
3355public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003356 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3357 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003358
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003359 bool isPromotableTypeForABI(QualType Ty) const;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003360 bool isAlignedParamType(QualType Ty, bool &Align32) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003361
3362 ABIArgInfo classifyReturnType(QualType RetTy) const;
3363 ABIArgInfo classifyArgumentType(QualType Ty) const;
3364
Reid Klecknere9f6a712014-10-31 17:10:41 +00003365 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3366 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3367 uint64_t Members) const override;
3368
Bill Schmidt84d37792012-10-12 19:26:17 +00003369 // TODO: We can add more logic to computeInfo to improve performance.
3370 // Example: For aggregate arguments that fit in a register, we could
3371 // use getDirectInReg (as is done below for structs containing a single
3372 // floating-point value) to avoid pushing them to memory on function
3373 // entry. This would require changing the logic in PPCISelLowering
3374 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003375 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003376 if (!getCXXABI().classifyReturnType(FI))
3377 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003378 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003379 // We rely on the default argument classification for the most part.
3380 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003381 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003382 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003383 if (T) {
3384 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003385 if (IsQPXVectorTy(T) ||
3386 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003387 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003388 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003389 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003390 continue;
3391 }
3392 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003393 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003394 }
3395 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003396
Craig Topper4f12f102014-03-12 06:41:41 +00003397 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3398 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003399};
3400
3401class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003402
Bill Schmidt25cb3492012-10-03 19:18:57 +00003403public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003404 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003405 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003406 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003407
Craig Topper4f12f102014-03-12 06:41:41 +00003408 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003409 // This is recovered from gcc output.
3410 return 1; // r1 is the dedicated stack pointer
3411 }
3412
3413 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003414 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003415};
3416
Roman Divackyd966e722012-05-09 18:22:46 +00003417class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3418public:
3419 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3420
Craig Topper4f12f102014-03-12 06:41:41 +00003421 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003422 // This is recovered from gcc output.
3423 return 1; // r1 is the dedicated stack pointer
3424 }
3425
3426 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003427 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003428};
3429
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003430}
Roman Divackyd966e722012-05-09 18:22:46 +00003431
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003432// Return true if the ABI requires Ty to be passed sign- or zero-
3433// extended to 64 bits.
3434bool
3435PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3436 // Treat an enum type as its underlying type.
3437 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3438 Ty = EnumTy->getDecl()->getIntegerType();
3439
3440 // Promotable integer types are required to be promoted by the ABI.
3441 if (Ty->isPromotableIntegerType())
3442 return true;
3443
3444 // In addition to the usual promotable integer types, we also need to
3445 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3446 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3447 switch (BT->getKind()) {
3448 case BuiltinType::Int:
3449 case BuiltinType::UInt:
3450 return true;
3451 default:
3452 break;
3453 }
3454
3455 return false;
3456}
3457
Ulrich Weigand581badc2014-07-10 17:20:07 +00003458/// isAlignedParamType - Determine whether a type requires 16-byte
3459/// alignment in the parameter area.
3460bool
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003461PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty, bool &Align32) const {
3462 Align32 = false;
3463
Ulrich Weigand581badc2014-07-10 17:20:07 +00003464 // Complex types are passed just like their elements.
3465 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3466 Ty = CTy->getElementType();
3467
3468 // Only vector types of size 16 bytes need alignment (larger types are
3469 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003470 if (IsQPXVectorTy(Ty)) {
3471 if (getContext().getTypeSize(Ty) > 128)
3472 Align32 = true;
3473
3474 return true;
3475 } else if (Ty->isVectorType()) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003476 return getContext().getTypeSize(Ty) == 128;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003477 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003478
3479 // For single-element float/vector structs, we consider the whole type
3480 // to have the same alignment requirements as its single element.
3481 const Type *AlignAsType = nullptr;
3482 const Type *EltType = isSingleElementStruct(Ty, getContext());
3483 if (EltType) {
3484 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003485 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003486 getContext().getTypeSize(EltType) == 128) ||
3487 (BT && BT->isFloatingPoint()))
3488 AlignAsType = EltType;
3489 }
3490
Ulrich Weigandb7122372014-07-21 00:48:09 +00003491 // Likewise for ELFv2 homogeneous aggregates.
3492 const Type *Base = nullptr;
3493 uint64_t Members = 0;
3494 if (!AlignAsType && Kind == ELFv2 &&
3495 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3496 AlignAsType = Base;
3497
Ulrich Weigand581badc2014-07-10 17:20:07 +00003498 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003499 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3500 if (getContext().getTypeSize(AlignAsType) > 128)
3501 Align32 = true;
3502
3503 return true;
3504 } else if (AlignAsType) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003505 return AlignAsType->isVectorType();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003506 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003507
3508 // Otherwise, we only need alignment for any aggregate type that
3509 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003510 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3511 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
3512 Align32 = true;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003513 return true;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003514 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003515
3516 return false;
3517}
3518
Ulrich Weigandb7122372014-07-21 00:48:09 +00003519/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3520/// aggregate. Base is set to the base element type, and Members is set
3521/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003522bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3523 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003524 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3525 uint64_t NElements = AT->getSize().getZExtValue();
3526 if (NElements == 0)
3527 return false;
3528 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3529 return false;
3530 Members *= NElements;
3531 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3532 const RecordDecl *RD = RT->getDecl();
3533 if (RD->hasFlexibleArrayMember())
3534 return false;
3535
3536 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003537
3538 // If this is a C++ record, check the bases first.
3539 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3540 for (const auto &I : CXXRD->bases()) {
3541 // Ignore empty records.
3542 if (isEmptyRecord(getContext(), I.getType(), true))
3543 continue;
3544
3545 uint64_t FldMembers;
3546 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3547 return false;
3548
3549 Members += FldMembers;
3550 }
3551 }
3552
Ulrich Weigandb7122372014-07-21 00:48:09 +00003553 for (const auto *FD : RD->fields()) {
3554 // Ignore (non-zero arrays of) empty records.
3555 QualType FT = FD->getType();
3556 while (const ConstantArrayType *AT =
3557 getContext().getAsConstantArrayType(FT)) {
3558 if (AT->getSize().getZExtValue() == 0)
3559 return false;
3560 FT = AT->getElementType();
3561 }
3562 if (isEmptyRecord(getContext(), FT, true))
3563 continue;
3564
3565 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3566 if (getContext().getLangOpts().CPlusPlus &&
3567 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3568 continue;
3569
3570 uint64_t FldMembers;
3571 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3572 return false;
3573
3574 Members = (RD->isUnion() ?
3575 std::max(Members, FldMembers) : Members + FldMembers);
3576 }
3577
3578 if (!Base)
3579 return false;
3580
3581 // Ensure there is no padding.
3582 if (getContext().getTypeSize(Base) * Members !=
3583 getContext().getTypeSize(Ty))
3584 return false;
3585 } else {
3586 Members = 1;
3587 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3588 Members = 2;
3589 Ty = CT->getElementType();
3590 }
3591
Reid Klecknere9f6a712014-10-31 17:10:41 +00003592 // Most ABIs only support float, double, and some vector type widths.
3593 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003594 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003595
3596 // The base type must be the same for all members. Types that
3597 // agree in both total size and mode (float vs. vector) are
3598 // treated as being equivalent here.
3599 const Type *TyPtr = Ty.getTypePtr();
3600 if (!Base)
3601 Base = TyPtr;
3602
3603 if (Base->isVectorType() != TyPtr->isVectorType() ||
3604 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3605 return false;
3606 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003607 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3608}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003609
Reid Klecknere9f6a712014-10-31 17:10:41 +00003610bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3611 // Homogeneous aggregates for ELFv2 must have base types of float,
3612 // double, long double, or 128-bit vectors.
3613 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3614 if (BT->getKind() == BuiltinType::Float ||
3615 BT->getKind() == BuiltinType::Double ||
3616 BT->getKind() == BuiltinType::LongDouble)
3617 return true;
3618 }
3619 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003620 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003621 return true;
3622 }
3623 return false;
3624}
3625
3626bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3627 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003628 // Vector types require one register, floating point types require one
3629 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003630 uint32_t NumRegs =
3631 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003632
3633 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003634 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003635}
3636
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003637ABIArgInfo
3638PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003639 Ty = useFirstFieldIfTransparentUnion(Ty);
3640
Bill Schmidt90b22c92012-11-27 02:46:43 +00003641 if (Ty->isAnyComplexType())
3642 return ABIArgInfo::getDirect();
3643
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003644 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3645 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003646 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003647 uint64_t Size = getContext().getTypeSize(Ty);
3648 if (Size > 128)
3649 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3650 else if (Size < 128) {
3651 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3652 return ABIArgInfo::getDirect(CoerceTy);
3653 }
3654 }
3655
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003656 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003657 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003658 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003659
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003660 bool Align32;
3661 uint64_t ABIAlign = isAlignedParamType(Ty, Align32) ?
3662 (Align32 ? 32 : 16) : 8;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003663 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003664
3665 // ELFv2 homogeneous aggregates are passed as array types.
3666 const Type *Base = nullptr;
3667 uint64_t Members = 0;
3668 if (Kind == ELFv2 &&
3669 isHomogeneousAggregate(Ty, Base, Members)) {
3670 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3671 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3672 return ABIArgInfo::getDirect(CoerceTy);
3673 }
3674
Ulrich Weigand601957f2014-07-21 00:56:36 +00003675 // If an aggregate may end up fully in registers, we do not
3676 // use the ByVal method, but pass the aggregate as array.
3677 // This is usually beneficial since we avoid forcing the
3678 // back-end to store the argument to memory.
3679 uint64_t Bits = getContext().getTypeSize(Ty);
3680 if (Bits > 0 && Bits <= 8 * GPRBits) {
3681 llvm::Type *CoerceTy;
3682
3683 // Types up to 8 bytes are passed as integer type (which will be
3684 // properly aligned in the argument save area doubleword).
3685 if (Bits <= GPRBits)
3686 CoerceTy = llvm::IntegerType::get(getVMContext(),
3687 llvm::RoundUpToAlignment(Bits, 8));
3688 // Larger types are passed as arrays, with the base type selected
3689 // according to the required alignment in the save area.
3690 else {
3691 uint64_t RegBits = ABIAlign * 8;
3692 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3693 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3694 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3695 }
3696
3697 return ABIArgInfo::getDirect(CoerceTy);
3698 }
3699
Ulrich Weigandb7122372014-07-21 00:48:09 +00003700 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003701 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3702 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003703 }
3704
3705 return (isPromotableTypeForABI(Ty) ?
3706 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3707}
3708
3709ABIArgInfo
3710PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3711 if (RetTy->isVoidType())
3712 return ABIArgInfo::getIgnore();
3713
Bill Schmidta3d121c2012-12-17 04:20:17 +00003714 if (RetTy->isAnyComplexType())
3715 return ABIArgInfo::getDirect();
3716
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003717 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3718 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003719 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003720 uint64_t Size = getContext().getTypeSize(RetTy);
3721 if (Size > 128)
3722 return ABIArgInfo::getIndirect(0);
3723 else if (Size < 128) {
3724 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3725 return ABIArgInfo::getDirect(CoerceTy);
3726 }
3727 }
3728
Ulrich Weigandb7122372014-07-21 00:48:09 +00003729 if (isAggregateTypeForABI(RetTy)) {
3730 // ELFv2 homogeneous aggregates are returned as array types.
3731 const Type *Base = nullptr;
3732 uint64_t Members = 0;
3733 if (Kind == ELFv2 &&
3734 isHomogeneousAggregate(RetTy, Base, Members)) {
3735 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3736 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3737 return ABIArgInfo::getDirect(CoerceTy);
3738 }
3739
3740 // ELFv2 small aggregates are returned in up to two registers.
3741 uint64_t Bits = getContext().getTypeSize(RetTy);
3742 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3743 if (Bits == 0)
3744 return ABIArgInfo::getIgnore();
3745
3746 llvm::Type *CoerceTy;
3747 if (Bits > GPRBits) {
3748 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003749 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003750 } else
3751 CoerceTy = llvm::IntegerType::get(getVMContext(),
3752 llvm::RoundUpToAlignment(Bits, 8));
3753 return ABIArgInfo::getDirect(CoerceTy);
3754 }
3755
3756 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003757 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003758 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003759
3760 return (isPromotableTypeForABI(RetTy) ?
3761 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3762}
3763
Bill Schmidt25cb3492012-10-03 19:18:57 +00003764// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3765llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3766 QualType Ty,
3767 CodeGenFunction &CGF) const {
3768 llvm::Type *BP = CGF.Int8PtrTy;
3769 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3770
3771 CGBuilderTy &Builder = CGF.Builder;
3772 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3773 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3774
Ulrich Weigand581badc2014-07-10 17:20:07 +00003775 // Handle types that require 16-byte alignment in the parameter save area.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003776 bool Align32;
3777 if (isAlignedParamType(Ty, Align32)) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003778 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003779 AddrAsInt = Builder.CreateAdd(AddrAsInt,
3780 Builder.getInt64(Align32 ? 31 : 15));
3781 AddrAsInt = Builder.CreateAnd(AddrAsInt,
3782 Builder.getInt64(Align32 ? -32 : -16));
Ulrich Weigand581badc2014-07-10 17:20:07 +00003783 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3784 }
3785
Bill Schmidt924c4782013-01-14 17:45:36 +00003786 // Update the va_list pointer. The pointer should be bumped by the
3787 // size of the object. We can trust getTypeSize() except for a complex
3788 // type whose base type is smaller than a doubleword. For these, the
3789 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003790 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003791 QualType BaseTy;
3792 unsigned CplxBaseSize = 0;
3793
3794 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3795 BaseTy = CTy->getElementType();
3796 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3797 if (CplxBaseSize < 8)
3798 SizeInBytes = 16;
3799 }
3800
Bill Schmidt25cb3492012-10-03 19:18:57 +00003801 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3802 llvm::Value *NextAddr =
3803 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3804 "ap.next");
3805 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3806
Bill Schmidt924c4782013-01-14 17:45:36 +00003807 // If we have a complex type and the base type is smaller than 8 bytes,
3808 // the ABI calls for the real and imaginary parts to be right-adjusted
3809 // in separate doublewords. However, Clang expects us to produce a
3810 // pointer to a structure with the two parts packed tightly. So generate
3811 // loads of the real and imaginary parts relative to the va_list pointer,
3812 // and store them to a temporary structure.
3813 if (CplxBaseSize && CplxBaseSize < 8) {
3814 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3815 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003816 if (CGF.CGM.getDataLayout().isBigEndian()) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00003817 RealAddr =
3818 Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3819 ImagAddr =
3820 Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003821 } else {
3822 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3823 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003824 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3825 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3826 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3827 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3828 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
David Blaikie2e804282015-04-05 22:47:07 +00003829 llvm::AllocaInst *Ptr =
3830 CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), "vacplx");
3831 llvm::Value *RealPtr =
3832 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 0, ".real");
3833 llvm::Value *ImagPtr =
3834 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 1, ".imag");
Bill Schmidt924c4782013-01-14 17:45:36 +00003835 Builder.CreateStore(Real, RealPtr, false);
3836 Builder.CreateStore(Imag, ImagPtr, false);
3837 return Ptr;
3838 }
3839
Bill Schmidt25cb3492012-10-03 19:18:57 +00003840 // If the argument is smaller than 8 bytes, it is right-adjusted in
3841 // its doubleword slot. Adjust the pointer to pick it up from the
3842 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003843 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003844 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3845 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3846 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3847 }
3848
3849 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3850 return Builder.CreateBitCast(Addr, PTy);
3851}
3852
3853static bool
3854PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3855 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003856 // This is calculated from the LLVM and GCC tables and verified
3857 // against gcc output. AFAIK all ABIs use the same encoding.
3858
3859 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3860
3861 llvm::IntegerType *i8 = CGF.Int8Ty;
3862 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3863 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3864 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3865
3866 // 0-31: r0-31, the 8-byte general-purpose registers
3867 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3868
3869 // 32-63: fp0-31, the 8-byte floating-point registers
3870 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3871
3872 // 64-76 are various 4-byte special-purpose registers:
3873 // 64: mq
3874 // 65: lr
3875 // 66: ctr
3876 // 67: ap
3877 // 68-75 cr0-7
3878 // 76: xer
3879 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3880
3881 // 77-108: v0-31, the 16-byte vector registers
3882 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3883
3884 // 109: vrsave
3885 // 110: vscr
3886 // 111: spe_acc
3887 // 112: spefscr
3888 // 113: sfp
3889 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3890
3891 return false;
3892}
John McCallea8d8bb2010-03-11 00:10:12 +00003893
Bill Schmidt25cb3492012-10-03 19:18:57 +00003894bool
3895PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3896 CodeGen::CodeGenFunction &CGF,
3897 llvm::Value *Address) const {
3898
3899 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3900}
3901
3902bool
3903PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3904 llvm::Value *Address) const {
3905
3906 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3907}
3908
Chris Lattner0cf24192010-06-28 20:05:43 +00003909//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003910// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003911//===----------------------------------------------------------------------===//
3912
3913namespace {
3914
Tim Northover573cbee2014-05-24 12:52:07 +00003915class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003916public:
3917 enum ABIKind {
3918 AAPCS = 0,
3919 DarwinPCS
3920 };
3921
3922private:
3923 ABIKind Kind;
3924
3925public:
Tim Northover573cbee2014-05-24 12:52:07 +00003926 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003927
3928private:
3929 ABIKind getABIKind() const { return Kind; }
3930 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3931
3932 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003933 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003934 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3935 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3936 uint64_t Members) const override;
3937
Tim Northovera2ee4332014-03-29 15:09:45 +00003938 bool isIllegalVectorType(QualType Ty) const;
3939
David Blaikie1cbb9712014-11-14 19:09:44 +00003940 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003941 if (!getCXXABI().classifyReturnType(FI))
3942 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003943
Tim Northoverb047bfa2014-11-27 21:02:49 +00003944 for (auto &it : FI.arguments())
3945 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003946 }
3947
3948 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3949 CodeGenFunction &CGF) const;
3950
3951 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3952 CodeGenFunction &CGF) const;
3953
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003954 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3955 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003956 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3957 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3958 }
3959};
3960
Tim Northover573cbee2014-05-24 12:52:07 +00003961class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003962public:
Tim Northover573cbee2014-05-24 12:52:07 +00003963 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3964 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003965
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003966 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003967 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3968 }
3969
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003970 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3971 return 31;
3972 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003973
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003974 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00003975};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003976}
Tim Northovera2ee4332014-03-29 15:09:45 +00003977
Tim Northoverb047bfa2014-11-27 21:02:49 +00003978ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003979 Ty = useFirstFieldIfTransparentUnion(Ty);
3980
Tim Northovera2ee4332014-03-29 15:09:45 +00003981 // Handle illegal vector types here.
3982 if (isIllegalVectorType(Ty)) {
3983 uint64_t Size = getContext().getTypeSize(Ty);
3984 if (Size <= 32) {
3985 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00003986 return ABIArgInfo::getDirect(ResType);
3987 }
3988 if (Size == 64) {
3989 llvm::Type *ResType =
3990 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00003991 return ABIArgInfo::getDirect(ResType);
3992 }
3993 if (Size == 128) {
3994 llvm::Type *ResType =
3995 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00003996 return ABIArgInfo::getDirect(ResType);
3997 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003998 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3999 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004000
4001 if (!isAggregateTypeForABI(Ty)) {
4002 // Treat an enum type as its underlying type.
4003 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4004 Ty = EnumTy->getDecl()->getIntegerType();
4005
Tim Northovera2ee4332014-03-29 15:09:45 +00004006 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4007 ? ABIArgInfo::getExtend()
4008 : ABIArgInfo::getDirect());
4009 }
4010
4011 // Structures with either a non-trivial destructor or a non-trivial
4012 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004013 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004014 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00004015 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004016 }
4017
4018 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4019 // elsewhere for GNU compatibility.
4020 if (isEmptyRecord(getContext(), Ty, true)) {
4021 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4022 return ABIArgInfo::getIgnore();
4023
Tim Northovera2ee4332014-03-29 15:09:45 +00004024 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4025 }
4026
4027 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004028 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004029 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004030 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004031 return ABIArgInfo::getDirect(
4032 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004033 }
4034
4035 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4036 uint64_t Size = getContext().getTypeSize(Ty);
4037 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004038 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004039 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004040
Tim Northovera2ee4332014-03-29 15:09:45 +00004041 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4042 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004043 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004044 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4045 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4046 }
4047 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4048 }
4049
Tim Northovera2ee4332014-03-29 15:09:45 +00004050 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4051}
4052
Tim Northover573cbee2014-05-24 12:52:07 +00004053ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004054 if (RetTy->isVoidType())
4055 return ABIArgInfo::getIgnore();
4056
4057 // Large vector types should be returned via memory.
4058 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4059 return ABIArgInfo::getIndirect(0);
4060
4061 if (!isAggregateTypeForABI(RetTy)) {
4062 // Treat an enum type as its underlying type.
4063 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4064 RetTy = EnumTy->getDecl()->getIntegerType();
4065
Tim Northover4dab6982014-04-18 13:46:08 +00004066 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4067 ? ABIArgInfo::getExtend()
4068 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004069 }
4070
Tim Northovera2ee4332014-03-29 15:09:45 +00004071 if (isEmptyRecord(getContext(), RetTy, true))
4072 return ABIArgInfo::getIgnore();
4073
Craig Topper8a13c412014-05-21 05:09:00 +00004074 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004075 uint64_t Members = 0;
4076 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004077 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4078 return ABIArgInfo::getDirect();
4079
4080 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4081 uint64_t Size = getContext().getTypeSize(RetTy);
4082 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004083 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004084 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004085
4086 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4087 // For aggregates with 16-byte alignment, we use i128.
4088 if (Alignment < 128 && Size == 128) {
4089 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4090 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4091 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004092 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4093 }
4094
4095 return ABIArgInfo::getIndirect(0);
4096}
4097
Tim Northover573cbee2014-05-24 12:52:07 +00004098/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4099bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004100 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4101 // Check whether VT is legal.
4102 unsigned NumElements = VT->getNumElements();
4103 uint64_t Size = getContext().getTypeSize(VT);
4104 // NumElements should be power of 2 between 1 and 16.
4105 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4106 return true;
4107 return Size != 64 && (Size != 128 || NumElements == 1);
4108 }
4109 return false;
4110}
4111
Reid Klecknere9f6a712014-10-31 17:10:41 +00004112bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4113 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4114 // point type or a short-vector type. This is the same as the 32-bit ABI,
4115 // but with the difference that any floating-point type is allowed,
4116 // including __fp16.
4117 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4118 if (BT->isFloatingPoint())
4119 return true;
4120 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4121 unsigned VecSize = getContext().getTypeSize(VT);
4122 if (VecSize == 64 || VecSize == 128)
4123 return true;
4124 }
4125 return false;
4126}
4127
4128bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4129 uint64_t Members) const {
4130 return Members <= 4;
4131}
4132
Tim Northoverb047bfa2014-11-27 21:02:49 +00004133llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4134 QualType Ty,
4135 CodeGenFunction &CGF) const {
4136 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004137 bool IsIndirect = AI.isIndirect();
4138
Tim Northoverb047bfa2014-11-27 21:02:49 +00004139 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4140 if (IsIndirect)
4141 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4142 else if (AI.getCoerceToType())
4143 BaseTy = AI.getCoerceToType();
4144
4145 unsigned NumRegs = 1;
4146 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4147 BaseTy = ArrTy->getElementType();
4148 NumRegs = ArrTy->getNumElements();
4149 }
4150 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4151
Tim Northovera2ee4332014-03-29 15:09:45 +00004152 // The AArch64 va_list type and handling is specified in the Procedure Call
4153 // Standard, section B.4:
4154 //
4155 // struct {
4156 // void *__stack;
4157 // void *__gr_top;
4158 // void *__vr_top;
4159 // int __gr_offs;
4160 // int __vr_offs;
4161 // };
4162
4163 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4164 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4165 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4166 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4167 auto &Ctx = CGF.getContext();
4168
Craig Topper8a13c412014-05-21 05:09:00 +00004169 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004170 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004171 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4172 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004173 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004174 reg_offs_p =
4175 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004176 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4177 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004178 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004179 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004180 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004181 reg_offs_p =
4182 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004183 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4184 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004185 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004186 }
4187
4188 //=======================================
4189 // Find out where argument was passed
4190 //=======================================
4191
4192 // If reg_offs >= 0 we're already using the stack for this type of
4193 // argument. We don't want to keep updating reg_offs (in case it overflows,
4194 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4195 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004196 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004197 UsingStack = CGF.Builder.CreateICmpSGE(
4198 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4199
4200 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4201
4202 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004203 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004204 CGF.EmitBlock(MaybeRegBlock);
4205
4206 // Integer arguments may need to correct register alignment (for example a
4207 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4208 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004209 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004210 int Align = Ctx.getTypeAlign(Ty) / 8;
4211
4212 reg_offs = CGF.Builder.CreateAdd(
4213 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4214 "align_regoffs");
4215 reg_offs = CGF.Builder.CreateAnd(
4216 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4217 "aligned_regoffs");
4218 }
4219
4220 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004221 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004222 NewOffset = CGF.Builder.CreateAdd(
4223 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4224 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4225
4226 // Now we're in a position to decide whether this argument really was in
4227 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004228 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004229 InRegs = CGF.Builder.CreateICmpSLE(
4230 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4231
4232 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4233
4234 //=======================================
4235 // Argument was in registers
4236 //=======================================
4237
4238 // Now we emit the code for if the argument was originally passed in
4239 // registers. First start the appropriate block:
4240 CGF.EmitBlock(InRegBlock);
4241
Craig Topper8a13c412014-05-21 05:09:00 +00004242 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
David Blaikie2e804282015-04-05 22:47:07 +00004243 reg_top_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, reg_top_index,
4244 "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004245 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4246 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004247 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004248 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4249
4250 if (IsIndirect) {
4251 // If it's been passed indirectly (actually a struct), whatever we find from
4252 // stored registers or on the stack will actually be a struct **.
4253 MemTy = llvm::PointerType::getUnqual(MemTy);
4254 }
4255
Craig Topper8a13c412014-05-21 05:09:00 +00004256 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004257 uint64_t NumMembers = 0;
4258 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004259 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004260 // Homogeneous aggregates passed in registers will have their elements split
4261 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4262 // qN+1, ...). We reload and store into a temporary local variable
4263 // contiguously.
4264 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4265 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4266 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
David Blaikie1ed728c2015-04-05 22:45:47 +00004267 llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(HFATy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004268 int Offset = 0;
4269
4270 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4271 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4272 for (unsigned i = 0; i < NumMembers; ++i) {
4273 llvm::Value *BaseOffset =
4274 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4275 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4276 LoadAddr = CGF.Builder.CreateBitCast(
4277 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
David Blaikie2e804282015-04-05 22:47:07 +00004278 llvm::Value *StoreAddr =
4279 CGF.Builder.CreateStructGEP(Tmp->getAllocatedType(), Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00004280
4281 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4282 CGF.Builder.CreateStore(Elem, StoreAddr);
4283 }
4284
4285 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4286 } else {
4287 // Otherwise the object is contiguous in memory
4288 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004289 if (CGF.CGM.getDataLayout().isBigEndian() &&
4290 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004291 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4292 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4293 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4294
4295 BaseAddr = CGF.Builder.CreateAdd(
4296 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4297
4298 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4299 }
4300
4301 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4302 }
4303
4304 CGF.EmitBranch(ContBlock);
4305
4306 //=======================================
4307 // Argument was on the stack
4308 //=======================================
4309 CGF.EmitBlock(OnStackBlock);
4310
Craig Topper8a13c412014-05-21 05:09:00 +00004311 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
David Blaikie1ed728c2015-04-05 22:45:47 +00004312 stack_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "stack_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004313 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4314
4315 // Again, stack arguments may need realigmnent. In this case both integer and
4316 // floating-point ones might be affected.
4317 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4318 int Align = Ctx.getTypeAlign(Ty) / 8;
4319
4320 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4321
4322 OnStackAddr = CGF.Builder.CreateAdd(
4323 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4324 "align_stack");
4325 OnStackAddr = CGF.Builder.CreateAnd(
4326 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4327 "align_stack");
4328
4329 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4330 }
4331
4332 uint64_t StackSize;
4333 if (IsIndirect)
4334 StackSize = 8;
4335 else
4336 StackSize = Ctx.getTypeSize(Ty) / 8;
4337
4338 // All stack slots are 8 bytes
4339 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4340
4341 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4342 llvm::Value *NewStack =
4343 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4344
4345 // Write the new value of __stack for the next call to va_arg
4346 CGF.Builder.CreateStore(NewStack, stack_p);
4347
4348 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4349 Ctx.getTypeSize(Ty) < 64) {
4350 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4351 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4352
4353 OnStackAddr = CGF.Builder.CreateAdd(
4354 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4355
4356 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4357 }
4358
4359 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4360
4361 CGF.EmitBranch(ContBlock);
4362
4363 //=======================================
4364 // Tidy up
4365 //=======================================
4366 CGF.EmitBlock(ContBlock);
4367
4368 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4369 ResAddr->addIncoming(RegAddr, InRegBlock);
4370 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4371
4372 if (IsIndirect)
4373 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4374
4375 return ResAddr;
4376}
4377
Eric Christopher7565e0d2015-05-29 23:09:49 +00004378llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr,
4379 QualType Ty,
4380 CodeGenFunction &CGF) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004381 // We do not support va_arg for aggregates or illegal vector types.
4382 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4383 // other cases.
4384 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004385 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004386
4387 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4388 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4389
Craig Topper8a13c412014-05-21 05:09:00 +00004390 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004391 uint64_t Members = 0;
4392 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004393
4394 bool isIndirect = false;
4395 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4396 // be passed indirectly.
4397 if (Size > 16 && !isHA) {
4398 isIndirect = true;
4399 Size = 8;
4400 Align = 8;
4401 }
4402
4403 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4404 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4405
4406 CGBuilderTy &Builder = CGF.Builder;
4407 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4408 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4409
4410 if (isEmptyRecord(getContext(), Ty, true)) {
4411 // These are ignored for parameter passing purposes.
4412 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4413 return Builder.CreateBitCast(Addr, PTy);
4414 }
4415
4416 const uint64_t MinABIAlign = 8;
4417 if (Align > MinABIAlign) {
4418 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4419 Addr = Builder.CreateGEP(Addr, Offset);
4420 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4421 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4422 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4423 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4424 }
4425
4426 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4427 llvm::Value *NextAddr = Builder.CreateGEP(
4428 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4429 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4430
4431 if (isIndirect)
4432 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4433 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4434 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4435
4436 return AddrTyped;
4437}
4438
4439//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004440// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004441//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004442
4443namespace {
4444
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004445class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004446public:
4447 enum ABIKind {
4448 APCS = 0,
4449 AAPCS = 1,
4450 AAPCS_VFP
4451 };
4452
4453private:
4454 ABIKind Kind;
4455
4456public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004457 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004458 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004459 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004460
John McCall3480ef22011-08-30 01:42:09 +00004461 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004462 switch (getTarget().getTriple().getEnvironment()) {
4463 case llvm::Triple::Android:
4464 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004465 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004466 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004467 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004468 return true;
4469 default:
4470 return false;
4471 }
John McCall3480ef22011-08-30 01:42:09 +00004472 }
4473
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004474 bool isEABIHF() const {
4475 switch (getTarget().getTriple().getEnvironment()) {
4476 case llvm::Triple::EABIHF:
4477 case llvm::Triple::GNUEABIHF:
4478 return true;
4479 default:
4480 return false;
4481 }
4482 }
4483
Daniel Dunbar020daa92009-09-12 01:00:39 +00004484 ABIKind getABIKind() const { return Kind; }
4485
Tim Northovera484bc02013-10-01 14:34:25 +00004486private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004487 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004488 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004489 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004490
Reid Klecknere9f6a712014-10-31 17:10:41 +00004491 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4492 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4493 uint64_t Members) const override;
4494
Craig Topper4f12f102014-03-12 06:41:41 +00004495 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004496
Craig Topper4f12f102014-03-12 06:41:41 +00004497 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4498 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004499
4500 llvm::CallingConv::ID getLLVMDefaultCC() const;
4501 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004502 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004503};
4504
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004505class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4506public:
Chris Lattner2b037972010-07-29 02:01:43 +00004507 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4508 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004509
John McCall3480ef22011-08-30 01:42:09 +00004510 const ARMABIInfo &getABIInfo() const {
4511 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4512 }
4513
Craig Topper4f12f102014-03-12 06:41:41 +00004514 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004515 return 13;
4516 }
Roman Divackyc1617352011-05-18 19:36:54 +00004517
Craig Topper4f12f102014-03-12 06:41:41 +00004518 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004519 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4520 }
4521
Roman Divackyc1617352011-05-18 19:36:54 +00004522 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004523 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004524 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004525
4526 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004527 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004528 return false;
4529 }
John McCall3480ef22011-08-30 01:42:09 +00004530
Craig Topper4f12f102014-03-12 06:41:41 +00004531 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004532 if (getABIInfo().isEABI()) return 88;
4533 return TargetCodeGenInfo::getSizeOfUnwindException();
4534 }
Tim Northovera484bc02013-10-01 14:34:25 +00004535
Eric Christopher162c91c2015-06-05 22:03:00 +00004536 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004537 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004538 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4539 if (!FD)
4540 return;
4541
4542 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4543 if (!Attr)
4544 return;
4545
4546 const char *Kind;
4547 switch (Attr->getInterrupt()) {
4548 case ARMInterruptAttr::Generic: Kind = ""; break;
4549 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4550 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4551 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4552 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4553 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4554 }
4555
4556 llvm::Function *Fn = cast<llvm::Function>(GV);
4557
4558 Fn->addFnAttr("interrupt", Kind);
4559
4560 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4561 return;
4562
4563 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4564 // however this is not necessarily true on taking any interrupt. Instruct
4565 // the backend to perform a realignment as part of the function prologue.
4566 llvm::AttrBuilder B;
4567 B.addStackAlignmentAttr(8);
4568 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4569 llvm::AttributeSet::get(CGM.getLLVMContext(),
4570 llvm::AttributeSet::FunctionIndex,
4571 B));
4572 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004573};
4574
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004575class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4576 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4577 CodeGen::CodeGenModule &CGM) const;
4578
4579public:
4580 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4581 : ARMTargetCodeGenInfo(CGT, K) {}
4582
Eric Christopher162c91c2015-06-05 22:03:00 +00004583 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004584 CodeGen::CodeGenModule &CGM) const override;
4585};
4586
4587void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4588 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4589 if (!isa<FunctionDecl>(D))
4590 return;
4591 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4592 return;
4593
4594 llvm::Function *F = cast<llvm::Function>(GV);
4595 F->addFnAttr("stack-probe-size",
4596 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4597}
4598
Eric Christopher162c91c2015-06-05 22:03:00 +00004599void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004600 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004601 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004602 addStackProbeSizeTargetAttribute(D, GV, CGM);
4603}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004604}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004605
Chris Lattner22326a12010-07-29 02:31:05 +00004606void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004607 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004608 FI.getReturnInfo() =
4609 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004610
Tim Northoverbc784d12015-02-24 17:22:40 +00004611 for (auto &I : FI.arguments())
4612 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004613
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004614 // Always honor user-specified calling convention.
4615 if (FI.getCallingConvention() != llvm::CallingConv::C)
4616 return;
4617
John McCall882987f2013-02-28 19:01:20 +00004618 llvm::CallingConv::ID cc = getRuntimeCC();
4619 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004620 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004621}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004622
John McCall882987f2013-02-28 19:01:20 +00004623/// Return the default calling convention that LLVM will use.
4624llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4625 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004626 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004627 return llvm::CallingConv::ARM_AAPCS_VFP;
4628 else if (isEABI())
4629 return llvm::CallingConv::ARM_AAPCS;
4630 else
4631 return llvm::CallingConv::ARM_APCS;
4632}
4633
4634/// Return the calling convention that our ABI would like us to use
4635/// as the C calling convention.
4636llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004637 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004638 case APCS: return llvm::CallingConv::ARM_APCS;
4639 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4640 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004641 }
John McCall882987f2013-02-28 19:01:20 +00004642 llvm_unreachable("bad ABI kind");
4643}
4644
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004645void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004646 assert(getRuntimeCC() == llvm::CallingConv::C);
4647
4648 // Don't muddy up the IR with a ton of explicit annotations if
4649 // they'd just match what LLVM will infer from the triple.
4650 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4651 if (abiCC != getLLVMDefaultCC())
4652 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004653
4654 BuiltinCC = (getABIKind() == APCS ?
4655 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004656}
4657
Tim Northoverbc784d12015-02-24 17:22:40 +00004658ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4659 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004660 // 6.1.2.1 The following argument types are VFP CPRCs:
4661 // A single-precision floating-point type (including promoted
4662 // half-precision types); A double-precision floating-point type;
4663 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4664 // with a Base Type of a single- or double-precision floating-point type,
4665 // 64-bit containerized vectors or 128-bit containerized vectors with one
4666 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004667 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004668
Reid Klecknerb1be6832014-11-15 01:41:41 +00004669 Ty = useFirstFieldIfTransparentUnion(Ty);
4670
Manman Renfef9e312012-10-16 19:18:39 +00004671 // Handle illegal vector types here.
4672 if (isIllegalVectorType(Ty)) {
4673 uint64_t Size = getContext().getTypeSize(Ty);
4674 if (Size <= 32) {
4675 llvm::Type *ResType =
4676 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004677 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004678 }
4679 if (Size == 64) {
4680 llvm::Type *ResType = llvm::VectorType::get(
4681 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004682 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004683 }
4684 if (Size == 128) {
4685 llvm::Type *ResType = llvm::VectorType::get(
4686 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004687 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004688 }
4689 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4690 }
4691
John McCalla1dee5302010-08-22 10:59:02 +00004692 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004693 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004694 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004695 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004696 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004697
Tim Northover5a1558e2014-11-07 22:30:50 +00004698 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4699 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004700 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004701
Oliver Stannard405bded2014-02-11 09:25:50 +00004702 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northover1060eae2013-06-21 22:49:34 +00004703 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004704 }
Tim Northover1060eae2013-06-21 22:49:34 +00004705
Daniel Dunbar09d33622009-09-14 21:54:03 +00004706 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004707 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004708 return ABIArgInfo::getIgnore();
4709
Tim Northover5a1558e2014-11-07 22:30:50 +00004710 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004711 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4712 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004713 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004714 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004715 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004716 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004717 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004718 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004719 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004720 }
4721
Manman Ren6c30e132012-08-13 21:23:55 +00004722 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004723 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4724 // most 8-byte. We realign the indirect argument if type alignment is bigger
4725 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004726 uint64_t ABIAlign = 4;
4727 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4728 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004729 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004730 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004731
Manman Ren8cd99812012-11-06 04:58:01 +00004732 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northoverd157e192015-03-09 21:40:42 +00004733 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004734 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004735 }
4736
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004737 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004738 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004739 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004740 // FIXME: Try to match the types of the arguments more accurately where
4741 // we can.
4742 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004743 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4744 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004745 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004746 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4747 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004748 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004749
Tim Northover5a1558e2014-11-07 22:30:50 +00004750 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004751}
4752
Chris Lattner458b2aa2010-07-29 02:16:43 +00004753static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004754 llvm::LLVMContext &VMContext) {
4755 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4756 // is called integer-like if its size is less than or equal to one word, and
4757 // the offset of each of its addressable sub-fields is zero.
4758
4759 uint64_t Size = Context.getTypeSize(Ty);
4760
4761 // Check that the type fits in a word.
4762 if (Size > 32)
4763 return false;
4764
4765 // FIXME: Handle vector types!
4766 if (Ty->isVectorType())
4767 return false;
4768
Daniel Dunbard53bac72009-09-14 02:20:34 +00004769 // Float types are never treated as "integer like".
4770 if (Ty->isRealFloatingType())
4771 return false;
4772
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004773 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004774 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004775 return true;
4776
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004777 // Small complex integer types are "integer like".
4778 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4779 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004780
4781 // Single element and zero sized arrays should be allowed, by the definition
4782 // above, but they are not.
4783
4784 // Otherwise, it must be a record type.
4785 const RecordType *RT = Ty->getAs<RecordType>();
4786 if (!RT) return false;
4787
4788 // Ignore records with flexible arrays.
4789 const RecordDecl *RD = RT->getDecl();
4790 if (RD->hasFlexibleArrayMember())
4791 return false;
4792
4793 // Check that all sub-fields are at offset 0, and are themselves "integer
4794 // like".
4795 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4796
4797 bool HadField = false;
4798 unsigned idx = 0;
4799 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4800 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004801 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004802
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004803 // Bit-fields are not addressable, we only need to verify they are "integer
4804 // like". We still have to disallow a subsequent non-bitfield, for example:
4805 // struct { int : 0; int x }
4806 // is non-integer like according to gcc.
4807 if (FD->isBitField()) {
4808 if (!RD->isUnion())
4809 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004810
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004811 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4812 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004813
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004814 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004815 }
4816
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004817 // Check if this field is at offset 0.
4818 if (Layout.getFieldOffset(idx) != 0)
4819 return false;
4820
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004821 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4822 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004823
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004824 // Only allow at most one field in a structure. This doesn't match the
4825 // wording above, but follows gcc in situations with a field following an
4826 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004827 if (!RD->isUnion()) {
4828 if (HadField)
4829 return false;
4830
4831 HadField = true;
4832 }
4833 }
4834
4835 return true;
4836}
4837
Oliver Stannard405bded2014-02-11 09:25:50 +00004838ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4839 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004840 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004841
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004842 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004843 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004844
Daniel Dunbar19964db2010-09-23 01:54:32 +00004845 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004846 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbar19964db2010-09-23 01:54:32 +00004847 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004848 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004849
John McCalla1dee5302010-08-22 10:59:02 +00004850 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004851 // Treat an enum type as its underlying type.
4852 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4853 RetTy = EnumTy->getDecl()->getIntegerType();
4854
Tim Northover5a1558e2014-11-07 22:30:50 +00004855 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4856 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004857 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004858
4859 // Are we following APCS?
4860 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004861 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004862 return ABIArgInfo::getIgnore();
4863
Daniel Dunbareedf1512010-02-01 23:31:19 +00004864 // Complex types are all returned as packed integers.
4865 //
4866 // FIXME: Consider using 2 x vector types if the back end handles them
4867 // correctly.
4868 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004869 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4870 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004871
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004872 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004873 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004874 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004875 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004876 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004877 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004878 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004879 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4880 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004881 }
4882
4883 // Otherwise return in memory.
4884 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004885 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004886
4887 // Otherwise this is an AAPCS variant.
4888
Chris Lattner458b2aa2010-07-29 02:16:43 +00004889 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004890 return ABIArgInfo::getIgnore();
4891
Bob Wilson1d9269a2011-11-02 04:51:36 +00004892 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004893 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004894 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004895 uint64_t Members;
4896 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004897 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004898 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004899 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004900 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004901 }
4902
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004903 // Aggregates <= 4 bytes are returned in r0; other aggregates
4904 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004905 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004906 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004907 if (getDataLayout().isBigEndian())
4908 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004909 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004910
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004911 // Return in the smallest viable integer type.
4912 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004913 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004914 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004915 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4916 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004917 }
4918
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004919 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004920}
4921
Manman Renfef9e312012-10-16 19:18:39 +00004922/// isIllegalVector - check whether Ty is an illegal vector type.
4923bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4924 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4925 // Check whether VT is legal.
4926 unsigned NumElements = VT->getNumElements();
4927 uint64_t Size = getContext().getTypeSize(VT);
4928 // NumElements should be power of 2.
4929 if ((NumElements & (NumElements - 1)) != 0)
4930 return true;
4931 // Size should be greater than 32 bits.
4932 return Size <= 32;
4933 }
4934 return false;
4935}
4936
Reid Klecknere9f6a712014-10-31 17:10:41 +00004937bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4938 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4939 // double, or 64-bit or 128-bit vectors.
4940 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4941 if (BT->getKind() == BuiltinType::Float ||
4942 BT->getKind() == BuiltinType::Double ||
4943 BT->getKind() == BuiltinType::LongDouble)
4944 return true;
4945 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4946 unsigned VecSize = getContext().getTypeSize(VT);
4947 if (VecSize == 64 || VecSize == 128)
4948 return true;
4949 }
4950 return false;
4951}
4952
4953bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4954 uint64_t Members) const {
4955 return Members <= 4;
4956}
4957
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004958llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004959 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004960 llvm::Type *BP = CGF.Int8PtrTy;
4961 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004962
4963 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004964 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004965 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004966
Tim Northover1711cc92013-06-21 23:05:33 +00004967 if (isEmptyRecord(getContext(), Ty, true)) {
4968 // These are ignored for parameter passing purposes.
4969 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4970 return Builder.CreateBitCast(Addr, PTy);
4971 }
4972
Manman Rencca54d02012-10-16 19:01:37 +00004973 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004974 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004975 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004976
4977 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4978 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004979 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4980 getABIKind() == ARMABIInfo::AAPCS)
4981 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4982 else
4983 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004984 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4985 if (isIllegalVectorType(Ty) && Size > 16) {
4986 IsIndirect = true;
4987 Size = 4;
4988 TyAlign = 4;
4989 }
Manman Rencca54d02012-10-16 19:01:37 +00004990
4991 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004992 if (TyAlign > 4) {
4993 assert((TyAlign & (TyAlign - 1)) == 0 &&
4994 "Alignment is not power of 2!");
4995 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4996 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4997 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004998 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004999 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005000
5001 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00005002 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005003 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00005004 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005005 "ap.next");
5006 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5007
Manman Renfef9e312012-10-16 19:18:39 +00005008 if (IsIndirect)
5009 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00005010 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00005011 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5012 // may not be correctly aligned for the vector type. We create an aligned
5013 // temporary space and copy the content over from ap.cur to the temporary
5014 // space. This is necessary if the natural alignment of the type is greater
5015 // than the ABI alignment.
5016 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5017 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5018 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5019 "var.align");
5020 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5021 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5022 Builder.CreateMemCpy(Dst, Src,
5023 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5024 TyAlign, false);
5025 Addr = AlignedTemp; //The content is in aligned location.
5026 }
5027 llvm::Type *PTy =
5028 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5029 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5030
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005031 return AddrTyped;
5032}
5033
Chris Lattner0cf24192010-06-28 20:05:43 +00005034//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005035// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005036//===----------------------------------------------------------------------===//
5037
5038namespace {
5039
Justin Holewinski83e96682012-05-24 17:43:12 +00005040class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005041public:
Justin Holewinski36837432013-03-30 14:38:24 +00005042 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005043
5044 ABIArgInfo classifyReturnType(QualType RetTy) const;
5045 ABIArgInfo classifyArgumentType(QualType Ty) const;
5046
Craig Topper4f12f102014-03-12 06:41:41 +00005047 void computeInfo(CGFunctionInfo &FI) const override;
5048 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5049 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005050};
5051
Justin Holewinski83e96682012-05-24 17:43:12 +00005052class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005053public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005054 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5055 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005056
Eric Christopher162c91c2015-06-05 22:03:00 +00005057 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005058 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005059private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005060 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5061 // resulting MDNode to the nvvm.annotations MDNode.
5062 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005063};
5064
Justin Holewinski83e96682012-05-24 17:43:12 +00005065ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005066 if (RetTy->isVoidType())
5067 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005068
5069 // note: this is different from default ABI
5070 if (!RetTy->isScalarType())
5071 return ABIArgInfo::getDirect();
5072
5073 // Treat an enum type as its underlying type.
5074 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5075 RetTy = EnumTy->getDecl()->getIntegerType();
5076
5077 return (RetTy->isPromotableIntegerType() ?
5078 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005079}
5080
Justin Holewinski83e96682012-05-24 17:43:12 +00005081ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005082 // Treat an enum type as its underlying type.
5083 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5084 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005085
Eli Bendersky95338a02014-10-29 13:43:21 +00005086 // Return aggregates type as indirect by value
5087 if (isAggregateTypeForABI(Ty))
5088 return ABIArgInfo::getIndirect(0, /* byval */ true);
5089
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005090 return (Ty->isPromotableIntegerType() ?
5091 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005092}
5093
Justin Holewinski83e96682012-05-24 17:43:12 +00005094void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005095 if (!getCXXABI().classifyReturnType(FI))
5096 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005097 for (auto &I : FI.arguments())
5098 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005099
5100 // Always honor user-specified calling convention.
5101 if (FI.getCallingConvention() != llvm::CallingConv::C)
5102 return;
5103
John McCall882987f2013-02-28 19:01:20 +00005104 FI.setEffectiveCallingConvention(getRuntimeCC());
5105}
5106
Justin Holewinski83e96682012-05-24 17:43:12 +00005107llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5108 CodeGenFunction &CFG) const {
5109 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005110}
5111
Justin Holewinski83e96682012-05-24 17:43:12 +00005112void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005113setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005114 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005115 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5116 if (!FD) return;
5117
5118 llvm::Function *F = cast<llvm::Function>(GV);
5119
5120 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005121 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005122 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005123 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005124 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005125 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005126 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5127 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005128 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005129 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005130 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005131 }
Justin Holewinski38031972011-10-05 17:58:44 +00005132
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005133 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005134 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005135 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005136 // __global__ functions cannot be called from the device, we do not
5137 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005138 if (FD->hasAttr<CUDAGlobalAttr>()) {
5139 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5140 addNVVMMetadata(F, "kernel", 1);
5141 }
Artem Belevich7093e402015-04-21 22:55:54 +00005142 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005143 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005144 llvm::APSInt MaxThreads(32);
5145 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5146 if (MaxThreads > 0)
5147 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5148
5149 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5150 // not specified in __launch_bounds__ or if the user specified a 0 value,
5151 // we don't have to add a PTX directive.
5152 if (Attr->getMinBlocks()) {
5153 llvm::APSInt MinBlocks(32);
5154 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5155 if (MinBlocks > 0)
5156 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5157 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005158 }
5159 }
Justin Holewinski38031972011-10-05 17:58:44 +00005160 }
5161}
5162
Eli Benderskye06a2c42014-04-15 16:57:05 +00005163void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5164 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005165 llvm::Module *M = F->getParent();
5166 llvm::LLVMContext &Ctx = M->getContext();
5167
5168 // Get "nvvm.annotations" metadata node
5169 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5170
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005171 llvm::Metadata *MDVals[] = {
5172 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5173 llvm::ConstantAsMetadata::get(
5174 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005175 // Append metadata to nvvm.annotations
5176 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5177}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005178}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005179
5180//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005181// SystemZ ABI Implementation
5182//===----------------------------------------------------------------------===//
5183
5184namespace {
5185
5186class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005187 bool HasVector;
5188
Ulrich Weigand47445072013-05-06 16:26:41 +00005189public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005190 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5191 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005192
5193 bool isPromotableIntegerType(QualType Ty) const;
5194 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005195 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005196 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005197 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005198
5199 ABIArgInfo classifyReturnType(QualType RetTy) const;
5200 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5201
Craig Topper4f12f102014-03-12 06:41:41 +00005202 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005203 if (!getCXXABI().classifyReturnType(FI))
5204 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005205 for (auto &I : FI.arguments())
5206 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005207 }
5208
Craig Topper4f12f102014-03-12 06:41:41 +00005209 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5210 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005211};
5212
5213class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5214public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005215 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5216 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005217};
5218
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005219}
Ulrich Weigand47445072013-05-06 16:26:41 +00005220
5221bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5222 // Treat an enum type as its underlying type.
5223 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5224 Ty = EnumTy->getDecl()->getIntegerType();
5225
5226 // Promotable integer types are required to be promoted by the ABI.
5227 if (Ty->isPromotableIntegerType())
5228 return true;
5229
5230 // 32-bit values must also be promoted.
5231 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5232 switch (BT->getKind()) {
5233 case BuiltinType::Int:
5234 case BuiltinType::UInt:
5235 return true;
5236 default:
5237 return false;
5238 }
5239 return false;
5240}
5241
5242bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005243 return (Ty->isAnyComplexType() ||
5244 Ty->isVectorType() ||
5245 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005246}
5247
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005248bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5249 return (HasVector &&
5250 Ty->isVectorType() &&
5251 getContext().getTypeSize(Ty) <= 128);
5252}
5253
Ulrich Weigand47445072013-05-06 16:26:41 +00005254bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5255 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5256 switch (BT->getKind()) {
5257 case BuiltinType::Float:
5258 case BuiltinType::Double:
5259 return true;
5260 default:
5261 return false;
5262 }
5263
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005264 return false;
5265}
5266
5267QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005268 if (const RecordType *RT = Ty->getAsStructureType()) {
5269 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005270 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005271
5272 // If this is a C++ record, check the bases first.
5273 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005274 for (const auto &I : CXXRD->bases()) {
5275 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005276
5277 // Empty bases don't affect things either way.
5278 if (isEmptyRecord(getContext(), Base, true))
5279 continue;
5280
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005281 if (!Found.isNull())
5282 return Ty;
5283 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005284 }
5285
5286 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005287 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005288 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005289 // Unlike isSingleElementStruct(), empty structure and array fields
5290 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005291 if (getContext().getLangOpts().CPlusPlus &&
5292 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5293 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005294
5295 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005296 // Nested structures still do though.
5297 if (!Found.isNull())
5298 return Ty;
5299 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005300 }
5301
5302 // Unlike isSingleElementStruct(), trailing padding is allowed.
5303 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005304 if (!Found.isNull())
5305 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005306 }
5307
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005308 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005309}
5310
5311llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5312 CodeGenFunction &CGF) const {
5313 // Assume that va_list type is correct; should be pointer to LLVM type:
5314 // struct {
5315 // i64 __gpr;
5316 // i64 __fpr;
5317 // i8 *__overflow_arg_area;
5318 // i8 *__reg_save_area;
5319 // };
5320
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005321 // Every non-vector argument occupies 8 bytes and is passed by preference
5322 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5323 // always passed on the stack.
Ulrich Weigand47445072013-05-06 16:26:41 +00005324 Ty = CGF.getContext().getCanonicalType(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005325 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
5326 llvm::Type *APTy = llvm::PointerType::getUnqual(ArgTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005327 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005328 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005329 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005330 bool IsVector = false;
Ulrich Weigand47445072013-05-06 16:26:41 +00005331 unsigned UnpaddedBitSize;
5332 if (IsIndirect) {
5333 APTy = llvm::PointerType::getUnqual(APTy);
5334 UnpaddedBitSize = 64;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005335 } else {
5336 if (AI.getCoerceToType())
5337 ArgTy = AI.getCoerceToType();
5338 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005339 IsVector = ArgTy->isVectorTy();
Ulrich Weigand47445072013-05-06 16:26:41 +00005340 UnpaddedBitSize = getContext().getTypeSize(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005341 }
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005342 unsigned PaddedBitSize = (IsVector && UnpaddedBitSize > 64) ? 128 : 64;
Ulrich Weigand47445072013-05-06 16:26:41 +00005343 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5344
5345 unsigned PaddedSize = PaddedBitSize / 8;
5346 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5347
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005348 llvm::Type *IndexTy = CGF.Int64Ty;
5349 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5350
5351 if (IsVector) {
5352 // Work out the address of a vector argument on the stack.
5353 // Vector arguments are always passed in the high bits of a
5354 // single (8 byte) or double (16 byte) stack slot.
5355 llvm::Value *OverflowArgAreaPtr =
5356 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 2,
5357 "overflow_arg_area_ptr");
5358 llvm::Value *OverflowArgArea =
5359 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5360 llvm::Value *MemAddr =
5361 CGF.Builder.CreateBitCast(OverflowArgArea, APTy, "mem_addr");
5362
5363 // Update overflow_arg_area_ptr pointer
5364 llvm::Value *NewOverflowArgArea =
5365 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5366 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5367
5368 return MemAddr;
5369 }
5370
Ulrich Weigand47445072013-05-06 16:26:41 +00005371 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5372 if (InFPRs) {
5373 MaxRegs = 4; // Maximum of 4 FPR arguments
5374 RegCountField = 1; // __fpr
5375 RegSaveIndex = 16; // save offset for f0
5376 RegPadding = 0; // floats are passed in the high bits of an FPR
5377 } else {
5378 MaxRegs = 5; // Maximum of 5 GPR arguments
5379 RegCountField = 0; // __gpr
5380 RegSaveIndex = 2; // save offset for r2
5381 RegPadding = Padding; // values are passed in the low bits of a GPR
5382 }
5383
David Blaikie2e804282015-04-05 22:47:07 +00005384 llvm::Value *RegCountPtr = CGF.Builder.CreateStructGEP(
5385 nullptr, VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005386 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005387 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5388 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005389 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005390
5391 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5392 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5393 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5394 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5395
5396 // Emit code to load the value if it was passed in registers.
5397 CGF.EmitBlock(InRegBlock);
5398
5399 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005400 llvm::Value *ScaledRegCount =
5401 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5402 llvm::Value *RegBase =
5403 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5404 llvm::Value *RegOffset =
5405 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5406 llvm::Value *RegSaveAreaPtr =
David Blaikie2e804282015-04-05 22:47:07 +00005407 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005408 llvm::Value *RegSaveArea =
5409 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5410 llvm::Value *RawRegAddr =
5411 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5412 llvm::Value *RegAddr =
5413 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5414
5415 // Update the register count
5416 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5417 llvm::Value *NewRegCount =
5418 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5419 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5420 CGF.EmitBranch(ContBlock);
5421
5422 // Emit code to load the value if it was passed in memory.
5423 CGF.EmitBlock(InMemBlock);
5424
5425 // Work out the address of a stack argument.
David Blaikie2e804282015-04-05 22:47:07 +00005426 llvm::Value *OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5427 nullptr, VAListAddr, 2, "overflow_arg_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005428 llvm::Value *OverflowArgArea =
5429 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5430 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5431 llvm::Value *RawMemAddr =
5432 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5433 llvm::Value *MemAddr =
5434 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5435
5436 // Update overflow_arg_area_ptr pointer
5437 llvm::Value *NewOverflowArgArea =
5438 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5439 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5440 CGF.EmitBranch(ContBlock);
5441
5442 // Return the appropriate result.
5443 CGF.EmitBlock(ContBlock);
5444 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5445 ResAddr->addIncoming(RegAddr, InRegBlock);
5446 ResAddr->addIncoming(MemAddr, InMemBlock);
5447
5448 if (IsIndirect)
5449 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5450
5451 return ResAddr;
5452}
5453
Ulrich Weigand47445072013-05-06 16:26:41 +00005454ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5455 if (RetTy->isVoidType())
5456 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005457 if (isVectorArgumentType(RetTy))
5458 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005459 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5460 return ABIArgInfo::getIndirect(0);
5461 return (isPromotableIntegerType(RetTy) ?
5462 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5463}
5464
5465ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5466 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005467 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005468 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5469
5470 // Integers and enums are extended to full register width.
5471 if (isPromotableIntegerType(Ty))
5472 return ABIArgInfo::getExtend();
5473
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005474 // Handle vector types and vector-like structure types. Note that
5475 // as opposed to float-like structure types, we do not allow any
5476 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005477 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005478 QualType SingleElementTy = GetSingleElementType(Ty);
5479 if (isVectorArgumentType(SingleElementTy) &&
5480 getContext().getTypeSize(SingleElementTy) == Size)
5481 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5482
5483 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005484 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005485 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005486
5487 // Handle small structures.
5488 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5489 // Structures with flexible arrays have variable length, so really
5490 // fail the size test above.
5491 const RecordDecl *RD = RT->getDecl();
5492 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005493 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005494
5495 // The structure is passed as an unextended integer, a float, or a double.
5496 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005497 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005498 assert(Size == 32 || Size == 64);
5499 if (Size == 32)
5500 PassTy = llvm::Type::getFloatTy(getVMContext());
5501 else
5502 PassTy = llvm::Type::getDoubleTy(getVMContext());
5503 } else
5504 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5505 return ABIArgInfo::getDirect(PassTy);
5506 }
5507
5508 // Non-structure compounds are passed indirectly.
5509 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005510 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005511
Craig Topper8a13c412014-05-21 05:09:00 +00005512 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005513}
5514
5515//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005516// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005517//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005518
5519namespace {
5520
5521class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5522public:
Chris Lattner2b037972010-07-29 02:01:43 +00005523 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5524 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005525 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005526 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005527};
5528
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005529}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005530
Eric Christopher162c91c2015-06-05 22:03:00 +00005531void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005532 llvm::GlobalValue *GV,
5533 CodeGen::CodeGenModule &M) const {
5534 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5535 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5536 // Handle 'interrupt' attribute:
5537 llvm::Function *F = cast<llvm::Function>(GV);
5538
5539 // Step 1: Set ISR calling convention.
5540 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5541
5542 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005543 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005544
5545 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005546 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005547 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5548 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005549 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005550 }
5551}
5552
Chris Lattner0cf24192010-06-28 20:05:43 +00005553//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005554// MIPS ABI Implementation. This works for both little-endian and
5555// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005556//===----------------------------------------------------------------------===//
5557
John McCall943fae92010-05-27 06:19:26 +00005558namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005559class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005560 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005561 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5562 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005563 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005564 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005565 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005566 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005567public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005568 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005569 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005570 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005571
5572 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005573 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005574 void computeInfo(CGFunctionInfo &FI) const override;
5575 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5576 CodeGenFunction &CGF) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005577 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005578};
5579
John McCall943fae92010-05-27 06:19:26 +00005580class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005581 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005582public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005583 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5584 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005585 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005586
Craig Topper4f12f102014-03-12 06:41:41 +00005587 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005588 return 29;
5589 }
5590
Eric Christopher162c91c2015-06-05 22:03:00 +00005591 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005592 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005593 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5594 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005595 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005596 if (FD->hasAttr<Mips16Attr>()) {
5597 Fn->addFnAttr("mips16");
5598 }
5599 else if (FD->hasAttr<NoMips16Attr>()) {
5600 Fn->addFnAttr("nomips16");
5601 }
Reed Kotler373feca2013-01-16 17:10:28 +00005602 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005603
John McCall943fae92010-05-27 06:19:26 +00005604 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005605 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005606
Craig Topper4f12f102014-03-12 06:41:41 +00005607 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005608 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005609 }
John McCall943fae92010-05-27 06:19:26 +00005610};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005611}
John McCall943fae92010-05-27 06:19:26 +00005612
Eric Christopher7565e0d2015-05-29 23:09:49 +00005613void MipsABIInfo::CoerceToIntArgs(
5614 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005615 llvm::IntegerType *IntTy =
5616 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005617
5618 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5619 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5620 ArgList.push_back(IntTy);
5621
5622 // If necessary, add one more integer type to ArgList.
5623 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5624
5625 if (R)
5626 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005627}
5628
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005629// In N32/64, an aligned double precision floating point field is passed in
5630// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005631llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005632 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5633
5634 if (IsO32) {
5635 CoerceToIntArgs(TySize, ArgList);
5636 return llvm::StructType::get(getVMContext(), ArgList);
5637 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005638
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005639 if (Ty->isComplexType())
5640 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005641
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005642 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005643
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005644 // Unions/vectors are passed in integer registers.
5645 if (!RT || !RT->isStructureOrClassType()) {
5646 CoerceToIntArgs(TySize, ArgList);
5647 return llvm::StructType::get(getVMContext(), ArgList);
5648 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005649
5650 const RecordDecl *RD = RT->getDecl();
5651 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005652 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00005653
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005654 uint64_t LastOffset = 0;
5655 unsigned idx = 0;
5656 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5657
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005658 // Iterate over fields in the struct/class and check if there are any aligned
5659 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005660 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5661 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005662 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005663 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5664
5665 if (!BT || BT->getKind() != BuiltinType::Double)
5666 continue;
5667
5668 uint64_t Offset = Layout.getFieldOffset(idx);
5669 if (Offset % 64) // Ignore doubles that are not aligned.
5670 continue;
5671
5672 // Add ((Offset - LastOffset) / 64) args of type i64.
5673 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5674 ArgList.push_back(I64);
5675
5676 // Add double type.
5677 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5678 LastOffset = Offset + 64;
5679 }
5680
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005681 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5682 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005683
5684 return llvm::StructType::get(getVMContext(), ArgList);
5685}
5686
Akira Hatanakaddd66342013-10-29 18:41:15 +00005687llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5688 uint64_t Offset) const {
5689 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005690 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005691
Akira Hatanakaddd66342013-10-29 18:41:15 +00005692 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005693}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005694
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005695ABIArgInfo
5696MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005697 Ty = useFirstFieldIfTransparentUnion(Ty);
5698
Akira Hatanaka1632af62012-01-09 19:31:25 +00005699 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005700 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005701 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005702
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005703 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5704 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005705 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5706 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005707
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005708 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005709 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005710 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005711 return ABIArgInfo::getIgnore();
5712
Mark Lacey3825e832013-10-06 01:33:34 +00005713 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005714 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005715 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005716 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005717
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005718 // If we have reached here, aggregates are passed directly by coercing to
5719 // another structure type. Padding is inserted if the offset of the
5720 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005721 ABIArgInfo ArgInfo =
5722 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5723 getPaddingType(OrigOffset, CurrOffset));
5724 ArgInfo.setInReg(true);
5725 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005726 }
5727
5728 // Treat an enum type as its underlying type.
5729 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5730 Ty = EnumTy->getDecl()->getIntegerType();
5731
Daniel Sanders5b445b32014-10-24 14:42:42 +00005732 // All integral types are promoted to the GPR width.
5733 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005734 return ABIArgInfo::getExtend();
5735
Akira Hatanakaddd66342013-10-29 18:41:15 +00005736 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005737 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005738}
5739
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005740llvm::Type*
5741MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005742 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005743 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005744
Akira Hatanakab6f74432012-02-09 18:49:26 +00005745 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005746 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005747 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5748 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005749
Akira Hatanakab6f74432012-02-09 18:49:26 +00005750 // N32/64 returns struct/classes in floating point registers if the
5751 // following conditions are met:
5752 // 1. The size of the struct/class is no larger than 128-bit.
5753 // 2. The struct/class has one or two fields all of which are floating
5754 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005755 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00005756 //
5757 // Any other composite results are returned in integer registers.
5758 //
5759 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5760 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5761 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005762 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005763
Akira Hatanakab6f74432012-02-09 18:49:26 +00005764 if (!BT || !BT->isFloatingPoint())
5765 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005766
David Blaikie2d7c57e2012-04-30 02:36:29 +00005767 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005768 }
5769
5770 if (b == e)
5771 return llvm::StructType::get(getVMContext(), RTList,
5772 RD->hasAttr<PackedAttr>());
5773
5774 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005775 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005776 }
5777
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005778 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005779 return llvm::StructType::get(getVMContext(), RTList);
5780}
5781
Akira Hatanakab579fe52011-06-02 00:09:17 +00005782ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005783 uint64_t Size = getContext().getTypeSize(RetTy);
5784
Daniel Sandersed39f582014-09-04 13:28:14 +00005785 if (RetTy->isVoidType())
5786 return ABIArgInfo::getIgnore();
5787
5788 // O32 doesn't treat zero-sized structs differently from other structs.
5789 // However, N32/N64 ignores zero sized return values.
5790 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005791 return ABIArgInfo::getIgnore();
5792
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005793 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005794 if (Size <= 128) {
5795 if (RetTy->isAnyComplexType())
5796 return ABIArgInfo::getDirect();
5797
Daniel Sanderse5018b62014-09-04 15:05:39 +00005798 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005799 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005800 if (!IsO32 ||
5801 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5802 ABIArgInfo ArgInfo =
5803 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5804 ArgInfo.setInReg(true);
5805 return ArgInfo;
5806 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005807 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005808
5809 return ABIArgInfo::getIndirect(0);
5810 }
5811
5812 // Treat an enum type as its underlying type.
5813 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5814 RetTy = EnumTy->getDecl()->getIntegerType();
5815
5816 return (RetTy->isPromotableIntegerType() ?
5817 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5818}
5819
5820void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005821 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005822 if (!getCXXABI().classifyReturnType(FI))
5823 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005824
Eric Christopher7565e0d2015-05-29 23:09:49 +00005825 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005826 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005827
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005828 for (auto &I : FI.arguments())
5829 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005830}
5831
5832llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5833 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005834 llvm::Type *BP = CGF.Int8PtrTy;
5835 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005836
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005837 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5838 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005839 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005840 unsigned PtrWidth = getTarget().getPointerWidth(0);
5841 if ((Ty->isIntegerType() &&
5842 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5843 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005844 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5845 Ty->isSignedIntegerType());
5846 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00005847
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005848 CGBuilderTy &Builder = CGF.Builder;
5849 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5850 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005851 int64_t TypeAlign =
5852 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005853 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5854 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005855 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5856
5857 if (TypeAlign > MinABIStackAlignInBytes) {
5858 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5859 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5860 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5861 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5862 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5863 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5864 }
5865 else
Eric Christopher7565e0d2015-05-29 23:09:49 +00005866 AddrTyped = Builder.CreateBitCast(Addr, PTy);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005867
5868 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5869 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005870 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5871 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005872 llvm::Value *NextAddr =
5873 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5874 "ap.next");
5875 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005876
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005877 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005878}
5879
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005880bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
5881 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005882
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005883 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
5884 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
5885 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00005886
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005887 return false;
5888}
5889
John McCall943fae92010-05-27 06:19:26 +00005890bool
5891MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5892 llvm::Value *Address) const {
5893 // This information comes from gcc's implementation, which seems to
5894 // as canonical as it gets.
5895
John McCall943fae92010-05-27 06:19:26 +00005896 // Everything on MIPS is 4 bytes. Double-precision FP registers
5897 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005898 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005899
5900 // 0-31 are the general purpose registers, $0 - $31.
5901 // 32-63 are the floating-point registers, $f0 - $f31.
5902 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5903 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005904 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005905
5906 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5907 // They are one bit wide and ignored here.
5908
5909 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5910 // (coprocessor 1 is the FP unit)
5911 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5912 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5913 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005914 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005915 return false;
5916}
5917
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005918//===----------------------------------------------------------------------===//
5919// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005920// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005921// handling.
5922//===----------------------------------------------------------------------===//
5923
5924namespace {
5925
5926class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5927public:
5928 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5929 : DefaultTargetCodeGenInfo(CGT) {}
5930
Eric Christopher162c91c2015-06-05 22:03:00 +00005931 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005932 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005933};
5934
Eric Christopher162c91c2015-06-05 22:03:00 +00005935void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00005936 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005937 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5938 if (!FD) return;
5939
5940 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005941
David Blaikiebbafb8a2012-03-11 07:00:24 +00005942 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005943 if (FD->hasAttr<OpenCLKernelAttr>()) {
5944 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005945 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005946 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5947 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005948 // Convert the reqd_work_group_size() attributes to metadata.
5949 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00005950 llvm::NamedMDNode *OpenCLMetadata =
5951 M.getModule().getOrInsertNamedMetadata(
5952 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005953
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005954 SmallVector<llvm::Metadata *, 5> Operands;
5955 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005956
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005957 Operands.push_back(
5958 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5959 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5960 Operands.push_back(
5961 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5962 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5963 Operands.push_back(
5964 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5965 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005966
Eric Christopher7565e0d2015-05-29 23:09:49 +00005967 // Add a boolean constant operand for "required" (true) or "hint"
5968 // (false) for implementing the work_group_size_hint attr later.
5969 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005970 Operands.push_back(
5971 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005972 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5973 }
5974 }
5975 }
5976}
5977
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005978}
John McCall943fae92010-05-27 06:19:26 +00005979
Tony Linthicum76329bf2011-12-12 21:14:55 +00005980//===----------------------------------------------------------------------===//
5981// Hexagon ABI Implementation
5982//===----------------------------------------------------------------------===//
5983
5984namespace {
5985
5986class HexagonABIInfo : public ABIInfo {
5987
5988
5989public:
5990 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5991
5992private:
5993
5994 ABIArgInfo classifyReturnType(QualType RetTy) const;
5995 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5996
Craig Topper4f12f102014-03-12 06:41:41 +00005997 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005998
Craig Topper4f12f102014-03-12 06:41:41 +00005999 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6000 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006001};
6002
6003class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6004public:
6005 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6006 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6007
Craig Topper4f12f102014-03-12 06:41:41 +00006008 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006009 return 29;
6010 }
6011};
6012
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006013}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006014
6015void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006016 if (!getCXXABI().classifyReturnType(FI))
6017 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006018 for (auto &I : FI.arguments())
6019 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006020}
6021
6022ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6023 if (!isAggregateTypeForABI(Ty)) {
6024 // Treat an enum type as its underlying type.
6025 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6026 Ty = EnumTy->getDecl()->getIntegerType();
6027
6028 return (Ty->isPromotableIntegerType() ?
6029 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6030 }
6031
6032 // Ignore empty records.
6033 if (isEmptyRecord(getContext(), Ty, true))
6034 return ABIArgInfo::getIgnore();
6035
Mark Lacey3825e832013-10-06 01:33:34 +00006036 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00006037 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006038
6039 uint64_t Size = getContext().getTypeSize(Ty);
6040 if (Size > 64)
6041 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6042 // Pass in the smallest viable integer type.
6043 else if (Size > 32)
6044 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6045 else if (Size > 16)
6046 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6047 else if (Size > 8)
6048 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6049 else
6050 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6051}
6052
6053ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6054 if (RetTy->isVoidType())
6055 return ABIArgInfo::getIgnore();
6056
6057 // Large vector types should be returned via memory.
6058 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6059 return ABIArgInfo::getIndirect(0);
6060
6061 if (!isAggregateTypeForABI(RetTy)) {
6062 // Treat an enum type as its underlying type.
6063 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6064 RetTy = EnumTy->getDecl()->getIntegerType();
6065
6066 return (RetTy->isPromotableIntegerType() ?
6067 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6068 }
6069
Tony Linthicum76329bf2011-12-12 21:14:55 +00006070 if (isEmptyRecord(getContext(), RetTy, true))
6071 return ABIArgInfo::getIgnore();
6072
6073 // Aggregates <= 8 bytes are returned in r0; other aggregates
6074 // are returned indirectly.
6075 uint64_t Size = getContext().getTypeSize(RetTy);
6076 if (Size <= 64) {
6077 // Return in the smallest viable integer type.
6078 if (Size <= 8)
6079 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6080 if (Size <= 16)
6081 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6082 if (Size <= 32)
6083 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6084 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6085 }
6086
6087 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6088}
6089
6090llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006091 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006092 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006093 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006094
6095 CGBuilderTy &Builder = CGF.Builder;
6096 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6097 "ap");
6098 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6099 llvm::Type *PTy =
6100 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6101 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6102
6103 uint64_t Offset =
6104 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6105 llvm::Value *NextAddr =
6106 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6107 "ap.next");
6108 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6109
6110 return AddrTyped;
6111}
6112
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006113//===----------------------------------------------------------------------===//
6114// AMDGPU ABI Implementation
6115//===----------------------------------------------------------------------===//
6116
6117namespace {
6118
6119class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6120public:
6121 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6122 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006123 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006124 CodeGen::CodeGenModule &M) const override;
6125};
6126
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006127}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006128
Eric Christopher162c91c2015-06-05 22:03:00 +00006129void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006130 const Decl *D,
6131 llvm::GlobalValue *GV,
6132 CodeGen::CodeGenModule &M) const {
6133 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6134 if (!FD)
6135 return;
6136
6137 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6138 llvm::Function *F = cast<llvm::Function>(GV);
6139 uint32_t NumVGPR = Attr->getNumVGPR();
6140 if (NumVGPR != 0)
6141 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6142 }
6143
6144 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6145 llvm::Function *F = cast<llvm::Function>(GV);
6146 unsigned NumSGPR = Attr->getNumSGPR();
6147 if (NumSGPR != 0)
6148 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6149 }
6150}
6151
Tony Linthicum76329bf2011-12-12 21:14:55 +00006152
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006153//===----------------------------------------------------------------------===//
6154// SPARC v9 ABI Implementation.
6155// Based on the SPARC Compliance Definition version 2.4.1.
6156//
6157// Function arguments a mapped to a nominal "parameter array" and promoted to
6158// registers depending on their type. Each argument occupies 8 or 16 bytes in
6159// the array, structs larger than 16 bytes are passed indirectly.
6160//
6161// One case requires special care:
6162//
6163// struct mixed {
6164// int i;
6165// float f;
6166// };
6167//
6168// When a struct mixed is passed by value, it only occupies 8 bytes in the
6169// parameter array, but the int is passed in an integer register, and the float
6170// is passed in a floating point register. This is represented as two arguments
6171// with the LLVM IR inreg attribute:
6172//
6173// declare void f(i32 inreg %i, float inreg %f)
6174//
6175// The code generator will only allocate 4 bytes from the parameter array for
6176// the inreg arguments. All other arguments are allocated a multiple of 8
6177// bytes.
6178//
6179namespace {
6180class SparcV9ABIInfo : public ABIInfo {
6181public:
6182 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6183
6184private:
6185 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006186 void computeInfo(CGFunctionInfo &FI) const override;
6187 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6188 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006189
6190 // Coercion type builder for structs passed in registers. The coercion type
6191 // serves two purposes:
6192 //
6193 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6194 // in registers.
6195 // 2. Expose aligned floating point elements as first-level elements, so the
6196 // code generator knows to pass them in floating point registers.
6197 //
6198 // We also compute the InReg flag which indicates that the struct contains
6199 // aligned 32-bit floats.
6200 //
6201 struct CoerceBuilder {
6202 llvm::LLVMContext &Context;
6203 const llvm::DataLayout &DL;
6204 SmallVector<llvm::Type*, 8> Elems;
6205 uint64_t Size;
6206 bool InReg;
6207
6208 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6209 : Context(c), DL(dl), Size(0), InReg(false) {}
6210
6211 // Pad Elems with integers until Size is ToSize.
6212 void pad(uint64_t ToSize) {
6213 assert(ToSize >= Size && "Cannot remove elements");
6214 if (ToSize == Size)
6215 return;
6216
6217 // Finish the current 64-bit word.
6218 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6219 if (Aligned > Size && Aligned <= ToSize) {
6220 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6221 Size = Aligned;
6222 }
6223
6224 // Add whole 64-bit words.
6225 while (Size + 64 <= ToSize) {
6226 Elems.push_back(llvm::Type::getInt64Ty(Context));
6227 Size += 64;
6228 }
6229
6230 // Final in-word padding.
6231 if (Size < ToSize) {
6232 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6233 Size = ToSize;
6234 }
6235 }
6236
6237 // Add a floating point element at Offset.
6238 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6239 // Unaligned floats are treated as integers.
6240 if (Offset % Bits)
6241 return;
6242 // The InReg flag is only required if there are any floats < 64 bits.
6243 if (Bits < 64)
6244 InReg = true;
6245 pad(Offset);
6246 Elems.push_back(Ty);
6247 Size = Offset + Bits;
6248 }
6249
6250 // Add a struct type to the coercion type, starting at Offset (in bits).
6251 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6252 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6253 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6254 llvm::Type *ElemTy = StrTy->getElementType(i);
6255 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6256 switch (ElemTy->getTypeID()) {
6257 case llvm::Type::StructTyID:
6258 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6259 break;
6260 case llvm::Type::FloatTyID:
6261 addFloat(ElemOffset, ElemTy, 32);
6262 break;
6263 case llvm::Type::DoubleTyID:
6264 addFloat(ElemOffset, ElemTy, 64);
6265 break;
6266 case llvm::Type::FP128TyID:
6267 addFloat(ElemOffset, ElemTy, 128);
6268 break;
6269 case llvm::Type::PointerTyID:
6270 if (ElemOffset % 64 == 0) {
6271 pad(ElemOffset);
6272 Elems.push_back(ElemTy);
6273 Size += 64;
6274 }
6275 break;
6276 default:
6277 break;
6278 }
6279 }
6280 }
6281
6282 // Check if Ty is a usable substitute for the coercion type.
6283 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006284 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006285 }
6286
6287 // Get the coercion type as a literal struct type.
6288 llvm::Type *getType() const {
6289 if (Elems.size() == 1)
6290 return Elems.front();
6291 else
6292 return llvm::StructType::get(Context, Elems);
6293 }
6294 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006295};
6296} // end anonymous namespace
6297
6298ABIArgInfo
6299SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6300 if (Ty->isVoidType())
6301 return ABIArgInfo::getIgnore();
6302
6303 uint64_t Size = getContext().getTypeSize(Ty);
6304
6305 // Anything too big to fit in registers is passed with an explicit indirect
6306 // pointer / sret pointer.
6307 if (Size > SizeLimit)
6308 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6309
6310 // Treat an enum type as its underlying type.
6311 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6312 Ty = EnumTy->getDecl()->getIntegerType();
6313
6314 // Integer types smaller than a register are extended.
6315 if (Size < 64 && Ty->isIntegerType())
6316 return ABIArgInfo::getExtend();
6317
6318 // Other non-aggregates go in registers.
6319 if (!isAggregateTypeForABI(Ty))
6320 return ABIArgInfo::getDirect();
6321
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006322 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6323 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6324 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6325 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6326
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006327 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006328 // Build a coercion type from the LLVM struct type.
6329 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6330 if (!StrTy)
6331 return ABIArgInfo::getDirect();
6332
6333 CoerceBuilder CB(getVMContext(), getDataLayout());
6334 CB.addStruct(0, StrTy);
6335 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6336
6337 // Try to use the original type for coercion.
6338 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6339
6340 if (CB.InReg)
6341 return ABIArgInfo::getDirectInReg(CoerceTy);
6342 else
6343 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006344}
6345
6346llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6347 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006348 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6349 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6350 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6351 AI.setCoerceToType(ArgTy);
6352
6353 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6354 CGBuilderTy &Builder = CGF.Builder;
6355 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6356 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6357 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6358 llvm::Value *ArgAddr;
6359 unsigned Stride;
6360
6361 switch (AI.getKind()) {
6362 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006363 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006364 llvm_unreachable("Unsupported ABI kind for va_arg");
6365
6366 case ABIArgInfo::Extend:
6367 Stride = 8;
6368 ArgAddr = Builder
6369 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6370 "extend");
6371 break;
6372
6373 case ABIArgInfo::Direct:
6374 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6375 ArgAddr = Addr;
6376 break;
6377
6378 case ABIArgInfo::Indirect:
6379 Stride = 8;
6380 ArgAddr = Builder.CreateBitCast(Addr,
6381 llvm::PointerType::getUnqual(ArgPtrTy),
6382 "indirect");
6383 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6384 break;
6385
6386 case ABIArgInfo::Ignore:
6387 return llvm::UndefValue::get(ArgPtrTy);
6388 }
6389
6390 // Update VAList.
6391 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6392 Builder.CreateStore(Addr, VAListAddrAsBPP);
6393
6394 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006395}
6396
6397void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6398 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006399 for (auto &I : FI.arguments())
6400 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006401}
6402
6403namespace {
6404class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6405public:
6406 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6407 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006408
Craig Topper4f12f102014-03-12 06:41:41 +00006409 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006410 return 14;
6411 }
6412
6413 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006414 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006415};
6416} // end anonymous namespace
6417
Roman Divackyf02c9942014-02-24 18:46:27 +00006418bool
6419SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6420 llvm::Value *Address) const {
6421 // This is calculated from the LLVM and GCC tables and verified
6422 // against gcc output. AFAIK all ABIs use the same encoding.
6423
6424 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6425
6426 llvm::IntegerType *i8 = CGF.Int8Ty;
6427 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6428 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6429
6430 // 0-31: the 8-byte general-purpose registers
6431 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6432
6433 // 32-63: f0-31, the 4-byte floating-point registers
6434 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6435
6436 // Y = 64
6437 // PSR = 65
6438 // WIM = 66
6439 // TBR = 67
6440 // PC = 68
6441 // NPC = 69
6442 // FSR = 70
6443 // CSR = 71
6444 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006445
Roman Divackyf02c9942014-02-24 18:46:27 +00006446 // 72-87: d0-15, the 8-byte floating-point registers
6447 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6448
6449 return false;
6450}
6451
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006452
Robert Lytton0e076492013-08-13 09:43:10 +00006453//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006454// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006455//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006456
Robert Lytton0e076492013-08-13 09:43:10 +00006457namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006458
6459/// A SmallStringEnc instance is used to build up the TypeString by passing
6460/// it by reference between functions that append to it.
6461typedef llvm::SmallString<128> SmallStringEnc;
6462
6463/// TypeStringCache caches the meta encodings of Types.
6464///
6465/// The reason for caching TypeStrings is two fold:
6466/// 1. To cache a type's encoding for later uses;
6467/// 2. As a means to break recursive member type inclusion.
6468///
6469/// A cache Entry can have a Status of:
6470/// NonRecursive: The type encoding is not recursive;
6471/// Recursive: The type encoding is recursive;
6472/// Incomplete: An incomplete TypeString;
6473/// IncompleteUsed: An incomplete TypeString that has been used in a
6474/// Recursive type encoding.
6475///
6476/// A NonRecursive entry will have all of its sub-members expanded as fully
6477/// as possible. Whilst it may contain types which are recursive, the type
6478/// itself is not recursive and thus its encoding may be safely used whenever
6479/// the type is encountered.
6480///
6481/// A Recursive entry will have all of its sub-members expanded as fully as
6482/// possible. The type itself is recursive and it may contain other types which
6483/// are recursive. The Recursive encoding must not be used during the expansion
6484/// of a recursive type's recursive branch. For simplicity the code uses
6485/// IncompleteCount to reject all usage of Recursive encodings for member types.
6486///
6487/// An Incomplete entry is always a RecordType and only encodes its
6488/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6489/// are placed into the cache during type expansion as a means to identify and
6490/// handle recursive inclusion of types as sub-members. If there is recursion
6491/// the entry becomes IncompleteUsed.
6492///
6493/// During the expansion of a RecordType's members:
6494///
6495/// If the cache contains a NonRecursive encoding for the member type, the
6496/// cached encoding is used;
6497///
6498/// If the cache contains a Recursive encoding for the member type, the
6499/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6500///
6501/// If the member is a RecordType, an Incomplete encoding is placed into the
6502/// cache to break potential recursive inclusion of itself as a sub-member;
6503///
6504/// Once a member RecordType has been expanded, its temporary incomplete
6505/// entry is removed from the cache. If a Recursive encoding was swapped out
6506/// it is swapped back in;
6507///
6508/// If an incomplete entry is used to expand a sub-member, the incomplete
6509/// entry is marked as IncompleteUsed. The cache keeps count of how many
6510/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6511///
6512/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6513/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6514/// Else the member is part of a recursive type and thus the recursion has
6515/// been exited too soon for the encoding to be correct for the member.
6516///
6517class TypeStringCache {
6518 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6519 struct Entry {
6520 std::string Str; // The encoded TypeString for the type.
6521 enum Status State; // Information about the encoding in 'Str'.
6522 std::string Swapped; // A temporary place holder for a Recursive encoding
6523 // during the expansion of RecordType's members.
6524 };
6525 std::map<const IdentifierInfo *, struct Entry> Map;
6526 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6527 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6528public:
Robert Lyttond263f142014-05-06 09:38:54 +00006529 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006530 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6531 bool removeIncomplete(const IdentifierInfo *ID);
6532 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6533 bool IsRecursive);
6534 StringRef lookupStr(const IdentifierInfo *ID);
6535};
6536
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006537/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006538/// FieldEncoding is a helper for this ordering process.
6539class FieldEncoding {
6540 bool HasName;
6541 std::string Enc;
6542public:
6543 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6544 StringRef str() {return Enc.c_str();};
6545 bool operator<(const FieldEncoding &rhs) const {
6546 if (HasName != rhs.HasName) return HasName;
6547 return Enc < rhs.Enc;
6548 }
6549};
6550
Robert Lytton7d1db152013-08-19 09:46:39 +00006551class XCoreABIInfo : public DefaultABIInfo {
6552public:
6553 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006554 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6555 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006556};
6557
Robert Lyttond21e2d72014-03-03 13:45:29 +00006558class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006559 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006560public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006561 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006562 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006563 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6564 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006565};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006566
Robert Lytton2d196952013-10-11 10:29:34 +00006567} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006568
Robert Lytton7d1db152013-08-19 09:46:39 +00006569llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6570 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006571 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006572
Robert Lytton2d196952013-10-11 10:29:34 +00006573 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006574 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6575 CGF.Int8PtrPtrTy);
6576 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006577
Robert Lytton2d196952013-10-11 10:29:34 +00006578 // Handle the argument.
6579 ABIArgInfo AI = classifyArgumentType(Ty);
6580 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6581 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6582 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006583 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006584 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006585 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006586 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006587 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006588 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006589 llvm_unreachable("Unsupported ABI kind for va_arg");
6590 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006591 Val = llvm::UndefValue::get(ArgPtrTy);
6592 ArgSize = 0;
6593 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006594 case ABIArgInfo::Extend:
6595 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006596 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6597 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6598 if (ArgSize < 4)
6599 ArgSize = 4;
6600 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006601 case ABIArgInfo::Indirect:
6602 llvm::Value *ArgAddr;
6603 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6604 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006605 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6606 ArgSize = 4;
6607 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006608 }
Robert Lytton2d196952013-10-11 10:29:34 +00006609
6610 // Increment the VAList.
6611 if (ArgSize) {
6612 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6613 Builder.CreateStore(APN, VAListAddrAsBPP);
6614 }
6615 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006616}
Robert Lytton0e076492013-08-13 09:43:10 +00006617
Robert Lytton844aeeb2014-05-02 09:33:20 +00006618/// During the expansion of a RecordType, an incomplete TypeString is placed
6619/// into the cache as a means to identify and break recursion.
6620/// If there is a Recursive encoding in the cache, it is swapped out and will
6621/// be reinserted by removeIncomplete().
6622/// All other types of encoding should have been used rather than arriving here.
6623void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6624 std::string StubEnc) {
6625 if (!ID)
6626 return;
6627 Entry &E = Map[ID];
6628 assert( (E.Str.empty() || E.State == Recursive) &&
6629 "Incorrectly use of addIncomplete");
6630 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6631 E.Swapped.swap(E.Str); // swap out the Recursive
6632 E.Str.swap(StubEnc);
6633 E.State = Incomplete;
6634 ++IncompleteCount;
6635}
6636
6637/// Once the RecordType has been expanded, the temporary incomplete TypeString
6638/// must be removed from the cache.
6639/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6640/// Returns true if the RecordType was defined recursively.
6641bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6642 if (!ID)
6643 return false;
6644 auto I = Map.find(ID);
6645 assert(I != Map.end() && "Entry not present");
6646 Entry &E = I->second;
6647 assert( (E.State == Incomplete ||
6648 E.State == IncompleteUsed) &&
6649 "Entry must be an incomplete type");
6650 bool IsRecursive = false;
6651 if (E.State == IncompleteUsed) {
6652 // We made use of our Incomplete encoding, thus we are recursive.
6653 IsRecursive = true;
6654 --IncompleteUsedCount;
6655 }
6656 if (E.Swapped.empty())
6657 Map.erase(I);
6658 else {
6659 // Swap the Recursive back.
6660 E.Swapped.swap(E.Str);
6661 E.Swapped.clear();
6662 E.State = Recursive;
6663 }
6664 --IncompleteCount;
6665 return IsRecursive;
6666}
6667
6668/// Add the encoded TypeString to the cache only if it is NonRecursive or
6669/// Recursive (viz: all sub-members were expanded as fully as possible).
6670void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6671 bool IsRecursive) {
6672 if (!ID || IncompleteUsedCount)
6673 return; // No key or it is is an incomplete sub-type so don't add.
6674 Entry &E = Map[ID];
6675 if (IsRecursive && !E.Str.empty()) {
6676 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6677 "This is not the same Recursive entry");
6678 // The parent container was not recursive after all, so we could have used
6679 // this Recursive sub-member entry after all, but we assumed the worse when
6680 // we started viz: IncompleteCount!=0.
6681 return;
6682 }
6683 assert(E.Str.empty() && "Entry already present");
6684 E.Str = Str.str();
6685 E.State = IsRecursive? Recursive : NonRecursive;
6686}
6687
6688/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6689/// are recursively expanding a type (IncompleteCount != 0) and the cached
6690/// encoding is Recursive, return an empty StringRef.
6691StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6692 if (!ID)
6693 return StringRef(); // We have no key.
6694 auto I = Map.find(ID);
6695 if (I == Map.end())
6696 return StringRef(); // We have no encoding.
6697 Entry &E = I->second;
6698 if (E.State == Recursive && IncompleteCount)
6699 return StringRef(); // We don't use Recursive encodings for member types.
6700
6701 if (E.State == Incomplete) {
6702 // The incomplete type is being used to break out of recursion.
6703 E.State = IncompleteUsed;
6704 ++IncompleteUsedCount;
6705 }
6706 return E.Str.c_str();
6707}
6708
6709/// The XCore ABI includes a type information section that communicates symbol
6710/// type information to the linker. The linker uses this information to verify
6711/// safety/correctness of things such as array bound and pointers et al.
6712/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6713/// This type information (TypeString) is emitted into meta data for all global
6714/// symbols: definitions, declarations, functions & variables.
6715///
6716/// The TypeString carries type, qualifier, name, size & value details.
6717/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00006718/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00006719/// The output is tested by test/CodeGen/xcore-stringtype.c.
6720///
6721static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6722 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6723
6724/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6725void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6726 CodeGen::CodeGenModule &CGM) const {
6727 SmallStringEnc Enc;
6728 if (getTypeString(Enc, D, CGM, TSC)) {
6729 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006730 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6731 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006732 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6733 llvm::NamedMDNode *MD =
6734 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6735 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6736 }
6737}
6738
6739static bool appendType(SmallStringEnc &Enc, QualType QType,
6740 const CodeGen::CodeGenModule &CGM,
6741 TypeStringCache &TSC);
6742
6743/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00006744/// Builds a SmallVector containing the encoded field types in declaration
6745/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006746static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6747 const RecordDecl *RD,
6748 const CodeGen::CodeGenModule &CGM,
6749 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006750 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006751 SmallStringEnc Enc;
6752 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006753 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006754 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006755 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006756 Enc += "b(";
6757 llvm::raw_svector_ostream OS(Enc);
6758 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006759 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006760 OS.flush();
6761 Enc += ':';
6762 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006763 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006764 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006765 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006766 Enc += ')';
6767 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00006768 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006769 }
6770 return true;
6771}
6772
6773/// Appends structure and union types to Enc and adds encoding to cache.
6774/// Recursively calls appendType (via extractFieldType) for each field.
6775/// Union types have their fields ordered according to the ABI.
6776static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6777 const CodeGen::CodeGenModule &CGM,
6778 TypeStringCache &TSC, const IdentifierInfo *ID) {
6779 // Append the cached TypeString if we have one.
6780 StringRef TypeString = TSC.lookupStr(ID);
6781 if (!TypeString.empty()) {
6782 Enc += TypeString;
6783 return true;
6784 }
6785
6786 // Start to emit an incomplete TypeString.
6787 size_t Start = Enc.size();
6788 Enc += (RT->isUnionType()? 'u' : 's');
6789 Enc += '(';
6790 if (ID)
6791 Enc += ID->getName();
6792 Enc += "){";
6793
6794 // We collect all encoded fields and order as necessary.
6795 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006796 const RecordDecl *RD = RT->getDecl()->getDefinition();
6797 if (RD && !RD->field_empty()) {
6798 // An incomplete TypeString stub is placed in the cache for this RecordType
6799 // so that recursive calls to this RecordType will use it whilst building a
6800 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006801 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006802 std::string StubEnc(Enc.substr(Start).str());
6803 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6804 TSC.addIncomplete(ID, std::move(StubEnc));
6805 if (!extractFieldType(FE, RD, CGM, TSC)) {
6806 (void) TSC.removeIncomplete(ID);
6807 return false;
6808 }
6809 IsRecursive = TSC.removeIncomplete(ID);
6810 // The ABI requires unions to be sorted but not structures.
6811 // See FieldEncoding::operator< for sort algorithm.
6812 if (RT->isUnionType())
6813 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006814 // We can now complete the TypeString.
6815 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006816 for (unsigned I = 0; I != E; ++I) {
6817 if (I)
6818 Enc += ',';
6819 Enc += FE[I].str();
6820 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006821 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006822 Enc += '}';
6823 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6824 return true;
6825}
6826
6827/// Appends enum types to Enc and adds the encoding to the cache.
6828static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6829 TypeStringCache &TSC,
6830 const IdentifierInfo *ID) {
6831 // Append the cached TypeString if we have one.
6832 StringRef TypeString = TSC.lookupStr(ID);
6833 if (!TypeString.empty()) {
6834 Enc += TypeString;
6835 return true;
6836 }
6837
6838 size_t Start = Enc.size();
6839 Enc += "e(";
6840 if (ID)
6841 Enc += ID->getName();
6842 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006843
6844 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006845 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006846 SmallVector<FieldEncoding, 16> FE;
6847 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6848 ++I) {
6849 SmallStringEnc EnumEnc;
6850 EnumEnc += "m(";
6851 EnumEnc += I->getName();
6852 EnumEnc += "){";
6853 I->getInitVal().toString(EnumEnc);
6854 EnumEnc += '}';
6855 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6856 }
6857 std::sort(FE.begin(), FE.end());
6858 unsigned E = FE.size();
6859 for (unsigned I = 0; I != E; ++I) {
6860 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006861 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006862 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006863 }
6864 }
6865 Enc += '}';
6866 TSC.addIfComplete(ID, Enc.substr(Start), false);
6867 return true;
6868}
6869
6870/// Appends type's qualifier to Enc.
6871/// This is done prior to appending the type's encoding.
6872static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6873 // Qualifiers are emitted in alphabetical order.
6874 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6875 int Lookup = 0;
6876 if (QT.isConstQualified())
6877 Lookup += 1<<0;
6878 if (QT.isRestrictQualified())
6879 Lookup += 1<<1;
6880 if (QT.isVolatileQualified())
6881 Lookup += 1<<2;
6882 Enc += Table[Lookup];
6883}
6884
6885/// Appends built-in types to Enc.
6886static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6887 const char *EncType;
6888 switch (BT->getKind()) {
6889 case BuiltinType::Void:
6890 EncType = "0";
6891 break;
6892 case BuiltinType::Bool:
6893 EncType = "b";
6894 break;
6895 case BuiltinType::Char_U:
6896 EncType = "uc";
6897 break;
6898 case BuiltinType::UChar:
6899 EncType = "uc";
6900 break;
6901 case BuiltinType::SChar:
6902 EncType = "sc";
6903 break;
6904 case BuiltinType::UShort:
6905 EncType = "us";
6906 break;
6907 case BuiltinType::Short:
6908 EncType = "ss";
6909 break;
6910 case BuiltinType::UInt:
6911 EncType = "ui";
6912 break;
6913 case BuiltinType::Int:
6914 EncType = "si";
6915 break;
6916 case BuiltinType::ULong:
6917 EncType = "ul";
6918 break;
6919 case BuiltinType::Long:
6920 EncType = "sl";
6921 break;
6922 case BuiltinType::ULongLong:
6923 EncType = "ull";
6924 break;
6925 case BuiltinType::LongLong:
6926 EncType = "sll";
6927 break;
6928 case BuiltinType::Float:
6929 EncType = "ft";
6930 break;
6931 case BuiltinType::Double:
6932 EncType = "d";
6933 break;
6934 case BuiltinType::LongDouble:
6935 EncType = "ld";
6936 break;
6937 default:
6938 return false;
6939 }
6940 Enc += EncType;
6941 return true;
6942}
6943
6944/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6945static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6946 const CodeGen::CodeGenModule &CGM,
6947 TypeStringCache &TSC) {
6948 Enc += "p(";
6949 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6950 return false;
6951 Enc += ')';
6952 return true;
6953}
6954
6955/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006956static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6957 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006958 const CodeGen::CodeGenModule &CGM,
6959 TypeStringCache &TSC, StringRef NoSizeEnc) {
6960 if (AT->getSizeModifier() != ArrayType::Normal)
6961 return false;
6962 Enc += "a(";
6963 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6964 CAT->getSize().toStringUnsigned(Enc);
6965 else
6966 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6967 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006968 // The Qualifiers should be attached to the type rather than the array.
6969 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006970 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6971 return false;
6972 Enc += ')';
6973 return true;
6974}
6975
6976/// Appends a function encoding to Enc, calling appendType for the return type
6977/// and the arguments.
6978static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6979 const CodeGen::CodeGenModule &CGM,
6980 TypeStringCache &TSC) {
6981 Enc += "f{";
6982 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6983 return false;
6984 Enc += "}(";
6985 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6986 // N.B. we are only interested in the adjusted param types.
6987 auto I = FPT->param_type_begin();
6988 auto E = FPT->param_type_end();
6989 if (I != E) {
6990 do {
6991 if (!appendType(Enc, *I, CGM, TSC))
6992 return false;
6993 ++I;
6994 if (I != E)
6995 Enc += ',';
6996 } while (I != E);
6997 if (FPT->isVariadic())
6998 Enc += ",va";
6999 } else {
7000 if (FPT->isVariadic())
7001 Enc += "va";
7002 else
7003 Enc += '0';
7004 }
7005 }
7006 Enc += ')';
7007 return true;
7008}
7009
7010/// Handles the type's qualifier before dispatching a call to handle specific
7011/// type encodings.
7012static bool appendType(SmallStringEnc &Enc, QualType QType,
7013 const CodeGen::CodeGenModule &CGM,
7014 TypeStringCache &TSC) {
7015
7016 QualType QT = QType.getCanonicalType();
7017
Robert Lytton6adb20f2014-06-05 09:06:21 +00007018 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7019 // The Qualifiers should be attached to the type rather than the array.
7020 // Thus we don't call appendQualifier() here.
7021 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7022
Robert Lytton844aeeb2014-05-02 09:33:20 +00007023 appendQualifier(Enc, QT);
7024
7025 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7026 return appendBuiltinType(Enc, BT);
7027
Robert Lytton844aeeb2014-05-02 09:33:20 +00007028 if (const PointerType *PT = QT->getAs<PointerType>())
7029 return appendPointerType(Enc, PT, CGM, TSC);
7030
7031 if (const EnumType *ET = QT->getAs<EnumType>())
7032 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7033
7034 if (const RecordType *RT = QT->getAsStructureType())
7035 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7036
7037 if (const RecordType *RT = QT->getAsUnionType())
7038 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7039
7040 if (const FunctionType *FT = QT->getAs<FunctionType>())
7041 return appendFunctionType(Enc, FT, CGM, TSC);
7042
7043 return false;
7044}
7045
7046static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7047 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7048 if (!D)
7049 return false;
7050
7051 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7052 if (FD->getLanguageLinkage() != CLanguageLinkage)
7053 return false;
7054 return appendType(Enc, FD->getType(), CGM, TSC);
7055 }
7056
7057 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7058 if (VD->getLanguageLinkage() != CLanguageLinkage)
7059 return false;
7060 QualType QT = VD->getType().getCanonicalType();
7061 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7062 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007063 // The Qualifiers should be attached to the type rather than the array.
7064 // Thus we don't call appendQualifier() here.
7065 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007066 }
7067 return appendType(Enc, QT, CGM, TSC);
7068 }
7069 return false;
7070}
7071
7072
Robert Lytton0e076492013-08-13 09:43:10 +00007073//===----------------------------------------------------------------------===//
7074// Driver code
7075//===----------------------------------------------------------------------===//
7076
Rafael Espindola9f834732014-09-19 01:54:22 +00007077const llvm::Triple &CodeGenModule::getTriple() const {
7078 return getTarget().getTriple();
7079}
7080
7081bool CodeGenModule::supportsCOMDAT() const {
7082 return !getTriple().isOSBinFormatMachO();
7083}
7084
Chris Lattner2b037972010-07-29 02:01:43 +00007085const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007086 if (TheTargetCodeGenInfo)
7087 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007088
John McCallc8e01702013-04-16 22:48:15 +00007089 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007090 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007091 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007092 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007093
Derek Schuff09338a22012-09-06 17:37:28 +00007094 case llvm::Triple::le32:
7095 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007096 case llvm::Triple::mips:
7097 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007098 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7099
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007100 case llvm::Triple::mips64:
7101 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007102 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7103
Tim Northover25e8a672014-05-24 12:51:25 +00007104 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007105 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007106 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007107 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007108 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007109
Tim Northover573cbee2014-05-24 12:52:07 +00007110 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007111 }
7112
Daniel Dunbard59655c2009-09-12 00:59:49 +00007113 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007114 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007115 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007116 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007117 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007118 if (Triple.getOS() == llvm::Triple::Win32) {
7119 TheTargetCodeGenInfo =
7120 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7121 return *TheTargetCodeGenInfo;
7122 }
7123
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007124 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007125 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007126 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007127 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007128 (CodeGenOpts.FloatABI != "soft" &&
7129 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007130 Kind = ARMABIInfo::AAPCS_VFP;
7131
Derek Schuff71658bd2015-01-29 00:47:04 +00007132 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007133 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007134
John McCallea8d8bb2010-03-11 00:10:12 +00007135 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007136 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007137 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007138 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007139 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007140 if (getTarget().getABI() == "elfv2")
7141 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007142 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007143
Ulrich Weigandb7122372014-07-21 00:48:09 +00007144 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007145 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007146 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007147 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007148 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007149 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007150 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007151 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007152 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007153 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007154
Ulrich Weigandb7122372014-07-21 00:48:09 +00007155 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007156 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007157 }
John McCallea8d8bb2010-03-11 00:10:12 +00007158
Peter Collingbournec947aae2012-05-20 23:28:41 +00007159 case llvm::Triple::nvptx:
7160 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007161 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007162
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007163 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007164 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007165
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007166 case llvm::Triple::systemz: {
7167 bool HasVector = getTarget().getABI() == "vector";
7168 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7169 HasVector));
7170 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007171
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007172 case llvm::Triple::tce:
7173 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7174
Eli Friedman33465822011-07-08 23:31:17 +00007175 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007176 bool IsDarwinVectorABI = Triple.isOSDarwin();
7177 bool IsSmallStructInRegABI =
7178 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007179 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007180
John McCall1fe2a8c2013-06-18 02:46:29 +00007181 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007182 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
7183 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7184 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007185 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007186 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
7187 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7188 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007189 }
Eli Friedman33465822011-07-08 23:31:17 +00007190 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007191
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007192 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007193 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007194 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7195 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007196 X86AVXABILevel::None);
7197
Chris Lattner04dc9572010-08-31 16:44:54 +00007198 switch (Triple.getOS()) {
7199 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007200 return *(TheTargetCodeGenInfo =
7201 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007202 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007203 return *(TheTargetCodeGenInfo =
7204 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007205 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007206 return *(TheTargetCodeGenInfo =
7207 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007208 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007209 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007210 case llvm::Triple::hexagon:
7211 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007212 case llvm::Triple::r600:
7213 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007214 case llvm::Triple::amdgcn:
7215 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007216 case llvm::Triple::sparcv9:
7217 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007218 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007219 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007220 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007221}