blob: 70b02dbebdcfd6878f4e202983cd23b8c9448d67 [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//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000448// WebAssembly ABI Implementation
449//
450// This is a very simple ABI that relies a lot on DefaultABIInfo.
451//===----------------------------------------------------------------------===//
452
453class WebAssemblyABIInfo final : public DefaultABIInfo {
454public:
455 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
456 : DefaultABIInfo(CGT) {}
457
458private:
459 ABIArgInfo classifyReturnType(QualType RetTy) const;
460 ABIArgInfo classifyArgumentType(QualType Ty) const;
461
462 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
463 // non-virtual, but computeInfo is virtual, so we overload that.
464 void computeInfo(CGFunctionInfo &FI) const override {
465 if (!getCXXABI().classifyReturnType(FI))
466 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
467 for (auto &Arg : FI.arguments())
468 Arg.info = classifyArgumentType(Arg.type);
469 }
470};
471
472class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
473public:
474 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
475 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
476};
477
478/// \brief Classify argument of given type \p Ty.
479ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
480 Ty = useFirstFieldIfTransparentUnion(Ty);
481
482 if (isAggregateTypeForABI(Ty)) {
483 // Records with non-trivial destructors/copy-constructors should not be
484 // passed by value.
485 unsigned TypeAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
486 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
487 return ABIArgInfo::getIndirect(TypeAlign,
488 RAA == CGCXXABI::RAA_DirectInMemory);
489 // Ignore empty structs/unions.
490 if (isEmptyRecord(getContext(), Ty, true))
491 return ABIArgInfo::getIgnore();
492 // Lower single-element structs to just pass a regular value. TODO: We
493 // could do reasonable-size multiple-element structs too, using getExpand(),
494 // though watch out for things like bitfields.
495 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
496 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
497 return ABIArgInfo::getIndirect(TypeAlign);
498 }
499
500 // Otherwise just do the default thing.
501 return DefaultABIInfo::classifyArgumentType(Ty);
502}
503
504ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
505 if (isAggregateTypeForABI(RetTy)) {
506 // Records with non-trivial destructors/copy-constructors should not be
507 // returned by value.
508 if (!getRecordArgABI(RetTy, getCXXABI())) {
509 // Ignore empty structs/unions.
510 if (isEmptyRecord(getContext(), RetTy, true))
511 return ABIArgInfo::getIgnore();
512 // Lower single-element structs to just return a regular value. TODO: We
513 // could do reasonable-size multiple-element structs too, using
514 // ABIArgInfo::getDirect().
515 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
516 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
517 }
518 }
519
520 // Otherwise just do the default thing.
521 return DefaultABIInfo::classifyReturnType(RetTy);
522}
523
524//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000525// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000526//
527// This is a simplified version of the x86_32 ABI. Arguments and return values
528// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000529//===----------------------------------------------------------------------===//
530
531class PNaClABIInfo : public ABIInfo {
532 public:
533 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
534
535 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000536 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000537
Craig Topper4f12f102014-03-12 06:41:41 +0000538 void computeInfo(CGFunctionInfo &FI) const override;
539 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
540 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000541};
542
543class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
544 public:
545 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
546 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
547};
548
549void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000550 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000551 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
552
Reid Kleckner40ca9132014-05-13 22:05:45 +0000553 for (auto &I : FI.arguments())
554 I.info = classifyArgumentType(I.type);
555}
Derek Schuff09338a22012-09-06 17:37:28 +0000556
557llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
558 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000559 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000560}
561
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000562/// \brief Classify argument of given type \p Ty.
563ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000564 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000565 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000566 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000567 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000568 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
569 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000570 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000571 } else if (Ty->isFloatingType()) {
572 // Floating-point types don't go inreg.
573 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000574 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000575
576 return (Ty->isPromotableIntegerType() ?
577 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000578}
579
580ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
581 if (RetTy->isVoidType())
582 return ABIArgInfo::getIgnore();
583
Eli Benderskye20dad62013-04-04 22:49:35 +0000584 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000585 if (isAggregateTypeForABI(RetTy))
586 return ABIArgInfo::getIndirect(0);
587
588 // Treat an enum type as its underlying type.
589 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
590 RetTy = EnumTy->getDecl()->getIntegerType();
591
592 return (RetTy->isPromotableIntegerType() ?
593 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
594}
595
Chad Rosier651c1832013-03-25 21:00:27 +0000596/// IsX86_MMXType - Return true if this is an MMX type.
597bool IsX86_MMXType(llvm::Type *IRType) {
598 // 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 +0000599 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
600 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
601 IRType->getScalarSizeInBits() != 64;
602}
603
Jay Foad7c57be32011-07-11 09:56:20 +0000604static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000605 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000606 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000607 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
608 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
609 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000610 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000611 }
612
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000613 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000614 }
615
616 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000617 return Ty;
618}
619
Reid Kleckner80944df2014-10-31 22:00:51 +0000620/// Returns true if this type can be passed in SSE registers with the
621/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
622static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
623 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
624 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
625 return true;
626 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
627 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
628 // registers specially.
629 unsigned VecSize = Context.getTypeSize(VT);
630 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
631 return true;
632 }
633 return false;
634}
635
636/// Returns true if this aggregate is small enough to be passed in SSE registers
637/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
638static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
639 return NumMembers <= 4;
640}
641
Chris Lattner0cf24192010-06-28 20:05:43 +0000642//===----------------------------------------------------------------------===//
643// X86-32 ABI Implementation
644//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000645
Reid Kleckner661f35b2014-01-18 01:12:41 +0000646/// \brief Similar to llvm::CCState, but for Clang.
647struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000648 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000649
650 unsigned CC;
651 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000652 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000653};
654
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000655/// X86_32ABIInfo - The X86-32 ABI information.
656class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000657 enum Class {
658 Integer,
659 Float
660 };
661
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000662 static const unsigned MinABIStackAlignInBytes = 4;
663
David Chisnallde3a0692009-08-17 23:08:21 +0000664 bool IsDarwinVectorABI;
665 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000666 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000667 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000668
669 static bool isRegisterSize(unsigned Size) {
670 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
671 }
672
Reid Kleckner80944df2014-10-31 22:00:51 +0000673 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
674 // FIXME: Assumes vectorcall is in use.
675 return isX86VectorTypeForVectorCall(getContext(), Ty);
676 }
677
678 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
679 uint64_t NumMembers) const override {
680 // FIXME: Assumes vectorcall is in use.
681 return isX86VectorCallAggregateSmallEnough(NumMembers);
682 }
683
Reid Kleckner40ca9132014-05-13 22:05:45 +0000684 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000685
Daniel Dunbar557893d2010-04-21 19:10:51 +0000686 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
687 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000688 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
689
690 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000691
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000692 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000693 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000694
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000695 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000696 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000697 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
698 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000699
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000700 /// \brief Rewrite the function info so that all memory arguments use
701 /// inalloca.
702 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
703
704 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
705 unsigned &StackOffset, ABIArgInfo &Info,
706 QualType Type) const;
707
Rafael Espindola75419dc2012-07-23 23:30:29 +0000708public:
709
Craig Topper4f12f102014-03-12 06:41:41 +0000710 void computeInfo(CGFunctionInfo &FI) const override;
711 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
712 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000713
Chad Rosier651c1832013-03-25 21:00:27 +0000714 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000715 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000716 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000717 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000718};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000719
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000720class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
721public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000722 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000723 bool d, bool p, bool w, unsigned r)
724 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000725
John McCall1fe2a8c2013-06-18 02:46:29 +0000726 static bool isStructReturnInRegABI(
727 const llvm::Triple &Triple, const CodeGenOptions &Opts);
728
Eric Christopher162c91c2015-06-05 22:03:00 +0000729 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000730 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000731
Craig Topper4f12f102014-03-12 06:41:41 +0000732 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000733 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000734 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000735 return 4;
736 }
737
738 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000739 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000740
Jay Foad7c57be32011-07-11 09:56:20 +0000741 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000742 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000743 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000744 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
745 }
746
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000747 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
748 std::string &Constraints,
749 std::vector<llvm::Type *> &ResultRegTypes,
750 std::vector<llvm::Type *> &ResultTruncRegTypes,
751 std::vector<LValue> &ResultRegDests,
752 std::string &AsmString,
753 unsigned NumOutputs) const override;
754
Craig Topper4f12f102014-03-12 06:41:41 +0000755 llvm::Constant *
756 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000757 unsigned Sig = (0xeb << 0) | // jmp rel8
758 (0x06 << 8) | // .+0x08
759 ('F' << 16) |
760 ('T' << 24);
761 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
762 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000763};
764
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000765}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000766
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000767/// Rewrite input constraint references after adding some output constraints.
768/// In the case where there is one output and one input and we add one output,
769/// we need to replace all operand references greater than or equal to 1:
770/// mov $0, $1
771/// mov eax, $1
772/// The result will be:
773/// mov $0, $2
774/// mov eax, $2
775static void rewriteInputConstraintReferences(unsigned FirstIn,
776 unsigned NumNewOuts,
777 std::string &AsmString) {
778 std::string Buf;
779 llvm::raw_string_ostream OS(Buf);
780 size_t Pos = 0;
781 while (Pos < AsmString.size()) {
782 size_t DollarStart = AsmString.find('$', Pos);
783 if (DollarStart == std::string::npos)
784 DollarStart = AsmString.size();
785 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
786 if (DollarEnd == std::string::npos)
787 DollarEnd = AsmString.size();
788 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
789 Pos = DollarEnd;
790 size_t NumDollars = DollarEnd - DollarStart;
791 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
792 // We have an operand reference.
793 size_t DigitStart = Pos;
794 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
795 if (DigitEnd == std::string::npos)
796 DigitEnd = AsmString.size();
797 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
798 unsigned OperandIndex;
799 if (!OperandStr.getAsInteger(10, OperandIndex)) {
800 if (OperandIndex >= FirstIn)
801 OperandIndex += NumNewOuts;
802 OS << OperandIndex;
803 } else {
804 OS << OperandStr;
805 }
806 Pos = DigitEnd;
807 }
808 }
809 AsmString = std::move(OS.str());
810}
811
812/// Add output constraints for EAX:EDX because they are return registers.
813void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
814 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
815 std::vector<llvm::Type *> &ResultRegTypes,
816 std::vector<llvm::Type *> &ResultTruncRegTypes,
817 std::vector<LValue> &ResultRegDests, std::string &AsmString,
818 unsigned NumOutputs) const {
819 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
820
821 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
822 // larger.
823 if (!Constraints.empty())
824 Constraints += ',';
825 if (RetWidth <= 32) {
826 Constraints += "={eax}";
827 ResultRegTypes.push_back(CGF.Int32Ty);
828 } else {
829 // Use the 'A' constraint for EAX:EDX.
830 Constraints += "=A";
831 ResultRegTypes.push_back(CGF.Int64Ty);
832 }
833
834 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
835 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
836 ResultTruncRegTypes.push_back(CoerceTy);
837
838 // Coerce the integer by bitcasting the return slot pointer.
839 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
840 CoerceTy->getPointerTo()));
841 ResultRegDests.push_back(ReturnSlot);
842
843 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
844}
845
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000846/// shouldReturnTypeInRegister - Determine if the given type should be
847/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000848bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
849 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000850 uint64_t Size = Context.getTypeSize(Ty);
851
852 // Type must be register sized.
853 if (!isRegisterSize(Size))
854 return false;
855
856 if (Ty->isVectorType()) {
857 // 64- and 128- bit vectors inside structures are not returned in
858 // registers.
859 if (Size == 64 || Size == 128)
860 return false;
861
862 return true;
863 }
864
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000865 // If this is a builtin, pointer, enum, complex type, member pointer, or
866 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000867 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000868 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000869 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000870 return true;
871
872 // Arrays are treated like records.
873 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000874 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000875
876 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000877 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000878 if (!RT) return false;
879
Anders Carlsson40446e82010-01-27 03:25:19 +0000880 // FIXME: Traverse bases here too.
881
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000882 // Structure types are passed in register if all fields would be
883 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000884 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000885 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000886 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000887 continue;
888
889 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000890 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000891 return false;
892 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000893 return true;
894}
895
Reid Kleckner661f35b2014-01-18 01:12:41 +0000896ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
897 // If the return value is indirect, then the hidden argument is consuming one
898 // integer register.
899 if (State.FreeRegs) {
900 --State.FreeRegs;
901 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
902 }
903 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
904}
905
Eric Christopher7565e0d2015-05-29 23:09:49 +0000906ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
907 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000908 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000909 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000910
Reid Kleckner80944df2014-10-31 22:00:51 +0000911 const Type *Base = nullptr;
912 uint64_t NumElts = 0;
913 if (State.CC == llvm::CallingConv::X86_VectorCall &&
914 isHomogeneousAggregate(RetTy, Base, NumElts)) {
915 // The LLVM struct type for such an aggregate should lower properly.
916 return ABIArgInfo::getDirect();
917 }
918
Chris Lattner458b2aa2010-07-29 02:16:43 +0000919 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000920 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000921 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000922 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000923
924 // 128-bit vectors are a special case; they are returned in
925 // registers and we need to make sure to pick a type the LLVM
926 // backend will like.
927 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000928 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000929 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000930
931 // Always return in register if it fits in a general purpose
932 // register, or if it is 64 bits and has a single element.
933 if ((Size == 8 || Size == 16 || Size == 32) ||
934 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000935 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000936 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000937
Reid Kleckner661f35b2014-01-18 01:12:41 +0000938 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000939 }
940
941 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000942 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000943
John McCalla1dee5302010-08-22 10:59:02 +0000944 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000945 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000946 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000947 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000948 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000949 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000950
David Chisnallde3a0692009-08-17 23:08:21 +0000951 // If specified, structs and unions are always indirect.
952 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000953 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000954
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000955 // Small structures which are register sized are generally returned
956 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000957 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000958 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000959
960 // As a special-case, if the struct is a "single-element" struct, and
961 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000962 // floating-point register. (MSVC does not apply this special case.)
963 // We apply a similar transformation for pointer types to improve the
964 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000965 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000966 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000967 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000968 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
969
970 // FIXME: We should be able to narrow this integer in cases with dead
971 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000972 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000973 }
974
Reid Kleckner661f35b2014-01-18 01:12:41 +0000975 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000976 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000977
Chris Lattner458b2aa2010-07-29 02:16:43 +0000978 // Treat an enum type as its underlying type.
979 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
980 RetTy = EnumTy->getDecl()->getIntegerType();
981
982 return (RetTy->isPromotableIntegerType() ?
983 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000984}
985
Eli Friedman7919bea2012-06-05 19:40:46 +0000986static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
987 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
988}
989
Daniel Dunbared23de32010-09-16 20:42:00 +0000990static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
991 const RecordType *RT = Ty->getAs<RecordType>();
992 if (!RT)
993 return 0;
994 const RecordDecl *RD = RT->getDecl();
995
996 // If this is a C++ record, check the bases first.
997 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000998 for (const auto &I : CXXRD->bases())
999 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001000 return false;
1001
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001002 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001003 QualType FT = i->getType();
1004
Eli Friedman7919bea2012-06-05 19:40:46 +00001005 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001006 return true;
1007
1008 if (isRecordWithSSEVectorType(Context, FT))
1009 return true;
1010 }
1011
1012 return false;
1013}
1014
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001015unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1016 unsigned Align) const {
1017 // Otherwise, if the alignment is less than or equal to the minimum ABI
1018 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001019 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001020 return 0; // Use default alignment.
1021
1022 // On non-Darwin, the stack type alignment is always 4.
1023 if (!IsDarwinVectorABI) {
1024 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001025 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001026 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001027
Daniel Dunbared23de32010-09-16 20:42:00 +00001028 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001029 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1030 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001031 return 16;
1032
1033 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001034}
1035
Rafael Espindola703c47f2012-10-19 05:04:37 +00001036ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001037 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001038 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001039 if (State.FreeRegs) {
1040 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +00001041 return ABIArgInfo::getIndirectInReg(0, false);
1042 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001043 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001044 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001045
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001046 // Compute the byval alignment.
1047 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1048 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1049 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001050 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001051
1052 // If the stack alignment is less than the type alignment, realign the
1053 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001054 bool Realign = TypeAlign > StackAlign;
1055 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001056}
1057
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001058X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1059 const Type *T = isSingleElementStruct(Ty, getContext());
1060 if (!T)
1061 T = Ty.getTypePtr();
1062
1063 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1064 BuiltinType::Kind K = BT->getKind();
1065 if (K == BuiltinType::Float || K == BuiltinType::Double)
1066 return Float;
1067 }
1068 return Integer;
1069}
1070
Reid Kleckner661f35b2014-01-18 01:12:41 +00001071bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
1072 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +00001073 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001074 Class C = classify(Ty);
1075 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +00001076 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001077
Rafael Espindola077dd592012-10-24 01:58:58 +00001078 unsigned Size = getContext().getTypeSize(Ty);
1079 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001080
1081 if (SizeInRegs == 0)
1082 return false;
1083
Reid Kleckner661f35b2014-01-18 01:12:41 +00001084 if (SizeInRegs > State.FreeRegs) {
1085 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001086 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001087 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001088
Reid Kleckner661f35b2014-01-18 01:12:41 +00001089 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001090
Reid Kleckner80944df2014-10-31 22:00:51 +00001091 if (State.CC == llvm::CallingConv::X86_FastCall ||
1092 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001093 if (Size > 32)
1094 return false;
1095
1096 if (Ty->isIntegralOrEnumerationType())
1097 return true;
1098
1099 if (Ty->isPointerType())
1100 return true;
1101
1102 if (Ty->isReferenceType())
1103 return true;
1104
Reid Kleckner661f35b2014-01-18 01:12:41 +00001105 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001106 NeedsPadding = true;
1107
Rafael Espindola077dd592012-10-24 01:58:58 +00001108 return false;
1109 }
1110
Rafael Espindola703c47f2012-10-19 05:04:37 +00001111 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001112}
1113
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001114ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1115 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001117
Reid Klecknerb1be6832014-11-15 01:41:41 +00001118 Ty = useFirstFieldIfTransparentUnion(Ty);
1119
Reid Kleckner80944df2014-10-31 22:00:51 +00001120 // Check with the C++ ABI first.
1121 const RecordType *RT = Ty->getAs<RecordType>();
1122 if (RT) {
1123 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1124 if (RAA == CGCXXABI::RAA_Indirect) {
1125 return getIndirectResult(Ty, false, State);
1126 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1127 // The field index doesn't matter, we'll fix it up later.
1128 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1129 }
1130 }
1131
1132 // vectorcall adds the concept of a homogenous vector aggregate, similar
1133 // to other targets.
1134 const Type *Base = nullptr;
1135 uint64_t NumElts = 0;
1136 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1137 isHomogeneousAggregate(Ty, Base, NumElts)) {
1138 if (State.FreeSSERegs >= NumElts) {
1139 State.FreeSSERegs -= NumElts;
1140 if (Ty->isBuiltinType() || Ty->isVectorType())
1141 return ABIArgInfo::getDirect();
1142 return ABIArgInfo::getExpand();
1143 }
1144 return getIndirectResult(Ty, /*ByVal=*/false, State);
1145 }
1146
1147 if (isAggregateTypeForABI(Ty)) {
1148 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001149 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001150 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001151 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001152
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001153 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001154 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001155 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001156 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001157
Eli Friedman9f061a32011-11-18 00:28:11 +00001158 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001159 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001160 return ABIArgInfo::getIgnore();
1161
Rafael Espindolafad28de2012-10-24 01:59:00 +00001162 llvm::LLVMContext &LLVMContext = getVMContext();
1163 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1164 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001165 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001166 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001167 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001168 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1169 return ABIArgInfo::getDirectInReg(Result);
1170 }
Craig Topper8a13c412014-05-21 05:09:00 +00001171 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001172
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001173 // Expand small (<= 128-bit) record types when we know that the stack layout
1174 // of those arguments will match the struct. This is important because the
1175 // LLVM backend isn't smart enough to remove byval, which inhibits many
1176 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001177 if (getContext().getTypeSize(Ty) <= 4*32 &&
1178 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001179 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001180 State.CC == llvm::CallingConv::X86_FastCall ||
1181 State.CC == llvm::CallingConv::X86_VectorCall,
1182 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001183
Reid Kleckner661f35b2014-01-18 01:12:41 +00001184 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001185 }
1186
Chris Lattnerd774ae92010-08-26 20:05:13 +00001187 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001188 // On Darwin, some vectors are passed in memory, we handle this by passing
1189 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001190 if (IsDarwinVectorABI) {
1191 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001192 if ((Size == 8 || Size == 16 || Size == 32) ||
1193 (Size == 64 && VT->getNumElements() == 1))
1194 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1195 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001196 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001197
Chad Rosier651c1832013-03-25 21:00:27 +00001198 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1199 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001200
Chris Lattnerd774ae92010-08-26 20:05:13 +00001201 return ABIArgInfo::getDirect();
1202 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001203
1204
Chris Lattner458b2aa2010-07-29 02:16:43 +00001205 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1206 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001207
Rafael Espindolafad28de2012-10-24 01:59:00 +00001208 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001209 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001210
1211 if (Ty->isPromotableIntegerType()) {
1212 if (InReg)
1213 return ABIArgInfo::getExtendInReg();
1214 return ABIArgInfo::getExtend();
1215 }
1216 if (InReg)
1217 return ABIArgInfo::getDirectInReg();
1218 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001219}
1220
Rafael Espindolaa6472962012-07-24 00:01:07 +00001221void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001222 CCState State(FI.getCallingConvention());
1223 if (State.CC == llvm::CallingConv::X86_FastCall)
1224 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001225 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1226 State.FreeRegs = 2;
1227 State.FreeSSERegs = 6;
1228 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001229 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001230 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001231 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001232
Reid Kleckner677539d2014-07-10 01:58:55 +00001233 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001234 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001235 } else if (FI.getReturnInfo().isIndirect()) {
1236 // The C++ ABI is not aware of register usage, so we have to check if the
1237 // return value was sret and put it in a register ourselves if appropriate.
1238 if (State.FreeRegs) {
1239 --State.FreeRegs; // The sret parameter consumes a register.
1240 FI.getReturnInfo().setInReg(true);
1241 }
1242 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001243
Peter Collingbournef7706832014-12-12 23:41:25 +00001244 // The chain argument effectively gives us another free register.
1245 if (FI.isChainCall())
1246 ++State.FreeRegs;
1247
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001248 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001249 for (auto &I : FI.arguments()) {
1250 I.info = classifyArgumentType(I.type, State);
1251 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001252 }
1253
1254 // If we needed to use inalloca for any argument, do a second pass and rewrite
1255 // all the memory arguments to use inalloca.
1256 if (UsedInAlloca)
1257 rewriteWithInAlloca(FI);
1258}
1259
1260void
1261X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1262 unsigned &StackOffset,
1263 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001264 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1265 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1266 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1267 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1268
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001269 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1270 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001271 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001272 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001273 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001274 unsigned NumBytes = StackOffset - OldOffset;
1275 assert(NumBytes);
1276 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1277 Ty = llvm::ArrayType::get(Ty, NumBytes);
1278 FrameFields.push_back(Ty);
1279 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001280}
1281
Reid Kleckner852361d2014-07-26 00:12:26 +00001282static bool isArgInAlloca(const ABIArgInfo &Info) {
1283 // Leave ignored and inreg arguments alone.
1284 switch (Info.getKind()) {
1285 case ABIArgInfo::InAlloca:
1286 return true;
1287 case ABIArgInfo::Indirect:
1288 assert(Info.getIndirectByVal());
1289 return true;
1290 case ABIArgInfo::Ignore:
1291 return false;
1292 case ABIArgInfo::Direct:
1293 case ABIArgInfo::Extend:
1294 case ABIArgInfo::Expand:
1295 if (Info.getInReg())
1296 return false;
1297 return true;
1298 }
1299 llvm_unreachable("invalid enum");
1300}
1301
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001302void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1303 assert(IsWin32StructABI && "inalloca only supported on win32");
1304
1305 // Build a packed struct type for all of the arguments in memory.
1306 SmallVector<llvm::Type *, 6> FrameFields;
1307
1308 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001309 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1310
1311 // Put 'this' into the struct before 'sret', if necessary.
1312 bool IsThisCall =
1313 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1314 ABIArgInfo &Ret = FI.getReturnInfo();
1315 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1316 isArgInAlloca(I->info)) {
1317 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1318 ++I;
1319 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001320
1321 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001322 if (Ret.isIndirect() && !Ret.getInReg()) {
1323 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1324 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001325 // On Windows, the hidden sret parameter is always returned in eax.
1326 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001327 }
1328
1329 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001330 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001331 ++I;
1332
1333 // Put arguments passed in memory into the struct.
1334 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001335 if (isArgInAlloca(I->info))
1336 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001337 }
1338
1339 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1340 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001341}
1342
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001343llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1344 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001345 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001346
1347 CGBuilderTy &Builder = CGF.Builder;
1348 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1349 "ap");
1350 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001351
1352 // Compute if the address needs to be aligned
1353 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1354 Align = getTypeStackAlignInBytes(Ty, Align);
1355 Align = std::max(Align, 4U);
1356 if (Align > 4) {
1357 // addr = (addr + align - 1) & -align;
1358 llvm::Value *Offset =
1359 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1360 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1361 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1362 CGF.Int32Ty);
1363 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1364 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1365 Addr->getType(),
1366 "ap.cur.aligned");
1367 }
1368
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001369 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001370 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001371 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1372
1373 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001374 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001375 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001376 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001377 "ap.next");
1378 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1379
1380 return AddrTyped;
1381}
1382
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001383bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1384 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1385 assert(Triple.getArch() == llvm::Triple::x86);
1386
1387 switch (Opts.getStructReturnConvention()) {
1388 case CodeGenOptions::SRCK_Default:
1389 break;
1390 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1391 return false;
1392 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1393 return true;
1394 }
1395
1396 if (Triple.isOSDarwin())
1397 return true;
1398
1399 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001400 case llvm::Triple::DragonFly:
1401 case llvm::Triple::FreeBSD:
1402 case llvm::Triple::OpenBSD:
1403 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001404 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001405 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001406 default:
1407 return false;
1408 }
1409}
1410
Eric Christopher162c91c2015-06-05 22:03:00 +00001411void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001412 llvm::GlobalValue *GV,
1413 CodeGen::CodeGenModule &CGM) const {
1414 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1415 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1416 // Get the LLVM function.
1417 llvm::Function *Fn = cast<llvm::Function>(GV);
1418
1419 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001420 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001421 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001422 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1423 llvm::AttributeSet::get(CGM.getLLVMContext(),
1424 llvm::AttributeSet::FunctionIndex,
1425 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001426 }
1427 }
1428}
1429
John McCallbeec5a02010-03-06 00:35:14 +00001430bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1431 CodeGen::CodeGenFunction &CGF,
1432 llvm::Value *Address) const {
1433 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001434
Chris Lattnerece04092012-02-07 00:39:47 +00001435 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001436
John McCallbeec5a02010-03-06 00:35:14 +00001437 // 0-7 are the eight integer registers; the order is different
1438 // on Darwin (for EH), but the range is the same.
1439 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001440 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001441
John McCallc8e01702013-04-16 22:48:15 +00001442 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001443 // 12-16 are st(0..4). Not sure why we stop at 4.
1444 // These have size 16, which is sizeof(long double) on
1445 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001446 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001447 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001448
John McCallbeec5a02010-03-06 00:35:14 +00001449 } else {
1450 // 9 is %eflags, which doesn't get a size on Darwin for some
1451 // reason.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001452 Builder.CreateStore(
1453 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9));
John McCallbeec5a02010-03-06 00:35:14 +00001454
1455 // 11-16 are st(0..5). Not sure why we stop at 5.
1456 // These have size 12, which is sizeof(long double) on
1457 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001458 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001459 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1460 }
John McCallbeec5a02010-03-06 00:35:14 +00001461
1462 return false;
1463}
1464
Chris Lattner0cf24192010-06-28 20:05:43 +00001465//===----------------------------------------------------------------------===//
1466// X86-64 ABI Implementation
1467//===----------------------------------------------------------------------===//
1468
1469
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001470namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001471/// The AVX ABI level for X86 targets.
1472enum class X86AVXABILevel {
1473 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001474 AVX,
1475 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001476};
1477
1478/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1479static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1480 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001481 case X86AVXABILevel::AVX512:
1482 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001483 case X86AVXABILevel::AVX:
1484 return 256;
1485 case X86AVXABILevel::None:
1486 return 128;
1487 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001488 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001489}
1490
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001491/// X86_64ABIInfo - The X86_64 ABI information.
1492class X86_64ABIInfo : public ABIInfo {
1493 enum Class {
1494 Integer = 0,
1495 SSE,
1496 SSEUp,
1497 X87,
1498 X87Up,
1499 ComplexX87,
1500 NoClass,
1501 Memory
1502 };
1503
1504 /// merge - Implement the X86_64 ABI merging algorithm.
1505 ///
1506 /// Merge an accumulating classification \arg Accum with a field
1507 /// classification \arg Field.
1508 ///
1509 /// \param Accum - The accumulating classification. This should
1510 /// always be either NoClass or the result of a previous merge
1511 /// call. In addition, this should never be Memory (the caller
1512 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001513 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001514
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001515 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1516 ///
1517 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1518 /// final MEMORY or SSE classes when necessary.
1519 ///
1520 /// \param AggregateSize - The size of the current aggregate in
1521 /// the classification process.
1522 ///
1523 /// \param Lo - The classification for the parts of the type
1524 /// residing in the low word of the containing object.
1525 ///
1526 /// \param Hi - The classification for the parts of the type
1527 /// residing in the higher words of the containing object.
1528 ///
1529 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1530
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001531 /// classify - Determine the x86_64 register classes in which the
1532 /// given type T should be passed.
1533 ///
1534 /// \param Lo - The classification for the parts of the type
1535 /// residing in the low word of the containing object.
1536 ///
1537 /// \param Hi - The classification for the parts of the type
1538 /// residing in the high word of the containing object.
1539 ///
1540 /// \param OffsetBase - The bit offset of this type in the
1541 /// containing object. Some parameters are classified different
1542 /// depending on whether they straddle an eightbyte boundary.
1543 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001544 /// \param isNamedArg - Whether the argument in question is a "named"
1545 /// argument, as used in AMD64-ABI 3.5.7.
1546 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001547 /// If a word is unused its result will be NoClass; if a type should
1548 /// be passed in Memory then at least the classification of \arg Lo
1549 /// will be Memory.
1550 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001551 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001552 ///
1553 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1554 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001555 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1556 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001557
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001558 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001559 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1560 unsigned IROffset, QualType SourceTy,
1561 unsigned SourceOffset) const;
1562 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1563 unsigned IROffset, QualType SourceTy,
1564 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001565
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001566 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001567 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001568 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001569
1570 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001571 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001572 ///
1573 /// \param freeIntRegs - The number of free integer registers remaining
1574 /// available.
1575 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001576
Chris Lattner458b2aa2010-07-29 02:16:43 +00001577 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001578
Bill Wendling5cd41c42010-10-18 03:41:31 +00001579 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001580 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001581 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001582 unsigned &neededSSE,
1583 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001584
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001585 bool IsIllegalVectorType(QualType Ty) const;
1586
John McCalle0fda732011-04-21 01:20:55 +00001587 /// The 0.98 ABI revision clarified a lot of ambiguities,
1588 /// unfortunately in ways that were not always consistent with
1589 /// certain previous compilers. In particular, platforms which
1590 /// required strict binary compatibility with older versions of GCC
1591 /// may need to exempt themselves.
1592 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001593 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001594 }
1595
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001596 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001597 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1598 // 64-bit hardware.
1599 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001600
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001601public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001602 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1603 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001604 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001605 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001606
John McCalla729c622012-02-17 03:33:10 +00001607 bool isPassedUsingAVXType(QualType type) const {
1608 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001609 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001610 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1611 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001612 if (info.isDirect()) {
1613 llvm::Type *ty = info.getCoerceToType();
1614 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1615 return (vectorTy->getBitWidth() > 128);
1616 }
1617 return false;
1618 }
1619
Craig Topper4f12f102014-03-12 06:41:41 +00001620 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001621
Craig Topper4f12f102014-03-12 06:41:41 +00001622 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1623 CodeGenFunction &CGF) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001624
1625 bool has64BitPointers() const {
1626 return Has64BitPointers;
1627 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001628};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001629
Chris Lattner04dc9572010-08-31 16:44:54 +00001630/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001631class WinX86_64ABIInfo : public ABIInfo {
1632
Reid Kleckner80944df2014-10-31 22:00:51 +00001633 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1634 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001635
Chris Lattner04dc9572010-08-31 16:44:54 +00001636public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001637 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1638
Craig Topper4f12f102014-03-12 06:41:41 +00001639 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001640
Craig Topper4f12f102014-03-12 06:41:41 +00001641 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1642 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001643
1644 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1645 // FIXME: Assumes vectorcall is in use.
1646 return isX86VectorTypeForVectorCall(getContext(), Ty);
1647 }
1648
1649 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1650 uint64_t NumMembers) const override {
1651 // FIXME: Assumes vectorcall is in use.
1652 return isX86VectorCallAggregateSmallEnough(NumMembers);
1653 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001654};
1655
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001656class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1657public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001658 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001659 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001660
John McCalla729c622012-02-17 03:33:10 +00001661 const X86_64ABIInfo &getABIInfo() const {
1662 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1663 }
1664
Craig Topper4f12f102014-03-12 06:41:41 +00001665 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001666 return 7;
1667 }
1668
1669 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001670 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001671 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001672
John McCall943fae92010-05-27 06:19:26 +00001673 // 0-15 are the 16 integer registers.
1674 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001675 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001676 return false;
1677 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001678
Jay Foad7c57be32011-07-11 09:56:20 +00001679 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001680 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001681 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001682 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1683 }
1684
John McCalla729c622012-02-17 03:33:10 +00001685 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001686 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001687 // The default CC on x86-64 sets %al to the number of SSA
1688 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001689 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001690 // that when AVX types are involved: the ABI explicitly states it is
1691 // undefined, and it doesn't work in practice because of how the ABI
1692 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001693 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001694 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001695 for (CallArgList::const_iterator
1696 it = args.begin(), ie = args.end(); it != ie; ++it) {
1697 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1698 HasAVXType = true;
1699 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001700 }
1701 }
John McCalla729c622012-02-17 03:33:10 +00001702
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001703 if (!HasAVXType)
1704 return true;
1705 }
John McCallcbc038a2011-09-21 08:08:30 +00001706
John McCalla729c622012-02-17 03:33:10 +00001707 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001708 }
1709
Craig Topper4f12f102014-03-12 06:41:41 +00001710 llvm::Constant *
1711 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001712 unsigned Sig;
1713 if (getABIInfo().has64BitPointers())
1714 Sig = (0xeb << 0) | // jmp rel8
1715 (0x0a << 8) | // .+0x0c
1716 ('F' << 16) |
1717 ('T' << 24);
1718 else
1719 Sig = (0xeb << 0) | // jmp rel8
1720 (0x06 << 8) | // .+0x08
1721 ('F' << 16) |
1722 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001723 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1724 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001725};
1726
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001727class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1728public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001729 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1730 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001731
1732 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001733 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001734 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00001735 // If the argument contains a space, enclose it in quotes.
1736 if (Lib.find(" ") != StringRef::npos)
1737 Opt += "\"" + Lib.str() + "\"";
1738 else
1739 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001740 }
1741};
1742
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001743static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001744 // If the argument does not end in .lib, automatically add the suffix.
1745 // If the argument contains a space, enclose it in quotes.
1746 // This matches the behavior of MSVC.
1747 bool Quote = (Lib.find(" ") != StringRef::npos);
1748 std::string ArgStr = Quote ? "\"" : "";
1749 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001750 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001751 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001752 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001753 return ArgStr;
1754}
1755
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001756class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1757public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001758 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1759 bool d, bool p, bool w, unsigned RegParms)
1760 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001761
Eric Christopher162c91c2015-06-05 22:03:00 +00001762 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001763 CodeGen::CodeGenModule &CGM) const override;
1764
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001765 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001766 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001767 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001768 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001769 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001770
1771 void getDetectMismatchOption(llvm::StringRef Name,
1772 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001773 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001774 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001775 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001776};
1777
Hans Wennborg77dc2362015-01-20 19:45:50 +00001778static void addStackProbeSizeTargetAttribute(const Decl *D,
1779 llvm::GlobalValue *GV,
1780 CodeGen::CodeGenModule &CGM) {
1781 if (isa<FunctionDecl>(D)) {
1782 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1783 llvm::Function *Fn = cast<llvm::Function>(GV);
1784
Eric Christopher7565e0d2015-05-29 23:09:49 +00001785 Fn->addFnAttr("stack-probe-size",
1786 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00001787 }
1788 }
1789}
1790
Eric Christopher162c91c2015-06-05 22:03:00 +00001791void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001792 llvm::GlobalValue *GV,
1793 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001794 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001795
1796 addStackProbeSizeTargetAttribute(D, GV, CGM);
1797}
1798
Chris Lattner04dc9572010-08-31 16:44:54 +00001799class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1800public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001801 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1802 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001803 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001804
Eric Christopher162c91c2015-06-05 22:03:00 +00001805 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001806 CodeGen::CodeGenModule &CGM) const override;
1807
Craig Topper4f12f102014-03-12 06:41:41 +00001808 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001809 return 7;
1810 }
1811
1812 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001813 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001814 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001815
Chris Lattner04dc9572010-08-31 16:44:54 +00001816 // 0-15 are the 16 integer registers.
1817 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001818 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001819 return false;
1820 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001821
1822 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001823 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001824 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001825 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001826 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001827
1828 void getDetectMismatchOption(llvm::StringRef Name,
1829 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001830 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001831 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001832 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001833};
1834
Eric Christopher162c91c2015-06-05 22:03:00 +00001835void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001836 llvm::GlobalValue *GV,
1837 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001838 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001839
1840 addStackProbeSizeTargetAttribute(D, GV, CGM);
1841}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001842}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001843
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001844void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1845 Class &Hi) const {
1846 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1847 //
1848 // (a) If one of the classes is Memory, the whole argument is passed in
1849 // memory.
1850 //
1851 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1852 // memory.
1853 //
1854 // (c) If the size of the aggregate exceeds two eightbytes and the first
1855 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1856 // argument is passed in memory. NOTE: This is necessary to keep the
1857 // ABI working for processors that don't support the __m256 type.
1858 //
1859 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1860 //
1861 // Some of these are enforced by the merging logic. Others can arise
1862 // only with unions; for example:
1863 // union { _Complex double; unsigned; }
1864 //
1865 // Note that clauses (b) and (c) were added in 0.98.
1866 //
1867 if (Hi == Memory)
1868 Lo = Memory;
1869 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1870 Lo = Memory;
1871 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1872 Lo = Memory;
1873 if (Hi == SSEUp && Lo != SSE)
1874 Hi = SSE;
1875}
1876
Chris Lattnerd776fb12010-06-28 21:43:59 +00001877X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001878 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1879 // classified recursively so that always two fields are
1880 // considered. The resulting class is calculated according to
1881 // the classes of the fields in the eightbyte:
1882 //
1883 // (a) If both classes are equal, this is the resulting class.
1884 //
1885 // (b) If one of the classes is NO_CLASS, the resulting class is
1886 // the other class.
1887 //
1888 // (c) If one of the classes is MEMORY, the result is the MEMORY
1889 // class.
1890 //
1891 // (d) If one of the classes is INTEGER, the result is the
1892 // INTEGER.
1893 //
1894 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1895 // MEMORY is used as class.
1896 //
1897 // (f) Otherwise class SSE is used.
1898
1899 // Accum should never be memory (we should have returned) or
1900 // ComplexX87 (because this cannot be passed in a structure).
1901 assert((Accum != Memory && Accum != ComplexX87) &&
1902 "Invalid accumulated classification during merge.");
1903 if (Accum == Field || Field == NoClass)
1904 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001905 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001906 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001907 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001908 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001909 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001910 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001911 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1912 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001913 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001914 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001915}
1916
Chris Lattner5c740f12010-06-30 19:14:05 +00001917void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001918 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001919 // FIXME: This code can be simplified by introducing a simple value class for
1920 // Class pairs with appropriate constructor methods for the various
1921 // situations.
1922
1923 // FIXME: Some of the split computations are wrong; unaligned vectors
1924 // shouldn't be passed in registers for example, so there is no chance they
1925 // can straddle an eightbyte. Verify & simplify.
1926
1927 Lo = Hi = NoClass;
1928
1929 Class &Current = OffsetBase < 64 ? Lo : Hi;
1930 Current = Memory;
1931
John McCall9dd450b2009-09-21 23:43:11 +00001932 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001933 BuiltinType::Kind k = BT->getKind();
1934
1935 if (k == BuiltinType::Void) {
1936 Current = NoClass;
1937 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1938 Lo = Integer;
1939 Hi = Integer;
1940 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1941 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00001942 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001943 Current = SSE;
1944 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00001945 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1946 if (LDF == &llvm::APFloat::IEEEquad) {
1947 Lo = SSE;
1948 Hi = SSEUp;
1949 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
1950 Lo = X87;
1951 Hi = X87Up;
1952 } else if (LDF == &llvm::APFloat::IEEEdouble) {
1953 Current = SSE;
1954 } else
1955 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001956 }
1957 // FIXME: _Decimal32 and _Decimal64 are SSE.
1958 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001959 return;
1960 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001961
Chris Lattnerd776fb12010-06-28 21:43:59 +00001962 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001963 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001964 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001965 return;
1966 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001967
Chris Lattnerd776fb12010-06-28 21:43:59 +00001968 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001969 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001970 return;
1971 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001972
Chris Lattnerd776fb12010-06-28 21:43:59 +00001973 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001974 if (Ty->isMemberFunctionPointerType()) {
1975 if (Has64BitPointers) {
1976 // If Has64BitPointers, this is an {i64, i64}, so classify both
1977 // Lo and Hi now.
1978 Lo = Hi = Integer;
1979 } else {
1980 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1981 // straddles an eightbyte boundary, Hi should be classified as well.
1982 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1983 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1984 if (EB_FuncPtr != EB_ThisAdj) {
1985 Lo = Hi = Integer;
1986 } else {
1987 Current = Integer;
1988 }
1989 }
1990 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001991 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001992 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001993 return;
1994 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001995
Chris Lattnerd776fb12010-06-28 21:43:59 +00001996 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001997 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00001998 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
1999 // gcc passes the following as integer:
2000 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2001 // 2 bytes - <2 x char>, <1 x short>
2002 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002003 Current = Integer;
2004
2005 // If this type crosses an eightbyte boundary, it should be
2006 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002007 uint64_t EB_Lo = (OffsetBase) / 64;
2008 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2009 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002010 Hi = Lo;
2011 } else if (Size == 64) {
2012 // gcc passes <1 x double> in memory. :(
2013 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
2014 return;
2015
2016 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00002017 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00002018 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2019 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
2020 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002021 Current = Integer;
2022 else
2023 Current = SSE;
2024
2025 // If this type crosses an eightbyte boundary, it should be
2026 // split.
2027 if (OffsetBase && OffsetBase != 64)
2028 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002029 } else if (Size == 128 ||
2030 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002031 // Arguments of 256-bits are split into four eightbyte chunks. The
2032 // least significant one belongs to class SSE and all the others to class
2033 // SSEUP. The original Lo and Hi design considers that types can't be
2034 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2035 // This design isn't correct for 256-bits, but since there're no cases
2036 // where the upper parts would need to be inspected, avoid adding
2037 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002038 //
2039 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2040 // registers if they are "named", i.e. not part of the "..." of a
2041 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002042 //
2043 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2044 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002045 Lo = SSE;
2046 Hi = SSEUp;
2047 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002048 return;
2049 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002050
Chris Lattnerd776fb12010-06-28 21:43:59 +00002051 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002052 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002053
Chris Lattner2b037972010-07-29 02:01:43 +00002054 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002055 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002056 if (Size <= 64)
2057 Current = Integer;
2058 else if (Size <= 128)
2059 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002060 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002061 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002062 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002063 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002064 } else if (ET == getContext().LongDoubleTy) {
2065 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2066 if (LDF == &llvm::APFloat::IEEEquad)
2067 Current = Memory;
2068 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2069 Current = ComplexX87;
2070 else if (LDF == &llvm::APFloat::IEEEdouble)
2071 Lo = Hi = SSE;
2072 else
2073 llvm_unreachable("unexpected long double representation!");
2074 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002075
2076 // If this complex type crosses an eightbyte boundary then it
2077 // should be split.
2078 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002079 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002080 if (Hi == NoClass && EB_Real != EB_Imag)
2081 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002082
Chris Lattnerd776fb12010-06-28 21:43:59 +00002083 return;
2084 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002085
Chris Lattner2b037972010-07-29 02:01:43 +00002086 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002087 // Arrays are treated like structures.
2088
Chris Lattner2b037972010-07-29 02:01:43 +00002089 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002090
2091 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002092 // than four eightbytes, ..., it has class MEMORY.
2093 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002094 return;
2095
2096 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2097 // fields, it has class MEMORY.
2098 //
2099 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002100 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002101 return;
2102
2103 // Otherwise implement simplified merge. We could be smarter about
2104 // this, but it isn't worth it and would be harder to verify.
2105 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002106 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002107 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002108
2109 // The only case a 256-bit wide vector could be used is when the array
2110 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2111 // to work for sizes wider than 128, early check and fallback to memory.
2112 if (Size > 128 && EltSize != 256)
2113 return;
2114
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002115 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2116 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002117 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002118 Lo = merge(Lo, FieldLo);
2119 Hi = merge(Hi, FieldHi);
2120 if (Lo == Memory || Hi == Memory)
2121 break;
2122 }
2123
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002124 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002125 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002126 return;
2127 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002128
Chris Lattnerd776fb12010-06-28 21:43:59 +00002129 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002130 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002131
2132 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002133 // than four eightbytes, ..., it has class MEMORY.
2134 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002135 return;
2136
Anders Carlsson20759ad2009-09-16 15:53:40 +00002137 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2138 // copy constructor or a non-trivial destructor, it is passed by invisible
2139 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002140 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002141 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002142
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002143 const RecordDecl *RD = RT->getDecl();
2144
2145 // Assume variable sized types are passed in memory.
2146 if (RD->hasFlexibleArrayMember())
2147 return;
2148
Chris Lattner2b037972010-07-29 02:01:43 +00002149 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002150
2151 // Reset Lo class, this will be recomputed.
2152 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002153
2154 // If this is a C++ record, classify the bases first.
2155 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002156 for (const auto &I : CXXRD->bases()) {
2157 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002158 "Unexpected base class!");
2159 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002160 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002161
2162 // Classify this field.
2163 //
2164 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2165 // single eightbyte, each is classified separately. Each eightbyte gets
2166 // initialized to class NO_CLASS.
2167 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002168 uint64_t Offset =
2169 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002170 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002171 Lo = merge(Lo, FieldLo);
2172 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002173 if (Lo == Memory || Hi == Memory) {
2174 postMerge(Size, Lo, Hi);
2175 return;
2176 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002177 }
2178 }
2179
2180 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002181 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002182 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002183 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002184 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2185 bool BitField = i->isBitField();
2186
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002187 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2188 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002189 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002190 // The only case a 256-bit wide vector could be used is when the struct
2191 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2192 // to work for sizes wider than 128, early check and fallback to memory.
2193 //
2194 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2195 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002196 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002197 return;
2198 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002199 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002200 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002201 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002202 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002203 return;
2204 }
2205
2206 // Classify this field.
2207 //
2208 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2209 // exceeds a single eightbyte, each is classified
2210 // separately. Each eightbyte gets initialized to class
2211 // NO_CLASS.
2212 Class FieldLo, FieldHi;
2213
2214 // Bit-fields require special handling, they do not force the
2215 // structure to be passed in memory even if unaligned, and
2216 // therefore they can straddle an eightbyte.
2217 if (BitField) {
2218 // Ignore padding bit-fields.
2219 if (i->isUnnamedBitfield())
2220 continue;
2221
2222 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002223 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002224
2225 uint64_t EB_Lo = Offset / 64;
2226 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002227
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002228 if (EB_Lo) {
2229 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2230 FieldLo = NoClass;
2231 FieldHi = Integer;
2232 } else {
2233 FieldLo = Integer;
2234 FieldHi = EB_Hi ? Integer : NoClass;
2235 }
2236 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002237 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002238 Lo = merge(Lo, FieldLo);
2239 Hi = merge(Hi, FieldHi);
2240 if (Lo == Memory || Hi == Memory)
2241 break;
2242 }
2243
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002244 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002245 }
2246}
2247
Chris Lattner22a931e2010-06-29 06:01:59 +00002248ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002249 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2250 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002251 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002252 // Treat an enum type as its underlying type.
2253 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2254 Ty = EnumTy->getDecl()->getIntegerType();
2255
2256 return (Ty->isPromotableIntegerType() ?
2257 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2258 }
2259
2260 return ABIArgInfo::getIndirect(0);
2261}
2262
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002263bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2264 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2265 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002266 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002267 if (Size <= 64 || Size > LargestVector)
2268 return true;
2269 }
2270
2271 return false;
2272}
2273
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002274ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2275 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002276 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2277 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002278 //
2279 // This assumption is optimistic, as there could be free registers available
2280 // when we need to pass this argument in memory, and LLVM could try to pass
2281 // the argument in the free register. This does not seem to happen currently,
2282 // but this code would be much safer if we could mark the argument with
2283 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002284 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002285 // Treat an enum type as its underlying type.
2286 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2287 Ty = EnumTy->getDecl()->getIntegerType();
2288
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002289 return (Ty->isPromotableIntegerType() ?
2290 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002291 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002292
Mark Lacey3825e832013-10-06 01:33:34 +00002293 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002294 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002295
Chris Lattner44c2b902011-05-22 23:21:23 +00002296 // Compute the byval alignment. We specify the alignment of the byval in all
2297 // cases so that the mid-level optimizer knows the alignment of the byval.
2298 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002299
2300 // Attempt to avoid passing indirect results using byval when possible. This
2301 // is important for good codegen.
2302 //
2303 // We do this by coercing the value into a scalar type which the backend can
2304 // handle naturally (i.e., without using byval).
2305 //
2306 // For simplicity, we currently only do this when we have exhausted all of the
2307 // free integer registers. Doing this when there are free integer registers
2308 // would require more care, as we would have to ensure that the coerced value
2309 // did not claim the unused register. That would require either reording the
2310 // arguments to the function (so that any subsequent inreg values came first),
2311 // or only doing this optimization when there were no following arguments that
2312 // might be inreg.
2313 //
2314 // We currently expect it to be rare (particularly in well written code) for
2315 // arguments to be passed on the stack when there are still free integer
2316 // registers available (this would typically imply large structs being passed
2317 // by value), so this seems like a fair tradeoff for now.
2318 //
2319 // We can revisit this if the backend grows support for 'onstack' parameter
2320 // attributes. See PR12193.
2321 if (freeIntRegs == 0) {
2322 uint64_t Size = getContext().getTypeSize(Ty);
2323
2324 // If this type fits in an eightbyte, coerce it into the matching integral
2325 // type, which will end up on the stack (with alignment 8).
2326 if (Align == 8 && Size <= 64)
2327 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2328 Size));
2329 }
2330
Chris Lattner44c2b902011-05-22 23:21:23 +00002331 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002332}
2333
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002334/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2335/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002336llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002337 // Wrapper structs/arrays that only contain vectors are passed just like
2338 // vectors; strip them off if present.
2339 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2340 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002341
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002342 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002343 if (isa<llvm::VectorType>(IRType) ||
2344 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002345 return IRType;
2346
2347 // We couldn't find the preferred IR vector type for 'Ty'.
2348 uint64_t Size = getContext().getTypeSize(Ty);
2349 assert((Size == 128 || Size == 256) && "Invalid type found!");
2350
2351 // Return a LLVM IR vector type based on the size of 'Ty'.
2352 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2353 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002354}
2355
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002356/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2357/// is known to either be off the end of the specified type or being in
2358/// alignment padding. The user type specified is known to be at most 128 bits
2359/// in size, and have passed through X86_64ABIInfo::classify with a successful
2360/// classification that put one of the two halves in the INTEGER class.
2361///
2362/// It is conservatively correct to return false.
2363static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2364 unsigned EndBit, ASTContext &Context) {
2365 // If the bytes being queried are off the end of the type, there is no user
2366 // data hiding here. This handles analysis of builtins, vectors and other
2367 // types that don't contain interesting padding.
2368 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2369 if (TySize <= StartBit)
2370 return true;
2371
Chris Lattner98076a22010-07-29 07:43:55 +00002372 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2373 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2374 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2375
2376 // Check each element to see if the element overlaps with the queried range.
2377 for (unsigned i = 0; i != NumElts; ++i) {
2378 // If the element is after the span we care about, then we're done..
2379 unsigned EltOffset = i*EltSize;
2380 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002381
Chris Lattner98076a22010-07-29 07:43:55 +00002382 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2383 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2384 EndBit-EltOffset, Context))
2385 return false;
2386 }
2387 // If it overlaps no elements, then it is safe to process as padding.
2388 return true;
2389 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002390
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002391 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2392 const RecordDecl *RD = RT->getDecl();
2393 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002394
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002395 // If this is a C++ record, check the bases first.
2396 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002397 for (const auto &I : CXXRD->bases()) {
2398 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002399 "Unexpected base class!");
2400 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002401 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002402
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002403 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002404 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002405 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002406
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002407 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002408 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002409 EndBit-BaseOffset, Context))
2410 return false;
2411 }
2412 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002413
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002414 // Verify that no field has data that overlaps the region of interest. Yes
2415 // this could be sped up a lot by being smarter about queried fields,
2416 // however we're only looking at structs up to 16 bytes, so we don't care
2417 // much.
2418 unsigned idx = 0;
2419 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2420 i != e; ++i, ++idx) {
2421 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002422
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002423 // If we found a field after the region we care about, then we're done.
2424 if (FieldOffset >= EndBit) break;
2425
2426 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2427 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2428 Context))
2429 return false;
2430 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002431
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002432 // If nothing in this record overlapped the area of interest, then we're
2433 // clean.
2434 return true;
2435 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002436
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002437 return false;
2438}
2439
Chris Lattnere556a712010-07-29 18:39:32 +00002440/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2441/// float member at the specified offset. For example, {int,{float}} has a
2442/// float at offset 4. It is conservatively correct for this routine to return
2443/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002444static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002445 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002446 // Base case if we find a float.
2447 if (IROffset == 0 && IRType->isFloatTy())
2448 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002449
Chris Lattnere556a712010-07-29 18:39:32 +00002450 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002451 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002452 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2453 unsigned Elt = SL->getElementContainingOffset(IROffset);
2454 IROffset -= SL->getElementOffset(Elt);
2455 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2456 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002457
Chris Lattnere556a712010-07-29 18:39:32 +00002458 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002459 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2460 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002461 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2462 IROffset -= IROffset/EltSize*EltSize;
2463 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2464 }
2465
2466 return false;
2467}
2468
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002469
2470/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2471/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002472llvm::Type *X86_64ABIInfo::
2473GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002474 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002475 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002476 // pass as float if the last 4 bytes is just padding. This happens for
2477 // structs that contain 3 floats.
2478 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2479 SourceOffset*8+64, getContext()))
2480 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002481
Chris Lattnere556a712010-07-29 18:39:32 +00002482 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2483 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2484 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002485 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2486 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002487 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002488
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002489 return llvm::Type::getDoubleTy(getVMContext());
2490}
2491
2492
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002493/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2494/// an 8-byte GPR. This means that we either have a scalar or we are talking
2495/// about the high or low part of an up-to-16-byte struct. This routine picks
2496/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002497/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2498/// etc).
2499///
2500/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2501/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2502/// the 8-byte value references. PrefType may be null.
2503///
Alp Toker9907f082014-07-09 14:06:35 +00002504/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002505/// an offset into this that we're processing (which is always either 0 or 8).
2506///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002507llvm::Type *X86_64ABIInfo::
2508GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002509 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002510 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2511 // returning an 8-byte unit starting with it. See if we can safely use it.
2512 if (IROffset == 0) {
2513 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002514 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2515 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002516 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002517
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002518 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2519 // goodness in the source type is just tail padding. This is allowed to
2520 // kick in for struct {double,int} on the int, but not on
2521 // struct{double,int,int} because we wouldn't return the second int. We
2522 // have to do this analysis on the source type because we can't depend on
2523 // unions being lowered a specific way etc.
2524 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002525 IRType->isIntegerTy(32) ||
2526 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2527 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2528 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002529
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002530 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2531 SourceOffset*8+64, getContext()))
2532 return IRType;
2533 }
2534 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002535
Chris Lattner2192fe52011-07-18 04:24:23 +00002536 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002537 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002538 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002539 if (IROffset < SL->getSizeInBytes()) {
2540 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2541 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002542
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002543 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2544 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002545 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002546 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002547
Chris Lattner2192fe52011-07-18 04:24:23 +00002548 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002549 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002550 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002551 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002552 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2553 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002554 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002555
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002556 // Okay, we don't have any better idea of what to pass, so we pass this in an
2557 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002558 unsigned TySizeInBytes =
2559 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002560
Chris Lattner3f763422010-07-29 17:34:39 +00002561 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002562
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002563 // It is always safe to classify this as an integer type up to i64 that
2564 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002565 return llvm::IntegerType::get(getVMContext(),
2566 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002567}
2568
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002569
2570/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2571/// be used as elements of a two register pair to pass or return, return a
2572/// first class aggregate to represent them. For example, if the low part of
2573/// a by-value argument should be passed as i32* and the high part as float,
2574/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002575static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002576GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002577 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002578 // In order to correctly satisfy the ABI, we need to the high part to start
2579 // at offset 8. If the high and low parts we inferred are both 4-byte types
2580 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2581 // the second element at offset 8. Check for this:
2582 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2583 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002584 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002585 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002586
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002587 // To handle this, we have to increase the size of the low part so that the
2588 // second element will start at an 8 byte offset. We can't increase the size
2589 // of the second element because it might make us access off the end of the
2590 // struct.
2591 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002592 // There are usually two sorts of types the ABI generation code can produce
2593 // for the low part of a pair that aren't 8 bytes in size: float or
2594 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2595 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002596 // Promote these to a larger type.
2597 if (Lo->isFloatTy())
2598 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2599 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002600 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2601 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002602 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2603 }
2604 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002605
Reid Kleckneree7cf842014-12-01 22:02:27 +00002606 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002607
2608
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002609 // Verify that the second element is at an 8-byte offset.
2610 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2611 "Invalid x86-64 argument pair!");
2612 return Result;
2613}
2614
Chris Lattner31faff52010-07-28 23:06:14 +00002615ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002616classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002617 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2618 // classification algorithm.
2619 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002620 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002621
2622 // Check some invariants.
2623 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002624 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2625
Craig Topper8a13c412014-05-21 05:09:00 +00002626 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002627 switch (Lo) {
2628 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002629 if (Hi == NoClass)
2630 return ABIArgInfo::getIgnore();
2631 // If the low part is just padding, it takes no register, leave ResType
2632 // null.
2633 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2634 "Unknown missing lo part");
2635 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002636
2637 case SSEUp:
2638 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002639 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002640
2641 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2642 // hidden argument.
2643 case Memory:
2644 return getIndirectReturnResult(RetTy);
2645
2646 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2647 // available register of the sequence %rax, %rdx is used.
2648 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002649 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002650
Chris Lattner1f3a0632010-07-29 21:42:50 +00002651 // If we have a sign or zero extended integer, make sure to return Extend
2652 // so that the parameter gets the right LLVM IR attributes.
2653 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2654 // Treat an enum type as its underlying type.
2655 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2656 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002657
Chris Lattner1f3a0632010-07-29 21:42:50 +00002658 if (RetTy->isIntegralOrEnumerationType() &&
2659 RetTy->isPromotableIntegerType())
2660 return ABIArgInfo::getExtend();
2661 }
Chris Lattner31faff52010-07-28 23:06:14 +00002662 break;
2663
2664 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2665 // available SSE register of the sequence %xmm0, %xmm1 is used.
2666 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002667 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002668 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002669
2670 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2671 // returned on the X87 stack in %st0 as 80-bit x87 number.
2672 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002673 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002674 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002675
2676 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2677 // part of the value is returned in %st0 and the imaginary part in
2678 // %st1.
2679 case ComplexX87:
2680 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002681 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002682 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002683 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002684 break;
2685 }
2686
Craig Topper8a13c412014-05-21 05:09:00 +00002687 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002688 switch (Hi) {
2689 // Memory was handled previously and X87 should
2690 // never occur as a hi class.
2691 case Memory:
2692 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002693 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002694
2695 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002696 case NoClass:
2697 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002698
Chris Lattner52b3c132010-09-01 00:20:33 +00002699 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002700 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002701 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2702 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002703 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002704 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002705 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002706 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2707 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002708 break;
2709
2710 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002711 // is passed in the next available eightbyte chunk if the last used
2712 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002713 //
Chris Lattner57540c52011-04-15 05:22:18 +00002714 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002715 case SSEUp:
2716 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002717 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002718 break;
2719
2720 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2721 // returned together with the previous X87 value in %st0.
2722 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002723 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002724 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002725 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002726 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002727 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002728 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002729 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2730 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002731 }
Chris Lattner31faff52010-07-28 23:06:14 +00002732 break;
2733 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002734
Chris Lattner52b3c132010-09-01 00:20:33 +00002735 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002736 // known to pass in the high eightbyte of the result. We do this by forming a
2737 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002738 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002739 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002740
Chris Lattner1f3a0632010-07-29 21:42:50 +00002741 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002742}
2743
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002744ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002745 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2746 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002747 const
2748{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002749 Ty = useFirstFieldIfTransparentUnion(Ty);
2750
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002751 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002752 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002753
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002754 // Check some invariants.
2755 // FIXME: Enforce these by construction.
2756 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002757 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2758
2759 neededInt = 0;
2760 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002761 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002762 switch (Lo) {
2763 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002764 if (Hi == NoClass)
2765 return ABIArgInfo::getIgnore();
2766 // If the low part is just padding, it takes no register, leave ResType
2767 // null.
2768 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2769 "Unknown missing lo part");
2770 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002771
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002772 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2773 // on the stack.
2774 case Memory:
2775
2776 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2777 // COMPLEX_X87, it is passed in memory.
2778 case X87:
2779 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002780 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002781 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002782 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002783
2784 case SSEUp:
2785 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002786 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002787
2788 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2789 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2790 // and %r9 is used.
2791 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002792 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002793
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002794 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002795 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002796
2797 // If we have a sign or zero extended integer, make sure to return Extend
2798 // so that the parameter gets the right LLVM IR attributes.
2799 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2800 // Treat an enum type as its underlying type.
2801 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2802 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002803
Chris Lattner1f3a0632010-07-29 21:42:50 +00002804 if (Ty->isIntegralOrEnumerationType() &&
2805 Ty->isPromotableIntegerType())
2806 return ABIArgInfo::getExtend();
2807 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002808
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002809 break;
2810
2811 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2812 // available SSE register is used, the registers are taken in the
2813 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002814 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002815 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002816 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002817 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002818 break;
2819 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002820 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002821
Craig Topper8a13c412014-05-21 05:09:00 +00002822 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002823 switch (Hi) {
2824 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002825 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002826 // which is passed in memory.
2827 case Memory:
2828 case X87:
2829 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002830 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002831
2832 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002833
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002834 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002835 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002836 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002837 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002838
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002839 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2840 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002841 break;
2842
2843 // X87Up generally doesn't occur here (long double is passed in
2844 // memory), except in situations involving unions.
2845 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002846 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002847 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002848
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002849 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2850 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002851
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002852 ++neededSSE;
2853 break;
2854
2855 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2856 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002857 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002858 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002859 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002860 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002861 break;
2862 }
2863
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002864 // If a high part was specified, merge it together with the low part. It is
2865 // known to pass in the high eightbyte of the result. We do this by forming a
2866 // first class struct aggregate with the high and low part: {low, high}
2867 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002868 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002869
Chris Lattner1f3a0632010-07-29 21:42:50 +00002870 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002871}
2872
Chris Lattner22326a12010-07-29 02:31:05 +00002873void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002874
Reid Kleckner40ca9132014-05-13 22:05:45 +00002875 if (!getCXXABI().classifyReturnType(FI))
2876 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002877
2878 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002879 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002880
2881 // If the return value is indirect, then the hidden argument is consuming one
2882 // integer register.
2883 if (FI.getReturnInfo().isIndirect())
2884 --freeIntRegs;
2885
Peter Collingbournef7706832014-12-12 23:41:25 +00002886 // The chain argument effectively gives us another free register.
2887 if (FI.isChainCall())
2888 ++freeIntRegs;
2889
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002890 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002891 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2892 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002893 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002894 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002895 it != ie; ++it, ++ArgNo) {
2896 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002897
Bill Wendling9987c0e2010-10-18 23:51:38 +00002898 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002899 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002900 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002901
2902 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2903 // eightbyte of an argument, the whole argument is passed on the
2904 // stack. If registers have already been assigned for some
2905 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002906 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002907 freeIntRegs -= neededInt;
2908 freeSSERegs -= neededSSE;
2909 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002910 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002911 }
2912 }
2913}
2914
2915static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2916 QualType Ty,
2917 CodeGenFunction &CGF) {
David Blaikie2e804282015-04-05 22:47:07 +00002918 llvm::Value *overflow_arg_area_p = CGF.Builder.CreateStructGEP(
2919 nullptr, VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002920 llvm::Value *overflow_arg_area =
2921 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2922
2923 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2924 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002925 // It isn't stated explicitly in the standard, but in practice we use
2926 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002927 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2928 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002929 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002930 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002931 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002932 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2933 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002934 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002935 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002936 overflow_arg_area =
2937 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2938 overflow_arg_area->getType(),
2939 "overflow_arg_area.align");
2940 }
2941
2942 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002943 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002944 llvm::Value *Res =
2945 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002946 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002947
2948 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2949 // l->overflow_arg_area + sizeof(type).
2950 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2951 // an 8 byte boundary.
2952
2953 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002954 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002955 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002956 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2957 "overflow_arg_area.next");
2958 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2959
2960 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2961 return Res;
2962}
2963
2964llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2965 CodeGenFunction &CGF) const {
2966 // Assume that va_list type is correct; should be pointer to LLVM type:
2967 // struct {
2968 // i32 gp_offset;
2969 // i32 fp_offset;
2970 // i8* overflow_arg_area;
2971 // i8* reg_save_area;
2972 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002973 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002974
Chris Lattner9723d6c2010-03-11 18:19:55 +00002975 Ty = CGF.getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00002976 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002977 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002978
2979 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2980 // in the registers. If not go to step 7.
2981 if (!neededInt && !neededSSE)
2982 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2983
2984 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2985 // general purpose registers needed to pass type and num_fp to hold
2986 // the number of floating point registers needed.
2987
2988 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2989 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2990 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2991 //
2992 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2993 // register save space).
2994
Craig Topper8a13c412014-05-21 05:09:00 +00002995 llvm::Value *InRegs = nullptr;
2996 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2997 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002998 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002999 gp_offset_p =
3000 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003001 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003002 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3003 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003004 }
3005
3006 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003007 fp_offset_p =
3008 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003009 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3010 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003011 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3012 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003013 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3014 }
3015
3016 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3017 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3018 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3019 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3020
3021 // Emit code to load the value if it was passed in registers.
3022
3023 CGF.EmitBlock(InRegBlock);
3024
3025 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3026 // an offset of l->gp_offset and/or l->fp_offset. This may require
3027 // copying to a temporary location in case the parameter is passed
3028 // in different register classes or requires an alignment greater
3029 // than 8 for general purpose registers and 16 for XMM registers.
3030 //
3031 // FIXME: This really results in shameful code when we end up needing to
3032 // collect arguments from different places; often what should result in a
3033 // simple assembling of a structure from scattered addresses has many more
3034 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003035 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
David Blaikie1ed728c2015-04-05 22:45:47 +00003036 llvm::Value *RegAddr = CGF.Builder.CreateLoad(
3037 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3), "reg_save_area");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003038 if (neededInt && neededSSE) {
3039 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003040 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003041 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00003042 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
3043 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003044 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003045 llvm::Type *TyLo = ST->getElementType(0);
3046 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003047 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003048 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003049 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3050 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003051 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
3052 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003053 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3054 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003055 llvm::Value *V =
3056 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
David Blaikie1ed728c2015-04-05 22:45:47 +00003057 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003058 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
David Blaikie1ed728c2015-04-05 22:45:47 +00003059 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003060
Owen Anderson170229f2009-07-14 23:10:40 +00003061 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003062 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003063 } else if (neededInt) {
3064 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
3065 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003066 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00003067
3068 // Copy to a temporary if necessary to ensure the appropriate alignment.
3069 std::pair<CharUnits, CharUnits> SizeAlign =
3070 CGF.getContext().getTypeInfoInChars(Ty);
3071 uint64_t TySize = SizeAlign.first.getQuantity();
3072 unsigned TyAlign = SizeAlign.second.getQuantity();
3073 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00003074 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
3075 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
3076 RegAddr = Tmp;
3077 }
Chris Lattner0cf24192010-06-28 20:05:43 +00003078 } else if (neededSSE == 1) {
3079 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
3080 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
3081 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003082 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003083 assert(neededSSE == 2 && "Invalid number of needed registers!");
3084 // SSE registers are spaced 16 bytes apart in the register save
3085 // area, we need to collect the two eightbytes together.
3086 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00003087 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00003088 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00003089 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00003090 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003091 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003092 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
3093 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00003094 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
3095 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00003096 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Chris Lattner0cf24192010-06-28 20:05:43 +00003097 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
3098 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00003099 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Chris Lattner0cf24192010-06-28 20:05:43 +00003100 RegAddr = CGF.Builder.CreateBitCast(Tmp,
3101 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003102 }
3103
3104 // AMD64-ABI 3.5.7p5: Step 5. Set:
3105 // l->gp_offset = l->gp_offset + num_gp * 8
3106 // l->fp_offset = l->fp_offset + num_fp * 16.
3107 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003108 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003109 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3110 gp_offset_p);
3111 }
3112 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003113 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003114 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3115 fp_offset_p);
3116 }
3117 CGF.EmitBranch(ContBlock);
3118
3119 // Emit code to load the value if it was passed in memory.
3120
3121 CGF.EmitBlock(InMemBlock);
3122 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
3123
3124 // Return the appropriate result.
3125
3126 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00003127 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003128 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003129 ResAddr->addIncoming(RegAddr, InRegBlock);
3130 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003131 return ResAddr;
3132}
3133
Reid Kleckner80944df2014-10-31 22:00:51 +00003134ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3135 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003136
3137 if (Ty->isVoidType())
3138 return ABIArgInfo::getIgnore();
3139
3140 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3141 Ty = EnumTy->getDecl()->getIntegerType();
3142
Reid Kleckner80944df2014-10-31 22:00:51 +00003143 TypeInfo Info = getContext().getTypeInfo(Ty);
3144 uint64_t Width = Info.Width;
3145 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003146
Reid Kleckner9005f412014-05-02 00:51:20 +00003147 const RecordType *RT = Ty->getAs<RecordType>();
3148 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003149 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003150 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003151 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3152 }
3153
3154 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003155 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3156
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003157 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003158 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003159 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003160 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003161 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003162
Reid Kleckner80944df2014-10-31 22:00:51 +00003163 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3164 // other targets.
3165 const Type *Base = nullptr;
3166 uint64_t NumElts = 0;
3167 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3168 if (FreeSSERegs >= NumElts) {
3169 FreeSSERegs -= NumElts;
3170 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3171 return ABIArgInfo::getDirect();
3172 return ABIArgInfo::getExpand();
3173 }
3174 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3175 }
3176
3177
Reid Klecknerec87fec2014-05-02 01:17:12 +00003178 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003179 // If the member pointer is represented by an LLVM int or ptr, pass it
3180 // directly.
3181 llvm::Type *LLTy = CGT.ConvertType(Ty);
3182 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3183 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003184 }
3185
Michael Kuperstein4f818702015-02-24 09:35:58 +00003186 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003187 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3188 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003189 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003190 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003191
Reid Kleckner9005f412014-05-02 00:51:20 +00003192 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003193 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003194 }
3195
Julien Lerouge10dcff82014-08-27 00:36:55 +00003196 // Bool type is always extended to the ABI, other builtin types are not
3197 // extended.
3198 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3199 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003200 return ABIArgInfo::getExtend();
3201
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003202 return ABIArgInfo::getDirect();
3203}
3204
3205void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003206 bool IsVectorCall =
3207 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003208
Reid Kleckner80944df2014-10-31 22:00:51 +00003209 // We can use up to 4 SSE return registers with vectorcall.
3210 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3211 if (!getCXXABI().classifyReturnType(FI))
3212 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3213
3214 // We can use up to 6 SSE register parameters with vectorcall.
3215 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003216 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003217 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003218}
3219
Chris Lattner04dc9572010-08-31 16:44:54 +00003220llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3221 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003222 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003223
Chris Lattner04dc9572010-08-31 16:44:54 +00003224 CGBuilderTy &Builder = CGF.Builder;
3225 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3226 "ap");
3227 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3228 llvm::Type *PTy =
3229 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3230 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3231
3232 uint64_t Offset =
3233 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3234 llvm::Value *NextAddr =
3235 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3236 "ap.next");
3237 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3238
3239 return AddrTyped;
3240}
Chris Lattner0cf24192010-06-28 20:05:43 +00003241
John McCallea8d8bb2010-03-11 00:10:12 +00003242// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003243namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003244/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3245class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003246public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003247 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3248
3249 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3250 CodeGenFunction &CGF) const override;
3251};
3252
3253class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3254public:
Eric Christopher7565e0d2015-05-29 23:09:49 +00003255 PPC32TargetCodeGenInfo(CodeGenTypes &CGT)
3256 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003257
Craig Topper4f12f102014-03-12 06:41:41 +00003258 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003259 // This is recovered from gcc output.
3260 return 1; // r1 is the dedicated stack pointer
3261 }
3262
3263 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003264 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003265};
3266
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003267}
John McCallea8d8bb2010-03-11 00:10:12 +00003268
Roman Divacky8a12d842014-11-03 18:32:54 +00003269llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3270 QualType Ty,
3271 CodeGenFunction &CGF) const {
3272 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3273 // TODO: Implement this. For now ignore.
3274 (void)CTy;
3275 return nullptr;
3276 }
3277
3278 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003279 bool isInt =
3280 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003281 llvm::Type *CharPtr = CGF.Int8PtrTy;
3282 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3283
3284 CGBuilderTy &Builder = CGF.Builder;
3285 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3286 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003287 llvm::Value *FPRPtrAsInt =
3288 Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
Roman Divacky8a12d842014-11-03 18:32:54 +00003289 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003290 llvm::Value *OverflowAreaPtrAsInt =
3291 Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3292 llvm::Value *OverflowAreaPtr =
3293 Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3294 llvm::Value *RegsaveAreaPtrAsInt =
3295 Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3296 llvm::Value *RegsaveAreaPtr =
3297 Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
Roman Divacky8a12d842014-11-03 18:32:54 +00003298 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3299 // Align GPR when TY is i64.
3300 if (isI64) {
3301 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3302 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3303 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3304 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3305 }
3306 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
Eric Christopher7565e0d2015-05-29 23:09:49 +00003307 llvm::Value *OverflowArea =
3308 Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3309 llvm::Value *OverflowAreaAsInt =
3310 Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3311 llvm::Value *RegsaveArea =
3312 Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3313 llvm::Value *RegsaveAreaAsInt =
3314 Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
Roman Divacky8a12d842014-11-03 18:32:54 +00003315
Eric Christopher7565e0d2015-05-29 23:09:49 +00003316 llvm::Value *CC =
3317 Builder.CreateICmpULT(isInt ? GPR : FPR, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003318
Eric Christopher7565e0d2015-05-29 23:09:49 +00003319 llvm::Value *RegConstant =
3320 Builder.CreateMul(isInt ? GPR : FPR, Builder.getInt8(isInt ? 4 : 8));
Roman Divacky8a12d842014-11-03 18:32:54 +00003321
Eric Christopher7565e0d2015-05-29 23:09:49 +00003322 llvm::Value *OurReg = Builder.CreateAdd(
3323 RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003324
3325 if (Ty->isFloatingType())
3326 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3327
3328 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3329 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3330 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3331
3332 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3333
3334 CGF.EmitBlock(UsingRegs);
3335
3336 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3337 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3338 // Increase the GPR/FPR indexes.
3339 if (isInt) {
3340 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3341 Builder.CreateStore(GPR, GPRPtr);
3342 } else {
3343 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3344 Builder.CreateStore(FPR, FPRPtr);
3345 }
3346 CGF.EmitBranch(Cont);
3347
3348 CGF.EmitBlock(UsingOverflow);
3349
3350 // Increase the overflow area.
3351 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003352 OverflowAreaAsInt =
3353 Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3354 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr),
3355 OverflowAreaPtr);
Roman Divacky8a12d842014-11-03 18:32:54 +00003356 CGF.EmitBranch(Cont);
3357
3358 CGF.EmitBlock(Cont);
3359
3360 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3361 Result->addIncoming(Result1, UsingRegs);
3362 Result->addIncoming(Result2, UsingOverflow);
3363
3364 if (Ty->isAggregateType()) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00003365 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003366 return Builder.CreateLoad(AGGPtr, false, "aggr");
3367 }
3368
3369 return Result;
3370}
3371
John McCallea8d8bb2010-03-11 00:10:12 +00003372bool
3373PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3374 llvm::Value *Address) const {
3375 // This is calculated from the LLVM and GCC tables and verified
3376 // against gcc output. AFAIK all ABIs use the same encoding.
3377
3378 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003379
Chris Lattnerece04092012-02-07 00:39:47 +00003380 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003381 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3382 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3383 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3384
3385 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003386 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003387
3388 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003389 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003390
3391 // 64-76 are various 4-byte special-purpose registers:
3392 // 64: mq
3393 // 65: lr
3394 // 66: ctr
3395 // 67: ap
3396 // 68-75 cr0-7
3397 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003398 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003399
3400 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003401 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003402
3403 // 109: vrsave
3404 // 110: vscr
3405 // 111: spe_acc
3406 // 112: spefscr
3407 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003408 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003409
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003410 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003411}
3412
Roman Divackyd966e722012-05-09 18:22:46 +00003413// PowerPC-64
3414
3415namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003416/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3417class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003418public:
3419 enum ABIKind {
3420 ELFv1 = 0,
3421 ELFv2
3422 };
3423
3424private:
3425 static const unsigned GPRBits = 64;
3426 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003427 bool HasQPX;
3428
3429 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3430 // will be passed in a QPX register.
3431 bool IsQPXVectorTy(const Type *Ty) const {
3432 if (!HasQPX)
3433 return false;
3434
3435 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3436 unsigned NumElements = VT->getNumElements();
3437 if (NumElements == 1)
3438 return false;
3439
3440 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3441 if (getContext().getTypeSize(Ty) <= 256)
3442 return true;
3443 } else if (VT->getElementType()->
3444 isSpecificBuiltinType(BuiltinType::Float)) {
3445 if (getContext().getTypeSize(Ty) <= 128)
3446 return true;
3447 }
3448 }
3449
3450 return false;
3451 }
3452
3453 bool IsQPXVectorTy(QualType Ty) const {
3454 return IsQPXVectorTy(Ty.getTypePtr());
3455 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003456
3457public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003458 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3459 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003460
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003461 bool isPromotableTypeForABI(QualType Ty) const;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003462 bool isAlignedParamType(QualType Ty, bool &Align32) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003463
3464 ABIArgInfo classifyReturnType(QualType RetTy) const;
3465 ABIArgInfo classifyArgumentType(QualType Ty) const;
3466
Reid Klecknere9f6a712014-10-31 17:10:41 +00003467 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3468 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3469 uint64_t Members) const override;
3470
Bill Schmidt84d37792012-10-12 19:26:17 +00003471 // TODO: We can add more logic to computeInfo to improve performance.
3472 // Example: For aggregate arguments that fit in a register, we could
3473 // use getDirectInReg (as is done below for structs containing a single
3474 // floating-point value) to avoid pushing them to memory on function
3475 // entry. This would require changing the logic in PPCISelLowering
3476 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003477 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003478 if (!getCXXABI().classifyReturnType(FI))
3479 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003480 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003481 // We rely on the default argument classification for the most part.
3482 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003483 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003484 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003485 if (T) {
3486 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003487 if (IsQPXVectorTy(T) ||
3488 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003489 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003490 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003491 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003492 continue;
3493 }
3494 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003495 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003496 }
3497 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003498
Craig Topper4f12f102014-03-12 06:41:41 +00003499 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3500 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003501};
3502
3503class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003504
Bill Schmidt25cb3492012-10-03 19:18:57 +00003505public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003506 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003507 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003508 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003509
Craig Topper4f12f102014-03-12 06:41:41 +00003510 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003511 // This is recovered from gcc output.
3512 return 1; // r1 is the dedicated stack pointer
3513 }
3514
3515 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003516 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003517};
3518
Roman Divackyd966e722012-05-09 18:22:46 +00003519class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3520public:
3521 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3522
Craig Topper4f12f102014-03-12 06:41:41 +00003523 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003524 // This is recovered from gcc output.
3525 return 1; // r1 is the dedicated stack pointer
3526 }
3527
3528 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003529 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003530};
3531
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003532}
Roman Divackyd966e722012-05-09 18:22:46 +00003533
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003534// Return true if the ABI requires Ty to be passed sign- or zero-
3535// extended to 64 bits.
3536bool
3537PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3538 // Treat an enum type as its underlying type.
3539 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3540 Ty = EnumTy->getDecl()->getIntegerType();
3541
3542 // Promotable integer types are required to be promoted by the ABI.
3543 if (Ty->isPromotableIntegerType())
3544 return true;
3545
3546 // In addition to the usual promotable integer types, we also need to
3547 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3548 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3549 switch (BT->getKind()) {
3550 case BuiltinType::Int:
3551 case BuiltinType::UInt:
3552 return true;
3553 default:
3554 break;
3555 }
3556
3557 return false;
3558}
3559
Ulrich Weigand581badc2014-07-10 17:20:07 +00003560/// isAlignedParamType - Determine whether a type requires 16-byte
3561/// alignment in the parameter area.
3562bool
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003563PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty, bool &Align32) const {
3564 Align32 = false;
3565
Ulrich Weigand581badc2014-07-10 17:20:07 +00003566 // Complex types are passed just like their elements.
3567 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3568 Ty = CTy->getElementType();
3569
3570 // Only vector types of size 16 bytes need alignment (larger types are
3571 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003572 if (IsQPXVectorTy(Ty)) {
3573 if (getContext().getTypeSize(Ty) > 128)
3574 Align32 = true;
3575
3576 return true;
3577 } else if (Ty->isVectorType()) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003578 return getContext().getTypeSize(Ty) == 128;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003579 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003580
3581 // For single-element float/vector structs, we consider the whole type
3582 // to have the same alignment requirements as its single element.
3583 const Type *AlignAsType = nullptr;
3584 const Type *EltType = isSingleElementStruct(Ty, getContext());
3585 if (EltType) {
3586 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003587 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003588 getContext().getTypeSize(EltType) == 128) ||
3589 (BT && BT->isFloatingPoint()))
3590 AlignAsType = EltType;
3591 }
3592
Ulrich Weigandb7122372014-07-21 00:48:09 +00003593 // Likewise for ELFv2 homogeneous aggregates.
3594 const Type *Base = nullptr;
3595 uint64_t Members = 0;
3596 if (!AlignAsType && Kind == ELFv2 &&
3597 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3598 AlignAsType = Base;
3599
Ulrich Weigand581badc2014-07-10 17:20:07 +00003600 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003601 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3602 if (getContext().getTypeSize(AlignAsType) > 128)
3603 Align32 = true;
3604
3605 return true;
3606 } else if (AlignAsType) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003607 return AlignAsType->isVectorType();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003608 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003609
3610 // Otherwise, we only need alignment for any aggregate type that
3611 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003612 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3613 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
3614 Align32 = true;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003615 return true;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003616 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003617
3618 return false;
3619}
3620
Ulrich Weigandb7122372014-07-21 00:48:09 +00003621/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3622/// aggregate. Base is set to the base element type, and Members is set
3623/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003624bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3625 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003626 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3627 uint64_t NElements = AT->getSize().getZExtValue();
3628 if (NElements == 0)
3629 return false;
3630 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3631 return false;
3632 Members *= NElements;
3633 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3634 const RecordDecl *RD = RT->getDecl();
3635 if (RD->hasFlexibleArrayMember())
3636 return false;
3637
3638 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003639
3640 // If this is a C++ record, check the bases first.
3641 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3642 for (const auto &I : CXXRD->bases()) {
3643 // Ignore empty records.
3644 if (isEmptyRecord(getContext(), I.getType(), true))
3645 continue;
3646
3647 uint64_t FldMembers;
3648 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3649 return false;
3650
3651 Members += FldMembers;
3652 }
3653 }
3654
Ulrich Weigandb7122372014-07-21 00:48:09 +00003655 for (const auto *FD : RD->fields()) {
3656 // Ignore (non-zero arrays of) empty records.
3657 QualType FT = FD->getType();
3658 while (const ConstantArrayType *AT =
3659 getContext().getAsConstantArrayType(FT)) {
3660 if (AT->getSize().getZExtValue() == 0)
3661 return false;
3662 FT = AT->getElementType();
3663 }
3664 if (isEmptyRecord(getContext(), FT, true))
3665 continue;
3666
3667 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3668 if (getContext().getLangOpts().CPlusPlus &&
3669 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3670 continue;
3671
3672 uint64_t FldMembers;
3673 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3674 return false;
3675
3676 Members = (RD->isUnion() ?
3677 std::max(Members, FldMembers) : Members + FldMembers);
3678 }
3679
3680 if (!Base)
3681 return false;
3682
3683 // Ensure there is no padding.
3684 if (getContext().getTypeSize(Base) * Members !=
3685 getContext().getTypeSize(Ty))
3686 return false;
3687 } else {
3688 Members = 1;
3689 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3690 Members = 2;
3691 Ty = CT->getElementType();
3692 }
3693
Reid Klecknere9f6a712014-10-31 17:10:41 +00003694 // Most ABIs only support float, double, and some vector type widths.
3695 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003696 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003697
3698 // The base type must be the same for all members. Types that
3699 // agree in both total size and mode (float vs. vector) are
3700 // treated as being equivalent here.
3701 const Type *TyPtr = Ty.getTypePtr();
3702 if (!Base)
3703 Base = TyPtr;
3704
3705 if (Base->isVectorType() != TyPtr->isVectorType() ||
3706 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3707 return false;
3708 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003709 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3710}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003711
Reid Klecknere9f6a712014-10-31 17:10:41 +00003712bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3713 // Homogeneous aggregates for ELFv2 must have base types of float,
3714 // double, long double, or 128-bit vectors.
3715 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3716 if (BT->getKind() == BuiltinType::Float ||
3717 BT->getKind() == BuiltinType::Double ||
3718 BT->getKind() == BuiltinType::LongDouble)
3719 return true;
3720 }
3721 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003722 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003723 return true;
3724 }
3725 return false;
3726}
3727
3728bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3729 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003730 // Vector types require one register, floating point types require one
3731 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003732 uint32_t NumRegs =
3733 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003734
3735 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003736 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003737}
3738
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003739ABIArgInfo
3740PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003741 Ty = useFirstFieldIfTransparentUnion(Ty);
3742
Bill Schmidt90b22c92012-11-27 02:46:43 +00003743 if (Ty->isAnyComplexType())
3744 return ABIArgInfo::getDirect();
3745
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003746 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3747 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003748 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003749 uint64_t Size = getContext().getTypeSize(Ty);
3750 if (Size > 128)
3751 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3752 else if (Size < 128) {
3753 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3754 return ABIArgInfo::getDirect(CoerceTy);
3755 }
3756 }
3757
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003758 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003759 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003760 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003761
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003762 bool Align32;
3763 uint64_t ABIAlign = isAlignedParamType(Ty, Align32) ?
3764 (Align32 ? 32 : 16) : 8;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003765 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003766
3767 // ELFv2 homogeneous aggregates are passed as array types.
3768 const Type *Base = nullptr;
3769 uint64_t Members = 0;
3770 if (Kind == ELFv2 &&
3771 isHomogeneousAggregate(Ty, Base, Members)) {
3772 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3773 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3774 return ABIArgInfo::getDirect(CoerceTy);
3775 }
3776
Ulrich Weigand601957f2014-07-21 00:56:36 +00003777 // If an aggregate may end up fully in registers, we do not
3778 // use the ByVal method, but pass the aggregate as array.
3779 // This is usually beneficial since we avoid forcing the
3780 // back-end to store the argument to memory.
3781 uint64_t Bits = getContext().getTypeSize(Ty);
3782 if (Bits > 0 && Bits <= 8 * GPRBits) {
3783 llvm::Type *CoerceTy;
3784
3785 // Types up to 8 bytes are passed as integer type (which will be
3786 // properly aligned in the argument save area doubleword).
3787 if (Bits <= GPRBits)
3788 CoerceTy = llvm::IntegerType::get(getVMContext(),
3789 llvm::RoundUpToAlignment(Bits, 8));
3790 // Larger types are passed as arrays, with the base type selected
3791 // according to the required alignment in the save area.
3792 else {
3793 uint64_t RegBits = ABIAlign * 8;
3794 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3795 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3796 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3797 }
3798
3799 return ABIArgInfo::getDirect(CoerceTy);
3800 }
3801
Ulrich Weigandb7122372014-07-21 00:48:09 +00003802 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003803 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3804 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003805 }
3806
3807 return (isPromotableTypeForABI(Ty) ?
3808 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3809}
3810
3811ABIArgInfo
3812PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3813 if (RetTy->isVoidType())
3814 return ABIArgInfo::getIgnore();
3815
Bill Schmidta3d121c2012-12-17 04:20:17 +00003816 if (RetTy->isAnyComplexType())
3817 return ABIArgInfo::getDirect();
3818
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003819 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3820 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003821 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003822 uint64_t Size = getContext().getTypeSize(RetTy);
3823 if (Size > 128)
3824 return ABIArgInfo::getIndirect(0);
3825 else if (Size < 128) {
3826 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3827 return ABIArgInfo::getDirect(CoerceTy);
3828 }
3829 }
3830
Ulrich Weigandb7122372014-07-21 00:48:09 +00003831 if (isAggregateTypeForABI(RetTy)) {
3832 // ELFv2 homogeneous aggregates are returned as array types.
3833 const Type *Base = nullptr;
3834 uint64_t Members = 0;
3835 if (Kind == ELFv2 &&
3836 isHomogeneousAggregate(RetTy, Base, Members)) {
3837 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3838 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3839 return ABIArgInfo::getDirect(CoerceTy);
3840 }
3841
3842 // ELFv2 small aggregates are returned in up to two registers.
3843 uint64_t Bits = getContext().getTypeSize(RetTy);
3844 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3845 if (Bits == 0)
3846 return ABIArgInfo::getIgnore();
3847
3848 llvm::Type *CoerceTy;
3849 if (Bits > GPRBits) {
3850 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003851 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003852 } else
3853 CoerceTy = llvm::IntegerType::get(getVMContext(),
3854 llvm::RoundUpToAlignment(Bits, 8));
3855 return ABIArgInfo::getDirect(CoerceTy);
3856 }
3857
3858 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003859 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003860 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003861
3862 return (isPromotableTypeForABI(RetTy) ?
3863 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3864}
3865
Bill Schmidt25cb3492012-10-03 19:18:57 +00003866// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3867llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3868 QualType Ty,
3869 CodeGenFunction &CGF) const {
3870 llvm::Type *BP = CGF.Int8PtrTy;
3871 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3872
3873 CGBuilderTy &Builder = CGF.Builder;
3874 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3875 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3876
Ulrich Weigand581badc2014-07-10 17:20:07 +00003877 // Handle types that require 16-byte alignment in the parameter save area.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003878 bool Align32;
3879 if (isAlignedParamType(Ty, Align32)) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003880 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003881 AddrAsInt = Builder.CreateAdd(AddrAsInt,
3882 Builder.getInt64(Align32 ? 31 : 15));
3883 AddrAsInt = Builder.CreateAnd(AddrAsInt,
3884 Builder.getInt64(Align32 ? -32 : -16));
Ulrich Weigand581badc2014-07-10 17:20:07 +00003885 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3886 }
3887
Bill Schmidt924c4782013-01-14 17:45:36 +00003888 // Update the va_list pointer. The pointer should be bumped by the
3889 // size of the object. We can trust getTypeSize() except for a complex
3890 // type whose base type is smaller than a doubleword. For these, the
3891 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003892 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003893 QualType BaseTy;
3894 unsigned CplxBaseSize = 0;
3895
3896 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3897 BaseTy = CTy->getElementType();
3898 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3899 if (CplxBaseSize < 8)
3900 SizeInBytes = 16;
3901 }
3902
Bill Schmidt25cb3492012-10-03 19:18:57 +00003903 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3904 llvm::Value *NextAddr =
3905 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3906 "ap.next");
3907 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3908
Bill Schmidt924c4782013-01-14 17:45:36 +00003909 // If we have a complex type and the base type is smaller than 8 bytes,
3910 // the ABI calls for the real and imaginary parts to be right-adjusted
3911 // in separate doublewords. However, Clang expects us to produce a
3912 // pointer to a structure with the two parts packed tightly. So generate
3913 // loads of the real and imaginary parts relative to the va_list pointer,
3914 // and store them to a temporary structure.
3915 if (CplxBaseSize && CplxBaseSize < 8) {
3916 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3917 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003918 if (CGF.CGM.getDataLayout().isBigEndian()) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00003919 RealAddr =
3920 Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3921 ImagAddr =
3922 Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003923 } else {
3924 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3925 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003926 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3927 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3928 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3929 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3930 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
David Blaikie2e804282015-04-05 22:47:07 +00003931 llvm::AllocaInst *Ptr =
3932 CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), "vacplx");
3933 llvm::Value *RealPtr =
3934 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 0, ".real");
3935 llvm::Value *ImagPtr =
3936 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 1, ".imag");
Bill Schmidt924c4782013-01-14 17:45:36 +00003937 Builder.CreateStore(Real, RealPtr, false);
3938 Builder.CreateStore(Imag, ImagPtr, false);
3939 return Ptr;
3940 }
3941
Bill Schmidt25cb3492012-10-03 19:18:57 +00003942 // If the argument is smaller than 8 bytes, it is right-adjusted in
3943 // its doubleword slot. Adjust the pointer to pick it up from the
3944 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003945 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003946 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3947 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3948 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3949 }
3950
3951 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3952 return Builder.CreateBitCast(Addr, PTy);
3953}
3954
3955static bool
3956PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3957 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003958 // This is calculated from the LLVM and GCC tables and verified
3959 // against gcc output. AFAIK all ABIs use the same encoding.
3960
3961 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3962
3963 llvm::IntegerType *i8 = CGF.Int8Ty;
3964 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3965 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3966 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3967
3968 // 0-31: r0-31, the 8-byte general-purpose registers
3969 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3970
3971 // 32-63: fp0-31, the 8-byte floating-point registers
3972 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3973
3974 // 64-76 are various 4-byte special-purpose registers:
3975 // 64: mq
3976 // 65: lr
3977 // 66: ctr
3978 // 67: ap
3979 // 68-75 cr0-7
3980 // 76: xer
3981 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3982
3983 // 77-108: v0-31, the 16-byte vector registers
3984 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3985
3986 // 109: vrsave
3987 // 110: vscr
3988 // 111: spe_acc
3989 // 112: spefscr
3990 // 113: sfp
3991 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3992
3993 return false;
3994}
John McCallea8d8bb2010-03-11 00:10:12 +00003995
Bill Schmidt25cb3492012-10-03 19:18:57 +00003996bool
3997PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3998 CodeGen::CodeGenFunction &CGF,
3999 llvm::Value *Address) const {
4000
4001 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4002}
4003
4004bool
4005PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4006 llvm::Value *Address) const {
4007
4008 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4009}
4010
Chris Lattner0cf24192010-06-28 20:05:43 +00004011//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004012// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004013//===----------------------------------------------------------------------===//
4014
4015namespace {
4016
Tim Northover573cbee2014-05-24 12:52:07 +00004017class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004018public:
4019 enum ABIKind {
4020 AAPCS = 0,
4021 DarwinPCS
4022 };
4023
4024private:
4025 ABIKind Kind;
4026
4027public:
Tim Northover573cbee2014-05-24 12:52:07 +00004028 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004029
4030private:
4031 ABIKind getABIKind() const { return Kind; }
4032 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4033
4034 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004035 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004036 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4037 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4038 uint64_t Members) const override;
4039
Tim Northovera2ee4332014-03-29 15:09:45 +00004040 bool isIllegalVectorType(QualType Ty) const;
4041
David Blaikie1cbb9712014-11-14 19:09:44 +00004042 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004043 if (!getCXXABI().classifyReturnType(FI))
4044 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004045
Tim Northoverb047bfa2014-11-27 21:02:49 +00004046 for (auto &it : FI.arguments())
4047 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004048 }
4049
4050 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
4051 CodeGenFunction &CGF) const;
4052
4053 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
4054 CodeGenFunction &CGF) const;
4055
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004056 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4057 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004058 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4059 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4060 }
4061};
4062
Tim Northover573cbee2014-05-24 12:52:07 +00004063class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004064public:
Tim Northover573cbee2014-05-24 12:52:07 +00004065 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4066 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004067
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004068 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004069 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4070 }
4071
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004072 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4073 return 31;
4074 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004075
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004076 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004077};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004078}
Tim Northovera2ee4332014-03-29 15:09:45 +00004079
Tim Northoverb047bfa2014-11-27 21:02:49 +00004080ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004081 Ty = useFirstFieldIfTransparentUnion(Ty);
4082
Tim Northovera2ee4332014-03-29 15:09:45 +00004083 // Handle illegal vector types here.
4084 if (isIllegalVectorType(Ty)) {
4085 uint64_t Size = getContext().getTypeSize(Ty);
4086 if (Size <= 32) {
4087 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004088 return ABIArgInfo::getDirect(ResType);
4089 }
4090 if (Size == 64) {
4091 llvm::Type *ResType =
4092 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004093 return ABIArgInfo::getDirect(ResType);
4094 }
4095 if (Size == 128) {
4096 llvm::Type *ResType =
4097 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004098 return ABIArgInfo::getDirect(ResType);
4099 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004100 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4101 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004102
4103 if (!isAggregateTypeForABI(Ty)) {
4104 // Treat an enum type as its underlying type.
4105 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4106 Ty = EnumTy->getDecl()->getIntegerType();
4107
Tim Northovera2ee4332014-03-29 15:09:45 +00004108 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4109 ? ABIArgInfo::getExtend()
4110 : ABIArgInfo::getDirect());
4111 }
4112
4113 // Structures with either a non-trivial destructor or a non-trivial
4114 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004115 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004116 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00004117 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004118 }
4119
4120 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4121 // elsewhere for GNU compatibility.
4122 if (isEmptyRecord(getContext(), Ty, true)) {
4123 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4124 return ABIArgInfo::getIgnore();
4125
Tim Northovera2ee4332014-03-29 15:09:45 +00004126 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4127 }
4128
4129 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004130 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004131 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004132 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004133 return ABIArgInfo::getDirect(
4134 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004135 }
4136
4137 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4138 uint64_t Size = getContext().getTypeSize(Ty);
4139 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004140 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004141 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004142
Tim Northovera2ee4332014-03-29 15:09:45 +00004143 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4144 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004145 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004146 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4147 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4148 }
4149 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4150 }
4151
Tim Northovera2ee4332014-03-29 15:09:45 +00004152 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4153}
4154
Tim Northover573cbee2014-05-24 12:52:07 +00004155ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004156 if (RetTy->isVoidType())
4157 return ABIArgInfo::getIgnore();
4158
4159 // Large vector types should be returned via memory.
4160 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4161 return ABIArgInfo::getIndirect(0);
4162
4163 if (!isAggregateTypeForABI(RetTy)) {
4164 // Treat an enum type as its underlying type.
4165 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4166 RetTy = EnumTy->getDecl()->getIntegerType();
4167
Tim Northover4dab6982014-04-18 13:46:08 +00004168 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4169 ? ABIArgInfo::getExtend()
4170 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004171 }
4172
Tim Northovera2ee4332014-03-29 15:09:45 +00004173 if (isEmptyRecord(getContext(), RetTy, true))
4174 return ABIArgInfo::getIgnore();
4175
Craig Topper8a13c412014-05-21 05:09:00 +00004176 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004177 uint64_t Members = 0;
4178 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004179 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4180 return ABIArgInfo::getDirect();
4181
4182 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4183 uint64_t Size = getContext().getTypeSize(RetTy);
4184 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004185 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004186 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004187
4188 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4189 // For aggregates with 16-byte alignment, we use i128.
4190 if (Alignment < 128 && Size == 128) {
4191 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4192 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4193 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004194 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4195 }
4196
4197 return ABIArgInfo::getIndirect(0);
4198}
4199
Tim Northover573cbee2014-05-24 12:52:07 +00004200/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4201bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004202 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4203 // Check whether VT is legal.
4204 unsigned NumElements = VT->getNumElements();
4205 uint64_t Size = getContext().getTypeSize(VT);
4206 // NumElements should be power of 2 between 1 and 16.
4207 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4208 return true;
4209 return Size != 64 && (Size != 128 || NumElements == 1);
4210 }
4211 return false;
4212}
4213
Reid Klecknere9f6a712014-10-31 17:10:41 +00004214bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4215 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4216 // point type or a short-vector type. This is the same as the 32-bit ABI,
4217 // but with the difference that any floating-point type is allowed,
4218 // including __fp16.
4219 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4220 if (BT->isFloatingPoint())
4221 return true;
4222 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4223 unsigned VecSize = getContext().getTypeSize(VT);
4224 if (VecSize == 64 || VecSize == 128)
4225 return true;
4226 }
4227 return false;
4228}
4229
4230bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4231 uint64_t Members) const {
4232 return Members <= 4;
4233}
4234
Tim Northoverb047bfa2014-11-27 21:02:49 +00004235llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4236 QualType Ty,
4237 CodeGenFunction &CGF) const {
4238 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004239 bool IsIndirect = AI.isIndirect();
4240
Tim Northoverb047bfa2014-11-27 21:02:49 +00004241 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4242 if (IsIndirect)
4243 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4244 else if (AI.getCoerceToType())
4245 BaseTy = AI.getCoerceToType();
4246
4247 unsigned NumRegs = 1;
4248 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4249 BaseTy = ArrTy->getElementType();
4250 NumRegs = ArrTy->getNumElements();
4251 }
4252 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4253
Tim Northovera2ee4332014-03-29 15:09:45 +00004254 // The AArch64 va_list type and handling is specified in the Procedure Call
4255 // Standard, section B.4:
4256 //
4257 // struct {
4258 // void *__stack;
4259 // void *__gr_top;
4260 // void *__vr_top;
4261 // int __gr_offs;
4262 // int __vr_offs;
4263 // };
4264
4265 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4266 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4267 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4268 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4269 auto &Ctx = CGF.getContext();
4270
Craig Topper8a13c412014-05-21 05:09:00 +00004271 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004272 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004273 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4274 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004275 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004276 reg_offs_p =
4277 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004278 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4279 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004280 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004281 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004282 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004283 reg_offs_p =
4284 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004285 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4286 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004287 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004288 }
4289
4290 //=======================================
4291 // Find out where argument was passed
4292 //=======================================
4293
4294 // If reg_offs >= 0 we're already using the stack for this type of
4295 // argument. We don't want to keep updating reg_offs (in case it overflows,
4296 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4297 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004298 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004299 UsingStack = CGF.Builder.CreateICmpSGE(
4300 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4301
4302 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4303
4304 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004305 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004306 CGF.EmitBlock(MaybeRegBlock);
4307
4308 // Integer arguments may need to correct register alignment (for example a
4309 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4310 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004311 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004312 int Align = Ctx.getTypeAlign(Ty) / 8;
4313
4314 reg_offs = CGF.Builder.CreateAdd(
4315 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4316 "align_regoffs");
4317 reg_offs = CGF.Builder.CreateAnd(
4318 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4319 "aligned_regoffs");
4320 }
4321
4322 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004323 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004324 NewOffset = CGF.Builder.CreateAdd(
4325 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4326 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4327
4328 // Now we're in a position to decide whether this argument really was in
4329 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004330 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004331 InRegs = CGF.Builder.CreateICmpSLE(
4332 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4333
4334 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4335
4336 //=======================================
4337 // Argument was in registers
4338 //=======================================
4339
4340 // Now we emit the code for if the argument was originally passed in
4341 // registers. First start the appropriate block:
4342 CGF.EmitBlock(InRegBlock);
4343
Craig Topper8a13c412014-05-21 05:09:00 +00004344 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
David Blaikie2e804282015-04-05 22:47:07 +00004345 reg_top_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, reg_top_index,
4346 "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004347 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4348 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004349 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004350 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4351
4352 if (IsIndirect) {
4353 // If it's been passed indirectly (actually a struct), whatever we find from
4354 // stored registers or on the stack will actually be a struct **.
4355 MemTy = llvm::PointerType::getUnqual(MemTy);
4356 }
4357
Craig Topper8a13c412014-05-21 05:09:00 +00004358 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004359 uint64_t NumMembers = 0;
4360 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004361 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004362 // Homogeneous aggregates passed in registers will have their elements split
4363 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4364 // qN+1, ...). We reload and store into a temporary local variable
4365 // contiguously.
4366 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4367 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4368 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
David Blaikie1ed728c2015-04-05 22:45:47 +00004369 llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(HFATy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004370 int Offset = 0;
4371
4372 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4373 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4374 for (unsigned i = 0; i < NumMembers; ++i) {
4375 llvm::Value *BaseOffset =
4376 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4377 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4378 LoadAddr = CGF.Builder.CreateBitCast(
4379 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
David Blaikie2e804282015-04-05 22:47:07 +00004380 llvm::Value *StoreAddr =
4381 CGF.Builder.CreateStructGEP(Tmp->getAllocatedType(), Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00004382
4383 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4384 CGF.Builder.CreateStore(Elem, StoreAddr);
4385 }
4386
4387 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4388 } else {
4389 // Otherwise the object is contiguous in memory
4390 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004391 if (CGF.CGM.getDataLayout().isBigEndian() &&
4392 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004393 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4394 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4395 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4396
4397 BaseAddr = CGF.Builder.CreateAdd(
4398 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4399
4400 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4401 }
4402
4403 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4404 }
4405
4406 CGF.EmitBranch(ContBlock);
4407
4408 //=======================================
4409 // Argument was on the stack
4410 //=======================================
4411 CGF.EmitBlock(OnStackBlock);
4412
Craig Topper8a13c412014-05-21 05:09:00 +00004413 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
David Blaikie1ed728c2015-04-05 22:45:47 +00004414 stack_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "stack_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004415 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4416
4417 // Again, stack arguments may need realigmnent. In this case both integer and
4418 // floating-point ones might be affected.
4419 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4420 int Align = Ctx.getTypeAlign(Ty) / 8;
4421
4422 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4423
4424 OnStackAddr = CGF.Builder.CreateAdd(
4425 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4426 "align_stack");
4427 OnStackAddr = CGF.Builder.CreateAnd(
4428 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4429 "align_stack");
4430
4431 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4432 }
4433
4434 uint64_t StackSize;
4435 if (IsIndirect)
4436 StackSize = 8;
4437 else
4438 StackSize = Ctx.getTypeSize(Ty) / 8;
4439
4440 // All stack slots are 8 bytes
4441 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4442
4443 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4444 llvm::Value *NewStack =
4445 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4446
4447 // Write the new value of __stack for the next call to va_arg
4448 CGF.Builder.CreateStore(NewStack, stack_p);
4449
4450 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4451 Ctx.getTypeSize(Ty) < 64) {
4452 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4453 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4454
4455 OnStackAddr = CGF.Builder.CreateAdd(
4456 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4457
4458 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4459 }
4460
4461 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4462
4463 CGF.EmitBranch(ContBlock);
4464
4465 //=======================================
4466 // Tidy up
4467 //=======================================
4468 CGF.EmitBlock(ContBlock);
4469
4470 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4471 ResAddr->addIncoming(RegAddr, InRegBlock);
4472 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4473
4474 if (IsIndirect)
4475 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4476
4477 return ResAddr;
4478}
4479
Eric Christopher7565e0d2015-05-29 23:09:49 +00004480llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr,
4481 QualType Ty,
4482 CodeGenFunction &CGF) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004483 // We do not support va_arg for aggregates or illegal vector types.
4484 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4485 // other cases.
4486 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004487 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004488
4489 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4490 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4491
Craig Topper8a13c412014-05-21 05:09:00 +00004492 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004493 uint64_t Members = 0;
4494 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004495
4496 bool isIndirect = false;
4497 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4498 // be passed indirectly.
4499 if (Size > 16 && !isHA) {
4500 isIndirect = true;
4501 Size = 8;
4502 Align = 8;
4503 }
4504
4505 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4506 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4507
4508 CGBuilderTy &Builder = CGF.Builder;
4509 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4510 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4511
4512 if (isEmptyRecord(getContext(), Ty, true)) {
4513 // These are ignored for parameter passing purposes.
4514 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4515 return Builder.CreateBitCast(Addr, PTy);
4516 }
4517
4518 const uint64_t MinABIAlign = 8;
4519 if (Align > MinABIAlign) {
4520 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4521 Addr = Builder.CreateGEP(Addr, Offset);
4522 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4523 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4524 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4525 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4526 }
4527
4528 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4529 llvm::Value *NextAddr = Builder.CreateGEP(
4530 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4531 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4532
4533 if (isIndirect)
4534 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4535 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4536 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4537
4538 return AddrTyped;
4539}
4540
4541//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004542// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004543//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004544
4545namespace {
4546
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004547class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004548public:
4549 enum ABIKind {
4550 APCS = 0,
4551 AAPCS = 1,
4552 AAPCS_VFP
4553 };
4554
4555private:
4556 ABIKind Kind;
4557
4558public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004559 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004560 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004561 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004562
John McCall3480ef22011-08-30 01:42:09 +00004563 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004564 switch (getTarget().getTriple().getEnvironment()) {
4565 case llvm::Triple::Android:
4566 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004567 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004568 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004569 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004570 return true;
4571 default:
4572 return false;
4573 }
John McCall3480ef22011-08-30 01:42:09 +00004574 }
4575
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004576 bool isEABIHF() const {
4577 switch (getTarget().getTriple().getEnvironment()) {
4578 case llvm::Triple::EABIHF:
4579 case llvm::Triple::GNUEABIHF:
4580 return true;
4581 default:
4582 return false;
4583 }
4584 }
4585
Daniel Dunbar020daa92009-09-12 01:00:39 +00004586 ABIKind getABIKind() const { return Kind; }
4587
Tim Northovera484bc02013-10-01 14:34:25 +00004588private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004589 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004590 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004591 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004592
Reid Klecknere9f6a712014-10-31 17:10:41 +00004593 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4594 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4595 uint64_t Members) const override;
4596
Craig Topper4f12f102014-03-12 06:41:41 +00004597 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004598
Craig Topper4f12f102014-03-12 06:41:41 +00004599 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4600 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004601
4602 llvm::CallingConv::ID getLLVMDefaultCC() const;
4603 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004604 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004605};
4606
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004607class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4608public:
Chris Lattner2b037972010-07-29 02:01:43 +00004609 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4610 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004611
John McCall3480ef22011-08-30 01:42:09 +00004612 const ARMABIInfo &getABIInfo() const {
4613 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4614 }
4615
Craig Topper4f12f102014-03-12 06:41:41 +00004616 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004617 return 13;
4618 }
Roman Divackyc1617352011-05-18 19:36:54 +00004619
Craig Topper4f12f102014-03-12 06:41:41 +00004620 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004621 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4622 }
4623
Roman Divackyc1617352011-05-18 19:36:54 +00004624 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004625 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004626 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004627
4628 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004629 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004630 return false;
4631 }
John McCall3480ef22011-08-30 01:42:09 +00004632
Craig Topper4f12f102014-03-12 06:41:41 +00004633 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004634 if (getABIInfo().isEABI()) return 88;
4635 return TargetCodeGenInfo::getSizeOfUnwindException();
4636 }
Tim Northovera484bc02013-10-01 14:34:25 +00004637
Eric Christopher162c91c2015-06-05 22:03:00 +00004638 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004639 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004640 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4641 if (!FD)
4642 return;
4643
4644 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4645 if (!Attr)
4646 return;
4647
4648 const char *Kind;
4649 switch (Attr->getInterrupt()) {
4650 case ARMInterruptAttr::Generic: Kind = ""; break;
4651 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4652 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4653 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4654 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4655 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4656 }
4657
4658 llvm::Function *Fn = cast<llvm::Function>(GV);
4659
4660 Fn->addFnAttr("interrupt", Kind);
4661
4662 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4663 return;
4664
4665 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4666 // however this is not necessarily true on taking any interrupt. Instruct
4667 // the backend to perform a realignment as part of the function prologue.
4668 llvm::AttrBuilder B;
4669 B.addStackAlignmentAttr(8);
4670 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4671 llvm::AttributeSet::get(CGM.getLLVMContext(),
4672 llvm::AttributeSet::FunctionIndex,
4673 B));
4674 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004675};
4676
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004677class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4678 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4679 CodeGen::CodeGenModule &CGM) const;
4680
4681public:
4682 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4683 : ARMTargetCodeGenInfo(CGT, K) {}
4684
Eric Christopher162c91c2015-06-05 22:03:00 +00004685 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004686 CodeGen::CodeGenModule &CGM) const override;
4687};
4688
4689void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4690 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4691 if (!isa<FunctionDecl>(D))
4692 return;
4693 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4694 return;
4695
4696 llvm::Function *F = cast<llvm::Function>(GV);
4697 F->addFnAttr("stack-probe-size",
4698 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4699}
4700
Eric Christopher162c91c2015-06-05 22:03:00 +00004701void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004702 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004703 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004704 addStackProbeSizeTargetAttribute(D, GV, CGM);
4705}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004706}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004707
Chris Lattner22326a12010-07-29 02:31:05 +00004708void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004709 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004710 FI.getReturnInfo() =
4711 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004712
Tim Northoverbc784d12015-02-24 17:22:40 +00004713 for (auto &I : FI.arguments())
4714 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004715
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004716 // Always honor user-specified calling convention.
4717 if (FI.getCallingConvention() != llvm::CallingConv::C)
4718 return;
4719
John McCall882987f2013-02-28 19:01:20 +00004720 llvm::CallingConv::ID cc = getRuntimeCC();
4721 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004722 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004723}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004724
John McCall882987f2013-02-28 19:01:20 +00004725/// Return the default calling convention that LLVM will use.
4726llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4727 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004728 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004729 return llvm::CallingConv::ARM_AAPCS_VFP;
4730 else if (isEABI())
4731 return llvm::CallingConv::ARM_AAPCS;
4732 else
4733 return llvm::CallingConv::ARM_APCS;
4734}
4735
4736/// Return the calling convention that our ABI would like us to use
4737/// as the C calling convention.
4738llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004739 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004740 case APCS: return llvm::CallingConv::ARM_APCS;
4741 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4742 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004743 }
John McCall882987f2013-02-28 19:01:20 +00004744 llvm_unreachable("bad ABI kind");
4745}
4746
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004747void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004748 assert(getRuntimeCC() == llvm::CallingConv::C);
4749
4750 // Don't muddy up the IR with a ton of explicit annotations if
4751 // they'd just match what LLVM will infer from the triple.
4752 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4753 if (abiCC != getLLVMDefaultCC())
4754 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004755
4756 BuiltinCC = (getABIKind() == APCS ?
4757 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004758}
4759
Tim Northoverbc784d12015-02-24 17:22:40 +00004760ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4761 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004762 // 6.1.2.1 The following argument types are VFP CPRCs:
4763 // A single-precision floating-point type (including promoted
4764 // half-precision types); A double-precision floating-point type;
4765 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4766 // with a Base Type of a single- or double-precision floating-point type,
4767 // 64-bit containerized vectors or 128-bit containerized vectors with one
4768 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004769 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004770
Reid Klecknerb1be6832014-11-15 01:41:41 +00004771 Ty = useFirstFieldIfTransparentUnion(Ty);
4772
Manman Renfef9e312012-10-16 19:18:39 +00004773 // Handle illegal vector types here.
4774 if (isIllegalVectorType(Ty)) {
4775 uint64_t Size = getContext().getTypeSize(Ty);
4776 if (Size <= 32) {
4777 llvm::Type *ResType =
4778 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004779 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004780 }
4781 if (Size == 64) {
4782 llvm::Type *ResType = llvm::VectorType::get(
4783 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004784 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004785 }
4786 if (Size == 128) {
4787 llvm::Type *ResType = llvm::VectorType::get(
4788 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004789 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004790 }
4791 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4792 }
4793
Oliver Stannarddc2854c2015-09-03 12:40:58 +00004794 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
4795 // unspecified. This is not done for OpenCL as it handles the half type
4796 // natively, and does not need to interwork with AAPCS code.
4797 if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
4798 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
4799 llvm::Type::getFloatTy(getVMContext()) :
4800 llvm::Type::getInt32Ty(getVMContext());
4801 return ABIArgInfo::getDirect(ResType);
4802 }
4803
John McCalla1dee5302010-08-22 10:59:02 +00004804 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004805 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004806 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004807 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004808 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004809
Tim Northover5a1558e2014-11-07 22:30:50 +00004810 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4811 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004812 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004813
Oliver Stannard405bded2014-02-11 09:25:50 +00004814 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northover1060eae2013-06-21 22:49:34 +00004815 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004816 }
Tim Northover1060eae2013-06-21 22:49:34 +00004817
Daniel Dunbar09d33622009-09-14 21:54:03 +00004818 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004819 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004820 return ABIArgInfo::getIgnore();
4821
Tim Northover5a1558e2014-11-07 22:30:50 +00004822 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004823 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4824 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004825 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004826 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004827 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004828 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004829 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004830 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004831 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004832 }
4833
Manman Ren6c30e132012-08-13 21:23:55 +00004834 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004835 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4836 // most 8-byte. We realign the indirect argument if type alignment is bigger
4837 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004838 uint64_t ABIAlign = 4;
4839 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4840 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004841 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004842 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004843
Manman Ren8cd99812012-11-06 04:58:01 +00004844 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northoverd157e192015-03-09 21:40:42 +00004845 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004846 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004847 }
4848
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004849 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004850 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004851 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004852 // FIXME: Try to match the types of the arguments more accurately where
4853 // we can.
4854 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004855 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4856 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004857 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004858 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4859 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004860 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004861
Tim Northover5a1558e2014-11-07 22:30:50 +00004862 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004863}
4864
Chris Lattner458b2aa2010-07-29 02:16:43 +00004865static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004866 llvm::LLVMContext &VMContext) {
4867 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4868 // is called integer-like if its size is less than or equal to one word, and
4869 // the offset of each of its addressable sub-fields is zero.
4870
4871 uint64_t Size = Context.getTypeSize(Ty);
4872
4873 // Check that the type fits in a word.
4874 if (Size > 32)
4875 return false;
4876
4877 // FIXME: Handle vector types!
4878 if (Ty->isVectorType())
4879 return false;
4880
Daniel Dunbard53bac72009-09-14 02:20:34 +00004881 // Float types are never treated as "integer like".
4882 if (Ty->isRealFloatingType())
4883 return false;
4884
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004885 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004886 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004887 return true;
4888
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004889 // Small complex integer types are "integer like".
4890 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4891 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004892
4893 // Single element and zero sized arrays should be allowed, by the definition
4894 // above, but they are not.
4895
4896 // Otherwise, it must be a record type.
4897 const RecordType *RT = Ty->getAs<RecordType>();
4898 if (!RT) return false;
4899
4900 // Ignore records with flexible arrays.
4901 const RecordDecl *RD = RT->getDecl();
4902 if (RD->hasFlexibleArrayMember())
4903 return false;
4904
4905 // Check that all sub-fields are at offset 0, and are themselves "integer
4906 // like".
4907 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4908
4909 bool HadField = false;
4910 unsigned idx = 0;
4911 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4912 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004913 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004914
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004915 // Bit-fields are not addressable, we only need to verify they are "integer
4916 // like". We still have to disallow a subsequent non-bitfield, for example:
4917 // struct { int : 0; int x }
4918 // is non-integer like according to gcc.
4919 if (FD->isBitField()) {
4920 if (!RD->isUnion())
4921 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004922
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004923 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4924 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004925
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004926 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004927 }
4928
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004929 // Check if this field is at offset 0.
4930 if (Layout.getFieldOffset(idx) != 0)
4931 return false;
4932
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004933 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4934 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004935
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004936 // Only allow at most one field in a structure. This doesn't match the
4937 // wording above, but follows gcc in situations with a field following an
4938 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004939 if (!RD->isUnion()) {
4940 if (HadField)
4941 return false;
4942
4943 HadField = true;
4944 }
4945 }
4946
4947 return true;
4948}
4949
Oliver Stannard405bded2014-02-11 09:25:50 +00004950ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4951 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004952 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004953
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004954 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004955 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004956
Daniel Dunbar19964db2010-09-23 01:54:32 +00004957 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004958 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbar19964db2010-09-23 01:54:32 +00004959 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004960 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004961
Oliver Stannarddc2854c2015-09-03 12:40:58 +00004962 // __fp16 gets returned as if it were an int or float, but with the top 16
4963 // bits unspecified. This is not done for OpenCL as it handles the half type
4964 // natively, and does not need to interwork with AAPCS code.
4965 if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
4966 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
4967 llvm::Type::getFloatTy(getVMContext()) :
4968 llvm::Type::getInt32Ty(getVMContext());
4969 return ABIArgInfo::getDirect(ResType);
4970 }
4971
John McCalla1dee5302010-08-22 10:59:02 +00004972 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004973 // Treat an enum type as its underlying type.
4974 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4975 RetTy = EnumTy->getDecl()->getIntegerType();
4976
Tim Northover5a1558e2014-11-07 22:30:50 +00004977 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4978 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004979 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004980
4981 // Are we following APCS?
4982 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004983 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004984 return ABIArgInfo::getIgnore();
4985
Daniel Dunbareedf1512010-02-01 23:31:19 +00004986 // Complex types are all returned as packed integers.
4987 //
4988 // FIXME: Consider using 2 x vector types if the back end handles them
4989 // correctly.
4990 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004991 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4992 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004993
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004994 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004995 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004996 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004997 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004998 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004999 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005000 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005001 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5002 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005003 }
5004
5005 // Otherwise return in memory.
5006 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005007 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005008
5009 // Otherwise this is an AAPCS variant.
5010
Chris Lattner458b2aa2010-07-29 02:16:43 +00005011 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005012 return ABIArgInfo::getIgnore();
5013
Bob Wilson1d9269a2011-11-02 04:51:36 +00005014 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005015 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005016 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005017 uint64_t Members;
5018 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005019 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005020 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005021 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005022 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005023 }
5024
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005025 // Aggregates <= 4 bytes are returned in r0; other aggregates
5026 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005027 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005028 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005029 if (getDataLayout().isBigEndian())
5030 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005031 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005032
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005033 // Return in the smallest viable integer type.
5034 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005035 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005036 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005037 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5038 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005039 }
5040
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005041 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005042}
5043
Manman Renfef9e312012-10-16 19:18:39 +00005044/// isIllegalVector - check whether Ty is an illegal vector type.
5045bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5046 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5047 // Check whether VT is legal.
5048 unsigned NumElements = VT->getNumElements();
5049 uint64_t Size = getContext().getTypeSize(VT);
5050 // NumElements should be power of 2.
5051 if ((NumElements & (NumElements - 1)) != 0)
5052 return true;
5053 // Size should be greater than 32 bits.
5054 return Size <= 32;
5055 }
5056 return false;
5057}
5058
Reid Klecknere9f6a712014-10-31 17:10:41 +00005059bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5060 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5061 // double, or 64-bit or 128-bit vectors.
5062 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5063 if (BT->getKind() == BuiltinType::Float ||
5064 BT->getKind() == BuiltinType::Double ||
5065 BT->getKind() == BuiltinType::LongDouble)
5066 return true;
5067 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5068 unsigned VecSize = getContext().getTypeSize(VT);
5069 if (VecSize == 64 || VecSize == 128)
5070 return true;
5071 }
5072 return false;
5073}
5074
5075bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5076 uint64_t Members) const {
5077 return Members <= 4;
5078}
5079
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005080llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00005081 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00005082 llvm::Type *BP = CGF.Int8PtrTy;
5083 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005084
5085 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00005086 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005087 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00005088
Tim Northover1711cc92013-06-21 23:05:33 +00005089 if (isEmptyRecord(getContext(), Ty, true)) {
5090 // These are ignored for parameter passing purposes.
5091 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5092 return Builder.CreateBitCast(Addr, PTy);
5093 }
5094
Manman Rencca54d02012-10-16 19:01:37 +00005095 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00005096 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00005097 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00005098
5099 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5100 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00005101 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5102 getABIKind() == ARMABIInfo::AAPCS)
5103 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5104 else
5105 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00005106 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5107 if (isIllegalVectorType(Ty) && Size > 16) {
5108 IsIndirect = true;
5109 Size = 4;
5110 TyAlign = 4;
5111 }
Manman Rencca54d02012-10-16 19:01:37 +00005112
5113 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00005114 if (TyAlign > 4) {
5115 assert((TyAlign & (TyAlign - 1)) == 0 &&
5116 "Alignment is not power of 2!");
5117 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
5118 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
5119 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00005120 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00005121 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005122
5123 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00005124 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005125 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00005126 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005127 "ap.next");
5128 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5129
Manman Renfef9e312012-10-16 19:18:39 +00005130 if (IsIndirect)
5131 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00005132 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00005133 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5134 // may not be correctly aligned for the vector type. We create an aligned
5135 // temporary space and copy the content over from ap.cur to the temporary
5136 // space. This is necessary if the natural alignment of the type is greater
5137 // than the ABI alignment.
5138 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5139 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5140 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5141 "var.align");
5142 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5143 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5144 Builder.CreateMemCpy(Dst, Src,
5145 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5146 TyAlign, false);
5147 Addr = AlignedTemp; //The content is in aligned location.
5148 }
5149 llvm::Type *PTy =
5150 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5151 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5152
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005153 return AddrTyped;
5154}
5155
Chris Lattner0cf24192010-06-28 20:05:43 +00005156//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005157// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005158//===----------------------------------------------------------------------===//
5159
5160namespace {
5161
Justin Holewinski83e96682012-05-24 17:43:12 +00005162class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005163public:
Justin Holewinski36837432013-03-30 14:38:24 +00005164 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005165
5166 ABIArgInfo classifyReturnType(QualType RetTy) const;
5167 ABIArgInfo classifyArgumentType(QualType Ty) const;
5168
Craig Topper4f12f102014-03-12 06:41:41 +00005169 void computeInfo(CGFunctionInfo &FI) const override;
5170 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5171 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005172};
5173
Justin Holewinski83e96682012-05-24 17:43:12 +00005174class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005175public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005176 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5177 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005178
Eric Christopher162c91c2015-06-05 22:03:00 +00005179 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005180 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005181private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005182 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5183 // resulting MDNode to the nvvm.annotations MDNode.
5184 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005185};
5186
Justin Holewinski83e96682012-05-24 17:43:12 +00005187ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005188 if (RetTy->isVoidType())
5189 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005190
5191 // note: this is different from default ABI
5192 if (!RetTy->isScalarType())
5193 return ABIArgInfo::getDirect();
5194
5195 // Treat an enum type as its underlying type.
5196 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5197 RetTy = EnumTy->getDecl()->getIntegerType();
5198
5199 return (RetTy->isPromotableIntegerType() ?
5200 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005201}
5202
Justin Holewinski83e96682012-05-24 17:43:12 +00005203ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005204 // Treat an enum type as its underlying type.
5205 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5206 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005207
Eli Bendersky95338a02014-10-29 13:43:21 +00005208 // Return aggregates type as indirect by value
5209 if (isAggregateTypeForABI(Ty))
5210 return ABIArgInfo::getIndirect(0, /* byval */ true);
5211
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005212 return (Ty->isPromotableIntegerType() ?
5213 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005214}
5215
Justin Holewinski83e96682012-05-24 17:43:12 +00005216void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005217 if (!getCXXABI().classifyReturnType(FI))
5218 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005219 for (auto &I : FI.arguments())
5220 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005221
5222 // Always honor user-specified calling convention.
5223 if (FI.getCallingConvention() != llvm::CallingConv::C)
5224 return;
5225
John McCall882987f2013-02-28 19:01:20 +00005226 FI.setEffectiveCallingConvention(getRuntimeCC());
5227}
5228
Justin Holewinski83e96682012-05-24 17:43:12 +00005229llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5230 CodeGenFunction &CFG) const {
5231 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005232}
5233
Justin Holewinski83e96682012-05-24 17:43:12 +00005234void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005235setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005236 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005237 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5238 if (!FD) return;
5239
5240 llvm::Function *F = cast<llvm::Function>(GV);
5241
5242 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005243 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005244 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005245 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005246 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005247 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005248 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5249 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005250 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005251 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005252 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005253 }
Justin Holewinski38031972011-10-05 17:58:44 +00005254
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005255 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005256 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005257 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005258 // __global__ functions cannot be called from the device, we do not
5259 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005260 if (FD->hasAttr<CUDAGlobalAttr>()) {
5261 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5262 addNVVMMetadata(F, "kernel", 1);
5263 }
Artem Belevich7093e402015-04-21 22:55:54 +00005264 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005265 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005266 llvm::APSInt MaxThreads(32);
5267 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5268 if (MaxThreads > 0)
5269 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5270
5271 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5272 // not specified in __launch_bounds__ or if the user specified a 0 value,
5273 // we don't have to add a PTX directive.
5274 if (Attr->getMinBlocks()) {
5275 llvm::APSInt MinBlocks(32);
5276 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5277 if (MinBlocks > 0)
5278 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5279 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005280 }
5281 }
Justin Holewinski38031972011-10-05 17:58:44 +00005282 }
5283}
5284
Eli Benderskye06a2c42014-04-15 16:57:05 +00005285void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5286 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005287 llvm::Module *M = F->getParent();
5288 llvm::LLVMContext &Ctx = M->getContext();
5289
5290 // Get "nvvm.annotations" metadata node
5291 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5292
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005293 llvm::Metadata *MDVals[] = {
5294 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5295 llvm::ConstantAsMetadata::get(
5296 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005297 // Append metadata to nvvm.annotations
5298 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5299}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005300}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005301
5302//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005303// SystemZ ABI Implementation
5304//===----------------------------------------------------------------------===//
5305
5306namespace {
5307
5308class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005309 bool HasVector;
5310
Ulrich Weigand47445072013-05-06 16:26:41 +00005311public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005312 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5313 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005314
5315 bool isPromotableIntegerType(QualType Ty) const;
5316 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005317 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005318 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005319 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005320
5321 ABIArgInfo classifyReturnType(QualType RetTy) const;
5322 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5323
Craig Topper4f12f102014-03-12 06:41:41 +00005324 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005325 if (!getCXXABI().classifyReturnType(FI))
5326 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005327 for (auto &I : FI.arguments())
5328 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005329 }
5330
Craig Topper4f12f102014-03-12 06:41:41 +00005331 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5332 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005333};
5334
5335class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5336public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005337 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5338 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005339};
5340
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005341}
Ulrich Weigand47445072013-05-06 16:26:41 +00005342
5343bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5344 // Treat an enum type as its underlying type.
5345 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5346 Ty = EnumTy->getDecl()->getIntegerType();
5347
5348 // Promotable integer types are required to be promoted by the ABI.
5349 if (Ty->isPromotableIntegerType())
5350 return true;
5351
5352 // 32-bit values must also be promoted.
5353 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5354 switch (BT->getKind()) {
5355 case BuiltinType::Int:
5356 case BuiltinType::UInt:
5357 return true;
5358 default:
5359 return false;
5360 }
5361 return false;
5362}
5363
5364bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005365 return (Ty->isAnyComplexType() ||
5366 Ty->isVectorType() ||
5367 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005368}
5369
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005370bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5371 return (HasVector &&
5372 Ty->isVectorType() &&
5373 getContext().getTypeSize(Ty) <= 128);
5374}
5375
Ulrich Weigand47445072013-05-06 16:26:41 +00005376bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5377 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5378 switch (BT->getKind()) {
5379 case BuiltinType::Float:
5380 case BuiltinType::Double:
5381 return true;
5382 default:
5383 return false;
5384 }
5385
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005386 return false;
5387}
5388
5389QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005390 if (const RecordType *RT = Ty->getAsStructureType()) {
5391 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005392 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005393
5394 // If this is a C++ record, check the bases first.
5395 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005396 for (const auto &I : CXXRD->bases()) {
5397 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005398
5399 // Empty bases don't affect things either way.
5400 if (isEmptyRecord(getContext(), Base, true))
5401 continue;
5402
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005403 if (!Found.isNull())
5404 return Ty;
5405 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005406 }
5407
5408 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005409 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005410 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005411 // Unlike isSingleElementStruct(), empty structure and array fields
5412 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005413 if (getContext().getLangOpts().CPlusPlus &&
5414 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5415 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005416
5417 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005418 // Nested structures still do though.
5419 if (!Found.isNull())
5420 return Ty;
5421 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005422 }
5423
5424 // Unlike isSingleElementStruct(), trailing padding is allowed.
5425 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005426 if (!Found.isNull())
5427 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005428 }
5429
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005430 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005431}
5432
5433llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5434 CodeGenFunction &CGF) const {
5435 // Assume that va_list type is correct; should be pointer to LLVM type:
5436 // struct {
5437 // i64 __gpr;
5438 // i64 __fpr;
5439 // i8 *__overflow_arg_area;
5440 // i8 *__reg_save_area;
5441 // };
5442
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005443 // Every non-vector argument occupies 8 bytes and is passed by preference
5444 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5445 // always passed on the stack.
Ulrich Weigand47445072013-05-06 16:26:41 +00005446 Ty = CGF.getContext().getCanonicalType(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005447 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
5448 llvm::Type *APTy = llvm::PointerType::getUnqual(ArgTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005449 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005450 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005451 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005452 bool IsVector = false;
Ulrich Weigand47445072013-05-06 16:26:41 +00005453 unsigned UnpaddedBitSize;
5454 if (IsIndirect) {
5455 APTy = llvm::PointerType::getUnqual(APTy);
5456 UnpaddedBitSize = 64;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005457 } else {
5458 if (AI.getCoerceToType())
5459 ArgTy = AI.getCoerceToType();
5460 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005461 IsVector = ArgTy->isVectorTy();
Ulrich Weigand47445072013-05-06 16:26:41 +00005462 UnpaddedBitSize = getContext().getTypeSize(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005463 }
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005464 unsigned PaddedBitSize = (IsVector && UnpaddedBitSize > 64) ? 128 : 64;
Ulrich Weigand47445072013-05-06 16:26:41 +00005465 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5466
5467 unsigned PaddedSize = PaddedBitSize / 8;
5468 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5469
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005470 llvm::Type *IndexTy = CGF.Int64Ty;
5471 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5472
5473 if (IsVector) {
5474 // Work out the address of a vector argument on the stack.
5475 // Vector arguments are always passed in the high bits of a
5476 // single (8 byte) or double (16 byte) stack slot.
5477 llvm::Value *OverflowArgAreaPtr =
5478 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 2,
5479 "overflow_arg_area_ptr");
5480 llvm::Value *OverflowArgArea =
5481 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5482 llvm::Value *MemAddr =
5483 CGF.Builder.CreateBitCast(OverflowArgArea, APTy, "mem_addr");
5484
5485 // Update overflow_arg_area_ptr pointer
5486 llvm::Value *NewOverflowArgArea =
5487 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5488 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5489
5490 return MemAddr;
5491 }
5492
Ulrich Weigand47445072013-05-06 16:26:41 +00005493 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5494 if (InFPRs) {
5495 MaxRegs = 4; // Maximum of 4 FPR arguments
5496 RegCountField = 1; // __fpr
5497 RegSaveIndex = 16; // save offset for f0
5498 RegPadding = 0; // floats are passed in the high bits of an FPR
5499 } else {
5500 MaxRegs = 5; // Maximum of 5 GPR arguments
5501 RegCountField = 0; // __gpr
5502 RegSaveIndex = 2; // save offset for r2
5503 RegPadding = Padding; // values are passed in the low bits of a GPR
5504 }
5505
David Blaikie2e804282015-04-05 22:47:07 +00005506 llvm::Value *RegCountPtr = CGF.Builder.CreateStructGEP(
5507 nullptr, VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005508 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005509 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5510 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005511 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005512
5513 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5514 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5515 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5516 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5517
5518 // Emit code to load the value if it was passed in registers.
5519 CGF.EmitBlock(InRegBlock);
5520
5521 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005522 llvm::Value *ScaledRegCount =
5523 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5524 llvm::Value *RegBase =
5525 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5526 llvm::Value *RegOffset =
5527 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5528 llvm::Value *RegSaveAreaPtr =
David Blaikie2e804282015-04-05 22:47:07 +00005529 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005530 llvm::Value *RegSaveArea =
5531 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5532 llvm::Value *RawRegAddr =
5533 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5534 llvm::Value *RegAddr =
5535 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5536
5537 // Update the register count
5538 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5539 llvm::Value *NewRegCount =
5540 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5541 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5542 CGF.EmitBranch(ContBlock);
5543
5544 // Emit code to load the value if it was passed in memory.
5545 CGF.EmitBlock(InMemBlock);
5546
5547 // Work out the address of a stack argument.
David Blaikie2e804282015-04-05 22:47:07 +00005548 llvm::Value *OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5549 nullptr, VAListAddr, 2, "overflow_arg_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005550 llvm::Value *OverflowArgArea =
5551 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5552 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5553 llvm::Value *RawMemAddr =
5554 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5555 llvm::Value *MemAddr =
5556 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5557
5558 // Update overflow_arg_area_ptr pointer
5559 llvm::Value *NewOverflowArgArea =
5560 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5561 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5562 CGF.EmitBranch(ContBlock);
5563
5564 // Return the appropriate result.
5565 CGF.EmitBlock(ContBlock);
5566 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5567 ResAddr->addIncoming(RegAddr, InRegBlock);
5568 ResAddr->addIncoming(MemAddr, InMemBlock);
5569
5570 if (IsIndirect)
5571 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5572
5573 return ResAddr;
5574}
5575
Ulrich Weigand47445072013-05-06 16:26:41 +00005576ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5577 if (RetTy->isVoidType())
5578 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005579 if (isVectorArgumentType(RetTy))
5580 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005581 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5582 return ABIArgInfo::getIndirect(0);
5583 return (isPromotableIntegerType(RetTy) ?
5584 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5585}
5586
5587ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5588 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005589 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005590 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5591
5592 // Integers and enums are extended to full register width.
5593 if (isPromotableIntegerType(Ty))
5594 return ABIArgInfo::getExtend();
5595
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005596 // Handle vector types and vector-like structure types. Note that
5597 // as opposed to float-like structure types, we do not allow any
5598 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005599 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005600 QualType SingleElementTy = GetSingleElementType(Ty);
5601 if (isVectorArgumentType(SingleElementTy) &&
5602 getContext().getTypeSize(SingleElementTy) == Size)
5603 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5604
5605 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005606 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005607 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005608
5609 // Handle small structures.
5610 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5611 // Structures with flexible arrays have variable length, so really
5612 // fail the size test above.
5613 const RecordDecl *RD = RT->getDecl();
5614 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005615 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005616
5617 // The structure is passed as an unextended integer, a float, or a double.
5618 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005619 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005620 assert(Size == 32 || Size == 64);
5621 if (Size == 32)
5622 PassTy = llvm::Type::getFloatTy(getVMContext());
5623 else
5624 PassTy = llvm::Type::getDoubleTy(getVMContext());
5625 } else
5626 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5627 return ABIArgInfo::getDirect(PassTy);
5628 }
5629
5630 // Non-structure compounds are passed indirectly.
5631 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005632 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005633
Craig Topper8a13c412014-05-21 05:09:00 +00005634 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005635}
5636
5637//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005638// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005639//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005640
5641namespace {
5642
5643class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5644public:
Chris Lattner2b037972010-07-29 02:01:43 +00005645 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5646 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005647 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005648 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005649};
5650
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005651}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005652
Eric Christopher162c91c2015-06-05 22:03:00 +00005653void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005654 llvm::GlobalValue *GV,
5655 CodeGen::CodeGenModule &M) const {
5656 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5657 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5658 // Handle 'interrupt' attribute:
5659 llvm::Function *F = cast<llvm::Function>(GV);
5660
5661 // Step 1: Set ISR calling convention.
5662 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5663
5664 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005665 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005666
5667 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005668 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005669 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5670 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005671 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005672 }
5673}
5674
Chris Lattner0cf24192010-06-28 20:05:43 +00005675//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005676// MIPS ABI Implementation. This works for both little-endian and
5677// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005678//===----------------------------------------------------------------------===//
5679
John McCall943fae92010-05-27 06:19:26 +00005680namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005681class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005682 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005683 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5684 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005685 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005686 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005687 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005688 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005689public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005690 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005691 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005692 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005693
5694 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005695 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005696 void computeInfo(CGFunctionInfo &FI) const override;
5697 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5698 CodeGenFunction &CGF) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005699 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005700};
5701
John McCall943fae92010-05-27 06:19:26 +00005702class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005703 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005704public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005705 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5706 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005707 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005708
Craig Topper4f12f102014-03-12 06:41:41 +00005709 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005710 return 29;
5711 }
5712
Eric Christopher162c91c2015-06-05 22:03:00 +00005713 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005714 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005715 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5716 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005717 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005718 if (FD->hasAttr<Mips16Attr>()) {
5719 Fn->addFnAttr("mips16");
5720 }
5721 else if (FD->hasAttr<NoMips16Attr>()) {
5722 Fn->addFnAttr("nomips16");
5723 }
Reed Kotler373feca2013-01-16 17:10:28 +00005724 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005725
John McCall943fae92010-05-27 06:19:26 +00005726 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005727 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005728
Craig Topper4f12f102014-03-12 06:41:41 +00005729 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005730 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005731 }
John McCall943fae92010-05-27 06:19:26 +00005732};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005733}
John McCall943fae92010-05-27 06:19:26 +00005734
Eric Christopher7565e0d2015-05-29 23:09:49 +00005735void MipsABIInfo::CoerceToIntArgs(
5736 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005737 llvm::IntegerType *IntTy =
5738 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005739
5740 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5741 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5742 ArgList.push_back(IntTy);
5743
5744 // If necessary, add one more integer type to ArgList.
5745 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5746
5747 if (R)
5748 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005749}
5750
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005751// In N32/64, an aligned double precision floating point field is passed in
5752// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005753llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005754 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5755
5756 if (IsO32) {
5757 CoerceToIntArgs(TySize, ArgList);
5758 return llvm::StructType::get(getVMContext(), ArgList);
5759 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005760
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005761 if (Ty->isComplexType())
5762 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005763
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005764 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005765
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005766 // Unions/vectors are passed in integer registers.
5767 if (!RT || !RT->isStructureOrClassType()) {
5768 CoerceToIntArgs(TySize, ArgList);
5769 return llvm::StructType::get(getVMContext(), ArgList);
5770 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005771
5772 const RecordDecl *RD = RT->getDecl();
5773 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005774 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00005775
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005776 uint64_t LastOffset = 0;
5777 unsigned idx = 0;
5778 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5779
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005780 // Iterate over fields in the struct/class and check if there are any aligned
5781 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005782 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5783 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005784 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005785 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5786
5787 if (!BT || BT->getKind() != BuiltinType::Double)
5788 continue;
5789
5790 uint64_t Offset = Layout.getFieldOffset(idx);
5791 if (Offset % 64) // Ignore doubles that are not aligned.
5792 continue;
5793
5794 // Add ((Offset - LastOffset) / 64) args of type i64.
5795 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5796 ArgList.push_back(I64);
5797
5798 // Add double type.
5799 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5800 LastOffset = Offset + 64;
5801 }
5802
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005803 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5804 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005805
5806 return llvm::StructType::get(getVMContext(), ArgList);
5807}
5808
Akira Hatanakaddd66342013-10-29 18:41:15 +00005809llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5810 uint64_t Offset) const {
5811 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005812 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005813
Akira Hatanakaddd66342013-10-29 18:41:15 +00005814 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005815}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005816
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005817ABIArgInfo
5818MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005819 Ty = useFirstFieldIfTransparentUnion(Ty);
5820
Akira Hatanaka1632af62012-01-09 19:31:25 +00005821 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005822 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005823 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005824
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005825 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5826 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005827 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5828 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005829
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005830 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005831 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005832 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005833 return ABIArgInfo::getIgnore();
5834
Mark Lacey3825e832013-10-06 01:33:34 +00005835 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005836 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005837 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005838 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005839
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005840 // If we have reached here, aggregates are passed directly by coercing to
5841 // another structure type. Padding is inserted if the offset of the
5842 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005843 ABIArgInfo ArgInfo =
5844 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5845 getPaddingType(OrigOffset, CurrOffset));
5846 ArgInfo.setInReg(true);
5847 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005848 }
5849
5850 // Treat an enum type as its underlying type.
5851 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5852 Ty = EnumTy->getDecl()->getIntegerType();
5853
Daniel Sanders5b445b32014-10-24 14:42:42 +00005854 // All integral types are promoted to the GPR width.
5855 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005856 return ABIArgInfo::getExtend();
5857
Akira Hatanakaddd66342013-10-29 18:41:15 +00005858 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005859 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005860}
5861
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005862llvm::Type*
5863MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005864 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005865 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005866
Akira Hatanakab6f74432012-02-09 18:49:26 +00005867 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005868 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005869 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5870 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005871
Akira Hatanakab6f74432012-02-09 18:49:26 +00005872 // N32/64 returns struct/classes in floating point registers if the
5873 // following conditions are met:
5874 // 1. The size of the struct/class is no larger than 128-bit.
5875 // 2. The struct/class has one or two fields all of which are floating
5876 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005877 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00005878 //
5879 // Any other composite results are returned in integer registers.
5880 //
5881 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5882 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5883 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005884 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005885
Akira Hatanakab6f74432012-02-09 18:49:26 +00005886 if (!BT || !BT->isFloatingPoint())
5887 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005888
David Blaikie2d7c57e2012-04-30 02:36:29 +00005889 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005890 }
5891
5892 if (b == e)
5893 return llvm::StructType::get(getVMContext(), RTList,
5894 RD->hasAttr<PackedAttr>());
5895
5896 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005897 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005898 }
5899
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005900 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005901 return llvm::StructType::get(getVMContext(), RTList);
5902}
5903
Akira Hatanakab579fe52011-06-02 00:09:17 +00005904ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005905 uint64_t Size = getContext().getTypeSize(RetTy);
5906
Daniel Sandersed39f582014-09-04 13:28:14 +00005907 if (RetTy->isVoidType())
5908 return ABIArgInfo::getIgnore();
5909
5910 // O32 doesn't treat zero-sized structs differently from other structs.
5911 // However, N32/N64 ignores zero sized return values.
5912 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005913 return ABIArgInfo::getIgnore();
5914
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005915 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005916 if (Size <= 128) {
5917 if (RetTy->isAnyComplexType())
5918 return ABIArgInfo::getDirect();
5919
Daniel Sanderse5018b62014-09-04 15:05:39 +00005920 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005921 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005922 if (!IsO32 ||
5923 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5924 ABIArgInfo ArgInfo =
5925 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5926 ArgInfo.setInReg(true);
5927 return ArgInfo;
5928 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005929 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005930
5931 return ABIArgInfo::getIndirect(0);
5932 }
5933
5934 // Treat an enum type as its underlying type.
5935 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5936 RetTy = EnumTy->getDecl()->getIntegerType();
5937
5938 return (RetTy->isPromotableIntegerType() ?
5939 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5940}
5941
5942void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005943 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005944 if (!getCXXABI().classifyReturnType(FI))
5945 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005946
Eric Christopher7565e0d2015-05-29 23:09:49 +00005947 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005948 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005949
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005950 for (auto &I : FI.arguments())
5951 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005952}
5953
5954llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5955 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005956 llvm::Type *BP = CGF.Int8PtrTy;
5957 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005958
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005959 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5960 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005961 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005962 unsigned PtrWidth = getTarget().getPointerWidth(0);
5963 if ((Ty->isIntegerType() &&
5964 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5965 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005966 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5967 Ty->isSignedIntegerType());
5968 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00005969
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005970 CGBuilderTy &Builder = CGF.Builder;
5971 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5972 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005973 int64_t TypeAlign =
5974 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005975 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5976 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005977 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5978
5979 if (TypeAlign > MinABIStackAlignInBytes) {
5980 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5981 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5982 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5983 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5984 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5985 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5986 }
5987 else
Eric Christopher7565e0d2015-05-29 23:09:49 +00005988 AddrTyped = Builder.CreateBitCast(Addr, PTy);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005989
5990 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5991 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005992 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5993 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005994 llvm::Value *NextAddr =
5995 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5996 "ap.next");
5997 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005998
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005999 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006000}
6001
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006002bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6003 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006004
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006005 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6006 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6007 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006008
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006009 return false;
6010}
6011
John McCall943fae92010-05-27 06:19:26 +00006012bool
6013MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6014 llvm::Value *Address) const {
6015 // This information comes from gcc's implementation, which seems to
6016 // as canonical as it gets.
6017
John McCall943fae92010-05-27 06:19:26 +00006018 // Everything on MIPS is 4 bytes. Double-precision FP registers
6019 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006020 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006021
6022 // 0-31 are the general purpose registers, $0 - $31.
6023 // 32-63 are the floating-point registers, $f0 - $f31.
6024 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6025 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006026 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006027
6028 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6029 // They are one bit wide and ignored here.
6030
6031 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6032 // (coprocessor 1 is the FP unit)
6033 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6034 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6035 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006036 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006037 return false;
6038}
6039
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006040//===----------------------------------------------------------------------===//
6041// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006042// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006043// handling.
6044//===----------------------------------------------------------------------===//
6045
6046namespace {
6047
6048class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6049public:
6050 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6051 : DefaultTargetCodeGenInfo(CGT) {}
6052
Eric Christopher162c91c2015-06-05 22:03:00 +00006053 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006054 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006055};
6056
Eric Christopher162c91c2015-06-05 22:03:00 +00006057void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006058 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006059 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6060 if (!FD) return;
6061
6062 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006063
David Blaikiebbafb8a2012-03-11 07:00:24 +00006064 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006065 if (FD->hasAttr<OpenCLKernelAttr>()) {
6066 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006067 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006068 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6069 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006070 // Convert the reqd_work_group_size() attributes to metadata.
6071 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006072 llvm::NamedMDNode *OpenCLMetadata =
6073 M.getModule().getOrInsertNamedMetadata(
6074 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006075
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006076 SmallVector<llvm::Metadata *, 5> Operands;
6077 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006078
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006079 Operands.push_back(
6080 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6081 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6082 Operands.push_back(
6083 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6084 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6085 Operands.push_back(
6086 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6087 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006088
Eric Christopher7565e0d2015-05-29 23:09:49 +00006089 // Add a boolean constant operand for "required" (true) or "hint"
6090 // (false) for implementing the work_group_size_hint attr later.
6091 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006092 Operands.push_back(
6093 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006094 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6095 }
6096 }
6097 }
6098}
6099
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006100}
John McCall943fae92010-05-27 06:19:26 +00006101
Tony Linthicum76329bf2011-12-12 21:14:55 +00006102//===----------------------------------------------------------------------===//
6103// Hexagon ABI Implementation
6104//===----------------------------------------------------------------------===//
6105
6106namespace {
6107
6108class HexagonABIInfo : public ABIInfo {
6109
6110
6111public:
6112 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6113
6114private:
6115
6116 ABIArgInfo classifyReturnType(QualType RetTy) const;
6117 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6118
Craig Topper4f12f102014-03-12 06:41:41 +00006119 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006120
Craig Topper4f12f102014-03-12 06:41:41 +00006121 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6122 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006123};
6124
6125class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6126public:
6127 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6128 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6129
Craig Topper4f12f102014-03-12 06:41:41 +00006130 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006131 return 29;
6132 }
6133};
6134
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006135}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006136
6137void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006138 if (!getCXXABI().classifyReturnType(FI))
6139 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006140 for (auto &I : FI.arguments())
6141 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006142}
6143
6144ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6145 if (!isAggregateTypeForABI(Ty)) {
6146 // Treat an enum type as its underlying type.
6147 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6148 Ty = EnumTy->getDecl()->getIntegerType();
6149
6150 return (Ty->isPromotableIntegerType() ?
6151 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6152 }
6153
6154 // Ignore empty records.
6155 if (isEmptyRecord(getContext(), Ty, true))
6156 return ABIArgInfo::getIgnore();
6157
Mark Lacey3825e832013-10-06 01:33:34 +00006158 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00006159 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006160
6161 uint64_t Size = getContext().getTypeSize(Ty);
6162 if (Size > 64)
6163 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6164 // Pass in the smallest viable integer type.
6165 else if (Size > 32)
6166 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6167 else if (Size > 16)
6168 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6169 else if (Size > 8)
6170 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6171 else
6172 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6173}
6174
6175ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6176 if (RetTy->isVoidType())
6177 return ABIArgInfo::getIgnore();
6178
6179 // Large vector types should be returned via memory.
6180 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6181 return ABIArgInfo::getIndirect(0);
6182
6183 if (!isAggregateTypeForABI(RetTy)) {
6184 // Treat an enum type as its underlying type.
6185 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6186 RetTy = EnumTy->getDecl()->getIntegerType();
6187
6188 return (RetTy->isPromotableIntegerType() ?
6189 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6190 }
6191
Tony Linthicum76329bf2011-12-12 21:14:55 +00006192 if (isEmptyRecord(getContext(), RetTy, true))
6193 return ABIArgInfo::getIgnore();
6194
6195 // Aggregates <= 8 bytes are returned in r0; other aggregates
6196 // are returned indirectly.
6197 uint64_t Size = getContext().getTypeSize(RetTy);
6198 if (Size <= 64) {
6199 // Return in the smallest viable integer type.
6200 if (Size <= 8)
6201 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6202 if (Size <= 16)
6203 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6204 if (Size <= 32)
6205 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6206 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6207 }
6208
6209 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6210}
6211
6212llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006213 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006214 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006215 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006216
6217 CGBuilderTy &Builder = CGF.Builder;
6218 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6219 "ap");
6220 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6221 llvm::Type *PTy =
6222 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6223 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6224
6225 uint64_t Offset =
6226 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6227 llvm::Value *NextAddr =
6228 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6229 "ap.next");
6230 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6231
6232 return AddrTyped;
6233}
6234
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006235//===----------------------------------------------------------------------===//
6236// AMDGPU ABI Implementation
6237//===----------------------------------------------------------------------===//
6238
6239namespace {
6240
6241class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6242public:
6243 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6244 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006245 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006246 CodeGen::CodeGenModule &M) const override;
6247};
6248
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006249}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006250
Eric Christopher162c91c2015-06-05 22:03:00 +00006251void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006252 const Decl *D,
6253 llvm::GlobalValue *GV,
6254 CodeGen::CodeGenModule &M) const {
6255 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6256 if (!FD)
6257 return;
6258
6259 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6260 llvm::Function *F = cast<llvm::Function>(GV);
6261 uint32_t NumVGPR = Attr->getNumVGPR();
6262 if (NumVGPR != 0)
6263 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6264 }
6265
6266 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6267 llvm::Function *F = cast<llvm::Function>(GV);
6268 unsigned NumSGPR = Attr->getNumSGPR();
6269 if (NumSGPR != 0)
6270 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6271 }
6272}
6273
Tony Linthicum76329bf2011-12-12 21:14:55 +00006274
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006275//===----------------------------------------------------------------------===//
6276// SPARC v9 ABI Implementation.
6277// Based on the SPARC Compliance Definition version 2.4.1.
6278//
6279// Function arguments a mapped to a nominal "parameter array" and promoted to
6280// registers depending on their type. Each argument occupies 8 or 16 bytes in
6281// the array, structs larger than 16 bytes are passed indirectly.
6282//
6283// One case requires special care:
6284//
6285// struct mixed {
6286// int i;
6287// float f;
6288// };
6289//
6290// When a struct mixed is passed by value, it only occupies 8 bytes in the
6291// parameter array, but the int is passed in an integer register, and the float
6292// is passed in a floating point register. This is represented as two arguments
6293// with the LLVM IR inreg attribute:
6294//
6295// declare void f(i32 inreg %i, float inreg %f)
6296//
6297// The code generator will only allocate 4 bytes from the parameter array for
6298// the inreg arguments. All other arguments are allocated a multiple of 8
6299// bytes.
6300//
6301namespace {
6302class SparcV9ABIInfo : public ABIInfo {
6303public:
6304 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6305
6306private:
6307 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006308 void computeInfo(CGFunctionInfo &FI) const override;
6309 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6310 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006311
6312 // Coercion type builder for structs passed in registers. The coercion type
6313 // serves two purposes:
6314 //
6315 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6316 // in registers.
6317 // 2. Expose aligned floating point elements as first-level elements, so the
6318 // code generator knows to pass them in floating point registers.
6319 //
6320 // We also compute the InReg flag which indicates that the struct contains
6321 // aligned 32-bit floats.
6322 //
6323 struct CoerceBuilder {
6324 llvm::LLVMContext &Context;
6325 const llvm::DataLayout &DL;
6326 SmallVector<llvm::Type*, 8> Elems;
6327 uint64_t Size;
6328 bool InReg;
6329
6330 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6331 : Context(c), DL(dl), Size(0), InReg(false) {}
6332
6333 // Pad Elems with integers until Size is ToSize.
6334 void pad(uint64_t ToSize) {
6335 assert(ToSize >= Size && "Cannot remove elements");
6336 if (ToSize == Size)
6337 return;
6338
6339 // Finish the current 64-bit word.
6340 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6341 if (Aligned > Size && Aligned <= ToSize) {
6342 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6343 Size = Aligned;
6344 }
6345
6346 // Add whole 64-bit words.
6347 while (Size + 64 <= ToSize) {
6348 Elems.push_back(llvm::Type::getInt64Ty(Context));
6349 Size += 64;
6350 }
6351
6352 // Final in-word padding.
6353 if (Size < ToSize) {
6354 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6355 Size = ToSize;
6356 }
6357 }
6358
6359 // Add a floating point element at Offset.
6360 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6361 // Unaligned floats are treated as integers.
6362 if (Offset % Bits)
6363 return;
6364 // The InReg flag is only required if there are any floats < 64 bits.
6365 if (Bits < 64)
6366 InReg = true;
6367 pad(Offset);
6368 Elems.push_back(Ty);
6369 Size = Offset + Bits;
6370 }
6371
6372 // Add a struct type to the coercion type, starting at Offset (in bits).
6373 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6374 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6375 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6376 llvm::Type *ElemTy = StrTy->getElementType(i);
6377 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6378 switch (ElemTy->getTypeID()) {
6379 case llvm::Type::StructTyID:
6380 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6381 break;
6382 case llvm::Type::FloatTyID:
6383 addFloat(ElemOffset, ElemTy, 32);
6384 break;
6385 case llvm::Type::DoubleTyID:
6386 addFloat(ElemOffset, ElemTy, 64);
6387 break;
6388 case llvm::Type::FP128TyID:
6389 addFloat(ElemOffset, ElemTy, 128);
6390 break;
6391 case llvm::Type::PointerTyID:
6392 if (ElemOffset % 64 == 0) {
6393 pad(ElemOffset);
6394 Elems.push_back(ElemTy);
6395 Size += 64;
6396 }
6397 break;
6398 default:
6399 break;
6400 }
6401 }
6402 }
6403
6404 // Check if Ty is a usable substitute for the coercion type.
6405 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006406 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006407 }
6408
6409 // Get the coercion type as a literal struct type.
6410 llvm::Type *getType() const {
6411 if (Elems.size() == 1)
6412 return Elems.front();
6413 else
6414 return llvm::StructType::get(Context, Elems);
6415 }
6416 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006417};
6418} // end anonymous namespace
6419
6420ABIArgInfo
6421SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6422 if (Ty->isVoidType())
6423 return ABIArgInfo::getIgnore();
6424
6425 uint64_t Size = getContext().getTypeSize(Ty);
6426
6427 // Anything too big to fit in registers is passed with an explicit indirect
6428 // pointer / sret pointer.
6429 if (Size > SizeLimit)
6430 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6431
6432 // Treat an enum type as its underlying type.
6433 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6434 Ty = EnumTy->getDecl()->getIntegerType();
6435
6436 // Integer types smaller than a register are extended.
6437 if (Size < 64 && Ty->isIntegerType())
6438 return ABIArgInfo::getExtend();
6439
6440 // Other non-aggregates go in registers.
6441 if (!isAggregateTypeForABI(Ty))
6442 return ABIArgInfo::getDirect();
6443
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006444 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6445 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6446 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6447 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6448
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006449 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006450 // Build a coercion type from the LLVM struct type.
6451 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6452 if (!StrTy)
6453 return ABIArgInfo::getDirect();
6454
6455 CoerceBuilder CB(getVMContext(), getDataLayout());
6456 CB.addStruct(0, StrTy);
6457 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6458
6459 // Try to use the original type for coercion.
6460 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6461
6462 if (CB.InReg)
6463 return ABIArgInfo::getDirectInReg(CoerceTy);
6464 else
6465 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006466}
6467
6468llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6469 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006470 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6471 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6472 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6473 AI.setCoerceToType(ArgTy);
6474
6475 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6476 CGBuilderTy &Builder = CGF.Builder;
6477 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6478 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6479 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6480 llvm::Value *ArgAddr;
6481 unsigned Stride;
6482
6483 switch (AI.getKind()) {
6484 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006485 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006486 llvm_unreachable("Unsupported ABI kind for va_arg");
6487
6488 case ABIArgInfo::Extend:
6489 Stride = 8;
6490 ArgAddr = Builder
6491 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6492 "extend");
6493 break;
6494
6495 case ABIArgInfo::Direct:
6496 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6497 ArgAddr = Addr;
6498 break;
6499
6500 case ABIArgInfo::Indirect:
6501 Stride = 8;
6502 ArgAddr = Builder.CreateBitCast(Addr,
6503 llvm::PointerType::getUnqual(ArgPtrTy),
6504 "indirect");
6505 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6506 break;
6507
6508 case ABIArgInfo::Ignore:
6509 return llvm::UndefValue::get(ArgPtrTy);
6510 }
6511
6512 // Update VAList.
6513 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6514 Builder.CreateStore(Addr, VAListAddrAsBPP);
6515
6516 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006517}
6518
6519void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6520 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006521 for (auto &I : FI.arguments())
6522 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006523}
6524
6525namespace {
6526class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6527public:
6528 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6529 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006530
Craig Topper4f12f102014-03-12 06:41:41 +00006531 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006532 return 14;
6533 }
6534
6535 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006536 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006537};
6538} // end anonymous namespace
6539
Roman Divackyf02c9942014-02-24 18:46:27 +00006540bool
6541SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6542 llvm::Value *Address) const {
6543 // This is calculated from the LLVM and GCC tables and verified
6544 // against gcc output. AFAIK all ABIs use the same encoding.
6545
6546 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6547
6548 llvm::IntegerType *i8 = CGF.Int8Ty;
6549 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6550 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6551
6552 // 0-31: the 8-byte general-purpose registers
6553 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6554
6555 // 32-63: f0-31, the 4-byte floating-point registers
6556 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6557
6558 // Y = 64
6559 // PSR = 65
6560 // WIM = 66
6561 // TBR = 67
6562 // PC = 68
6563 // NPC = 69
6564 // FSR = 70
6565 // CSR = 71
6566 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006567
Roman Divackyf02c9942014-02-24 18:46:27 +00006568 // 72-87: d0-15, the 8-byte floating-point registers
6569 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6570
6571 return false;
6572}
6573
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006574
Robert Lytton0e076492013-08-13 09:43:10 +00006575//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006576// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006577//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006578
Robert Lytton0e076492013-08-13 09:43:10 +00006579namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006580
6581/// A SmallStringEnc instance is used to build up the TypeString by passing
6582/// it by reference between functions that append to it.
6583typedef llvm::SmallString<128> SmallStringEnc;
6584
6585/// TypeStringCache caches the meta encodings of Types.
6586///
6587/// The reason for caching TypeStrings is two fold:
6588/// 1. To cache a type's encoding for later uses;
6589/// 2. As a means to break recursive member type inclusion.
6590///
6591/// A cache Entry can have a Status of:
6592/// NonRecursive: The type encoding is not recursive;
6593/// Recursive: The type encoding is recursive;
6594/// Incomplete: An incomplete TypeString;
6595/// IncompleteUsed: An incomplete TypeString that has been used in a
6596/// Recursive type encoding.
6597///
6598/// A NonRecursive entry will have all of its sub-members expanded as fully
6599/// as possible. Whilst it may contain types which are recursive, the type
6600/// itself is not recursive and thus its encoding may be safely used whenever
6601/// the type is encountered.
6602///
6603/// A Recursive entry will have all of its sub-members expanded as fully as
6604/// possible. The type itself is recursive and it may contain other types which
6605/// are recursive. The Recursive encoding must not be used during the expansion
6606/// of a recursive type's recursive branch. For simplicity the code uses
6607/// IncompleteCount to reject all usage of Recursive encodings for member types.
6608///
6609/// An Incomplete entry is always a RecordType and only encodes its
6610/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6611/// are placed into the cache during type expansion as a means to identify and
6612/// handle recursive inclusion of types as sub-members. If there is recursion
6613/// the entry becomes IncompleteUsed.
6614///
6615/// During the expansion of a RecordType's members:
6616///
6617/// If the cache contains a NonRecursive encoding for the member type, the
6618/// cached encoding is used;
6619///
6620/// If the cache contains a Recursive encoding for the member type, the
6621/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6622///
6623/// If the member is a RecordType, an Incomplete encoding is placed into the
6624/// cache to break potential recursive inclusion of itself as a sub-member;
6625///
6626/// Once a member RecordType has been expanded, its temporary incomplete
6627/// entry is removed from the cache. If a Recursive encoding was swapped out
6628/// it is swapped back in;
6629///
6630/// If an incomplete entry is used to expand a sub-member, the incomplete
6631/// entry is marked as IncompleteUsed. The cache keeps count of how many
6632/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6633///
6634/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6635/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6636/// Else the member is part of a recursive type and thus the recursion has
6637/// been exited too soon for the encoding to be correct for the member.
6638///
6639class TypeStringCache {
6640 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6641 struct Entry {
6642 std::string Str; // The encoded TypeString for the type.
6643 enum Status State; // Information about the encoding in 'Str'.
6644 std::string Swapped; // A temporary place holder for a Recursive encoding
6645 // during the expansion of RecordType's members.
6646 };
6647 std::map<const IdentifierInfo *, struct Entry> Map;
6648 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6649 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6650public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006651 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006652 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6653 bool removeIncomplete(const IdentifierInfo *ID);
6654 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6655 bool IsRecursive);
6656 StringRef lookupStr(const IdentifierInfo *ID);
6657};
6658
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006659/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006660/// FieldEncoding is a helper for this ordering process.
6661class FieldEncoding {
6662 bool HasName;
6663 std::string Enc;
6664public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006665 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6666 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006667 bool operator<(const FieldEncoding &rhs) const {
6668 if (HasName != rhs.HasName) return HasName;
6669 return Enc < rhs.Enc;
6670 }
6671};
6672
Robert Lytton7d1db152013-08-19 09:46:39 +00006673class XCoreABIInfo : public DefaultABIInfo {
6674public:
6675 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006676 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6677 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006678};
6679
Robert Lyttond21e2d72014-03-03 13:45:29 +00006680class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006681 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006682public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006683 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006684 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006685 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6686 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006687};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006688
Robert Lytton2d196952013-10-11 10:29:34 +00006689} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006690
Robert Lytton7d1db152013-08-19 09:46:39 +00006691llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6692 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006693 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006694
Robert Lytton2d196952013-10-11 10:29:34 +00006695 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006696 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6697 CGF.Int8PtrPtrTy);
6698 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006699
Robert Lytton2d196952013-10-11 10:29:34 +00006700 // Handle the argument.
6701 ABIArgInfo AI = classifyArgumentType(Ty);
6702 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6703 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6704 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006705 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006706 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006707 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006708 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006709 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006710 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006711 llvm_unreachable("Unsupported ABI kind for va_arg");
6712 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006713 Val = llvm::UndefValue::get(ArgPtrTy);
6714 ArgSize = 0;
6715 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006716 case ABIArgInfo::Extend:
6717 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006718 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6719 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6720 if (ArgSize < 4)
6721 ArgSize = 4;
6722 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006723 case ABIArgInfo::Indirect:
6724 llvm::Value *ArgAddr;
6725 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6726 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006727 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6728 ArgSize = 4;
6729 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006730 }
Robert Lytton2d196952013-10-11 10:29:34 +00006731
6732 // Increment the VAList.
6733 if (ArgSize) {
6734 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6735 Builder.CreateStore(APN, VAListAddrAsBPP);
6736 }
6737 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006738}
Robert Lytton0e076492013-08-13 09:43:10 +00006739
Robert Lytton844aeeb2014-05-02 09:33:20 +00006740/// During the expansion of a RecordType, an incomplete TypeString is placed
6741/// into the cache as a means to identify and break recursion.
6742/// If there is a Recursive encoding in the cache, it is swapped out and will
6743/// be reinserted by removeIncomplete().
6744/// All other types of encoding should have been used rather than arriving here.
6745void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6746 std::string StubEnc) {
6747 if (!ID)
6748 return;
6749 Entry &E = Map[ID];
6750 assert( (E.Str.empty() || E.State == Recursive) &&
6751 "Incorrectly use of addIncomplete");
6752 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6753 E.Swapped.swap(E.Str); // swap out the Recursive
6754 E.Str.swap(StubEnc);
6755 E.State = Incomplete;
6756 ++IncompleteCount;
6757}
6758
6759/// Once the RecordType has been expanded, the temporary incomplete TypeString
6760/// must be removed from the cache.
6761/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6762/// Returns true if the RecordType was defined recursively.
6763bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6764 if (!ID)
6765 return false;
6766 auto I = Map.find(ID);
6767 assert(I != Map.end() && "Entry not present");
6768 Entry &E = I->second;
6769 assert( (E.State == Incomplete ||
6770 E.State == IncompleteUsed) &&
6771 "Entry must be an incomplete type");
6772 bool IsRecursive = false;
6773 if (E.State == IncompleteUsed) {
6774 // We made use of our Incomplete encoding, thus we are recursive.
6775 IsRecursive = true;
6776 --IncompleteUsedCount;
6777 }
6778 if (E.Swapped.empty())
6779 Map.erase(I);
6780 else {
6781 // Swap the Recursive back.
6782 E.Swapped.swap(E.Str);
6783 E.Swapped.clear();
6784 E.State = Recursive;
6785 }
6786 --IncompleteCount;
6787 return IsRecursive;
6788}
6789
6790/// Add the encoded TypeString to the cache only if it is NonRecursive or
6791/// Recursive (viz: all sub-members were expanded as fully as possible).
6792void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6793 bool IsRecursive) {
6794 if (!ID || IncompleteUsedCount)
6795 return; // No key or it is is an incomplete sub-type so don't add.
6796 Entry &E = Map[ID];
6797 if (IsRecursive && !E.Str.empty()) {
6798 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6799 "This is not the same Recursive entry");
6800 // The parent container was not recursive after all, so we could have used
6801 // this Recursive sub-member entry after all, but we assumed the worse when
6802 // we started viz: IncompleteCount!=0.
6803 return;
6804 }
6805 assert(E.Str.empty() && "Entry already present");
6806 E.Str = Str.str();
6807 E.State = IsRecursive? Recursive : NonRecursive;
6808}
6809
6810/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6811/// are recursively expanding a type (IncompleteCount != 0) and the cached
6812/// encoding is Recursive, return an empty StringRef.
6813StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6814 if (!ID)
6815 return StringRef(); // We have no key.
6816 auto I = Map.find(ID);
6817 if (I == Map.end())
6818 return StringRef(); // We have no encoding.
6819 Entry &E = I->second;
6820 if (E.State == Recursive && IncompleteCount)
6821 return StringRef(); // We don't use Recursive encodings for member types.
6822
6823 if (E.State == Incomplete) {
6824 // The incomplete type is being used to break out of recursion.
6825 E.State = IncompleteUsed;
6826 ++IncompleteUsedCount;
6827 }
6828 return E.Str.c_str();
6829}
6830
6831/// The XCore ABI includes a type information section that communicates symbol
6832/// type information to the linker. The linker uses this information to verify
6833/// safety/correctness of things such as array bound and pointers et al.
6834/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6835/// This type information (TypeString) is emitted into meta data for all global
6836/// symbols: definitions, declarations, functions & variables.
6837///
6838/// The TypeString carries type, qualifier, name, size & value details.
6839/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00006840/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00006841/// The output is tested by test/CodeGen/xcore-stringtype.c.
6842///
6843static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6844 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6845
6846/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6847void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6848 CodeGen::CodeGenModule &CGM) const {
6849 SmallStringEnc Enc;
6850 if (getTypeString(Enc, D, CGM, TSC)) {
6851 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006852 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6853 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006854 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6855 llvm::NamedMDNode *MD =
6856 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6857 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6858 }
6859}
6860
6861static bool appendType(SmallStringEnc &Enc, QualType QType,
6862 const CodeGen::CodeGenModule &CGM,
6863 TypeStringCache &TSC);
6864
6865/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00006866/// Builds a SmallVector containing the encoded field types in declaration
6867/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006868static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6869 const RecordDecl *RD,
6870 const CodeGen::CodeGenModule &CGM,
6871 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006872 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006873 SmallStringEnc Enc;
6874 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006875 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006876 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006877 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006878 Enc += "b(";
6879 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00006880 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006881 Enc += ':';
6882 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006883 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006884 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006885 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006886 Enc += ')';
6887 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00006888 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006889 }
6890 return true;
6891}
6892
6893/// Appends structure and union types to Enc and adds encoding to cache.
6894/// Recursively calls appendType (via extractFieldType) for each field.
6895/// Union types have their fields ordered according to the ABI.
6896static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6897 const CodeGen::CodeGenModule &CGM,
6898 TypeStringCache &TSC, const IdentifierInfo *ID) {
6899 // Append the cached TypeString if we have one.
6900 StringRef TypeString = TSC.lookupStr(ID);
6901 if (!TypeString.empty()) {
6902 Enc += TypeString;
6903 return true;
6904 }
6905
6906 // Start to emit an incomplete TypeString.
6907 size_t Start = Enc.size();
6908 Enc += (RT->isUnionType()? 'u' : 's');
6909 Enc += '(';
6910 if (ID)
6911 Enc += ID->getName();
6912 Enc += "){";
6913
6914 // We collect all encoded fields and order as necessary.
6915 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006916 const RecordDecl *RD = RT->getDecl()->getDefinition();
6917 if (RD && !RD->field_empty()) {
6918 // An incomplete TypeString stub is placed in the cache for this RecordType
6919 // so that recursive calls to this RecordType will use it whilst building a
6920 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006921 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006922 std::string StubEnc(Enc.substr(Start).str());
6923 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6924 TSC.addIncomplete(ID, std::move(StubEnc));
6925 if (!extractFieldType(FE, RD, CGM, TSC)) {
6926 (void) TSC.removeIncomplete(ID);
6927 return false;
6928 }
6929 IsRecursive = TSC.removeIncomplete(ID);
6930 // The ABI requires unions to be sorted but not structures.
6931 // See FieldEncoding::operator< for sort algorithm.
6932 if (RT->isUnionType())
6933 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006934 // We can now complete the TypeString.
6935 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006936 for (unsigned I = 0; I != E; ++I) {
6937 if (I)
6938 Enc += ',';
6939 Enc += FE[I].str();
6940 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006941 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006942 Enc += '}';
6943 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6944 return true;
6945}
6946
6947/// Appends enum types to Enc and adds the encoding to the cache.
6948static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6949 TypeStringCache &TSC,
6950 const IdentifierInfo *ID) {
6951 // Append the cached TypeString if we have one.
6952 StringRef TypeString = TSC.lookupStr(ID);
6953 if (!TypeString.empty()) {
6954 Enc += TypeString;
6955 return true;
6956 }
6957
6958 size_t Start = Enc.size();
6959 Enc += "e(";
6960 if (ID)
6961 Enc += ID->getName();
6962 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006963
6964 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006965 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006966 SmallVector<FieldEncoding, 16> FE;
6967 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6968 ++I) {
6969 SmallStringEnc EnumEnc;
6970 EnumEnc += "m(";
6971 EnumEnc += I->getName();
6972 EnumEnc += "){";
6973 I->getInitVal().toString(EnumEnc);
6974 EnumEnc += '}';
6975 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6976 }
6977 std::sort(FE.begin(), FE.end());
6978 unsigned E = FE.size();
6979 for (unsigned I = 0; I != E; ++I) {
6980 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006981 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006982 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006983 }
6984 }
6985 Enc += '}';
6986 TSC.addIfComplete(ID, Enc.substr(Start), false);
6987 return true;
6988}
6989
6990/// Appends type's qualifier to Enc.
6991/// This is done prior to appending the type's encoding.
6992static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6993 // Qualifiers are emitted in alphabetical order.
6994 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6995 int Lookup = 0;
6996 if (QT.isConstQualified())
6997 Lookup += 1<<0;
6998 if (QT.isRestrictQualified())
6999 Lookup += 1<<1;
7000 if (QT.isVolatileQualified())
7001 Lookup += 1<<2;
7002 Enc += Table[Lookup];
7003}
7004
7005/// Appends built-in types to Enc.
7006static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7007 const char *EncType;
7008 switch (BT->getKind()) {
7009 case BuiltinType::Void:
7010 EncType = "0";
7011 break;
7012 case BuiltinType::Bool:
7013 EncType = "b";
7014 break;
7015 case BuiltinType::Char_U:
7016 EncType = "uc";
7017 break;
7018 case BuiltinType::UChar:
7019 EncType = "uc";
7020 break;
7021 case BuiltinType::SChar:
7022 EncType = "sc";
7023 break;
7024 case BuiltinType::UShort:
7025 EncType = "us";
7026 break;
7027 case BuiltinType::Short:
7028 EncType = "ss";
7029 break;
7030 case BuiltinType::UInt:
7031 EncType = "ui";
7032 break;
7033 case BuiltinType::Int:
7034 EncType = "si";
7035 break;
7036 case BuiltinType::ULong:
7037 EncType = "ul";
7038 break;
7039 case BuiltinType::Long:
7040 EncType = "sl";
7041 break;
7042 case BuiltinType::ULongLong:
7043 EncType = "ull";
7044 break;
7045 case BuiltinType::LongLong:
7046 EncType = "sll";
7047 break;
7048 case BuiltinType::Float:
7049 EncType = "ft";
7050 break;
7051 case BuiltinType::Double:
7052 EncType = "d";
7053 break;
7054 case BuiltinType::LongDouble:
7055 EncType = "ld";
7056 break;
7057 default:
7058 return false;
7059 }
7060 Enc += EncType;
7061 return true;
7062}
7063
7064/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7065static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7066 const CodeGen::CodeGenModule &CGM,
7067 TypeStringCache &TSC) {
7068 Enc += "p(";
7069 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7070 return false;
7071 Enc += ')';
7072 return true;
7073}
7074
7075/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007076static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7077 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007078 const CodeGen::CodeGenModule &CGM,
7079 TypeStringCache &TSC, StringRef NoSizeEnc) {
7080 if (AT->getSizeModifier() != ArrayType::Normal)
7081 return false;
7082 Enc += "a(";
7083 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7084 CAT->getSize().toStringUnsigned(Enc);
7085 else
7086 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7087 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007088 // The Qualifiers should be attached to the type rather than the array.
7089 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007090 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7091 return false;
7092 Enc += ')';
7093 return true;
7094}
7095
7096/// Appends a function encoding to Enc, calling appendType for the return type
7097/// and the arguments.
7098static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7099 const CodeGen::CodeGenModule &CGM,
7100 TypeStringCache &TSC) {
7101 Enc += "f{";
7102 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7103 return false;
7104 Enc += "}(";
7105 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7106 // N.B. we are only interested in the adjusted param types.
7107 auto I = FPT->param_type_begin();
7108 auto E = FPT->param_type_end();
7109 if (I != E) {
7110 do {
7111 if (!appendType(Enc, *I, CGM, TSC))
7112 return false;
7113 ++I;
7114 if (I != E)
7115 Enc += ',';
7116 } while (I != E);
7117 if (FPT->isVariadic())
7118 Enc += ",va";
7119 } else {
7120 if (FPT->isVariadic())
7121 Enc += "va";
7122 else
7123 Enc += '0';
7124 }
7125 }
7126 Enc += ')';
7127 return true;
7128}
7129
7130/// Handles the type's qualifier before dispatching a call to handle specific
7131/// type encodings.
7132static bool appendType(SmallStringEnc &Enc, QualType QType,
7133 const CodeGen::CodeGenModule &CGM,
7134 TypeStringCache &TSC) {
7135
7136 QualType QT = QType.getCanonicalType();
7137
Robert Lytton6adb20f2014-06-05 09:06:21 +00007138 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7139 // The Qualifiers should be attached to the type rather than the array.
7140 // Thus we don't call appendQualifier() here.
7141 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7142
Robert Lytton844aeeb2014-05-02 09:33:20 +00007143 appendQualifier(Enc, QT);
7144
7145 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7146 return appendBuiltinType(Enc, BT);
7147
Robert Lytton844aeeb2014-05-02 09:33:20 +00007148 if (const PointerType *PT = QT->getAs<PointerType>())
7149 return appendPointerType(Enc, PT, CGM, TSC);
7150
7151 if (const EnumType *ET = QT->getAs<EnumType>())
7152 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7153
7154 if (const RecordType *RT = QT->getAsStructureType())
7155 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7156
7157 if (const RecordType *RT = QT->getAsUnionType())
7158 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7159
7160 if (const FunctionType *FT = QT->getAs<FunctionType>())
7161 return appendFunctionType(Enc, FT, CGM, TSC);
7162
7163 return false;
7164}
7165
7166static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7167 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7168 if (!D)
7169 return false;
7170
7171 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7172 if (FD->getLanguageLinkage() != CLanguageLinkage)
7173 return false;
7174 return appendType(Enc, FD->getType(), CGM, TSC);
7175 }
7176
7177 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7178 if (VD->getLanguageLinkage() != CLanguageLinkage)
7179 return false;
7180 QualType QT = VD->getType().getCanonicalType();
7181 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7182 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007183 // The Qualifiers should be attached to the type rather than the array.
7184 // Thus we don't call appendQualifier() here.
7185 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007186 }
7187 return appendType(Enc, QT, CGM, TSC);
7188 }
7189 return false;
7190}
7191
7192
Robert Lytton0e076492013-08-13 09:43:10 +00007193//===----------------------------------------------------------------------===//
7194// Driver code
7195//===----------------------------------------------------------------------===//
7196
Rafael Espindola9f834732014-09-19 01:54:22 +00007197const llvm::Triple &CodeGenModule::getTriple() const {
7198 return getTarget().getTriple();
7199}
7200
7201bool CodeGenModule::supportsCOMDAT() const {
7202 return !getTriple().isOSBinFormatMachO();
7203}
7204
Chris Lattner2b037972010-07-29 02:01:43 +00007205const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007206 if (TheTargetCodeGenInfo)
7207 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007208
John McCallc8e01702013-04-16 22:48:15 +00007209 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007210 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007211 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007212 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007213
Derek Schuff09338a22012-09-06 17:37:28 +00007214 case llvm::Triple::le32:
7215 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007216 case llvm::Triple::mips:
7217 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007218 if (Triple.getOS() == llvm::Triple::NaCl)
7219 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007220 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7221
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007222 case llvm::Triple::mips64:
7223 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007224 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7225
Tim Northover25e8a672014-05-24 12:51:25 +00007226 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007227 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007228 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007229 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007230 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007231
Tim Northover573cbee2014-05-24 12:52:07 +00007232 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007233 }
7234
Dan Gohmanc2853072015-09-03 22:51:53 +00007235 case llvm::Triple::wasm32:
7236 case llvm::Triple::wasm64:
7237 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7238
Daniel Dunbard59655c2009-09-12 00:59:49 +00007239 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007240 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007241 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007242 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007243 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007244 if (Triple.getOS() == llvm::Triple::Win32) {
7245 TheTargetCodeGenInfo =
7246 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7247 return *TheTargetCodeGenInfo;
7248 }
7249
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007250 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007251 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007252 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007253 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007254 (CodeGenOpts.FloatABI != "soft" &&
7255 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007256 Kind = ARMABIInfo::AAPCS_VFP;
7257
Derek Schuff71658bd2015-01-29 00:47:04 +00007258 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007259 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007260
John McCallea8d8bb2010-03-11 00:10:12 +00007261 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007262 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007263 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007264 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007265 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007266 if (getTarget().getABI() == "elfv2")
7267 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007268 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007269
Ulrich Weigandb7122372014-07-21 00:48:09 +00007270 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007271 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007272 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007273 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007274 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007275 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007276 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007277 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007278 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007279 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007280
Ulrich Weigandb7122372014-07-21 00:48:09 +00007281 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007282 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007283 }
John McCallea8d8bb2010-03-11 00:10:12 +00007284
Peter Collingbournec947aae2012-05-20 23:28:41 +00007285 case llvm::Triple::nvptx:
7286 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007287 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007288
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007289 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007290 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007291
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007292 case llvm::Triple::systemz: {
7293 bool HasVector = getTarget().getABI() == "vector";
7294 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7295 HasVector));
7296 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007297
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007298 case llvm::Triple::tce:
7299 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7300
Eli Friedman33465822011-07-08 23:31:17 +00007301 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007302 bool IsDarwinVectorABI = Triple.isOSDarwin();
7303 bool IsSmallStructInRegABI =
7304 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007305 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007306
John McCall1fe2a8c2013-06-18 02:46:29 +00007307 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007308 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
7309 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7310 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007311 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007312 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
7313 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7314 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007315 }
Eli Friedman33465822011-07-08 23:31:17 +00007316 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007317
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007318 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007319 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007320 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7321 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007322 X86AVXABILevel::None);
7323
Chris Lattner04dc9572010-08-31 16:44:54 +00007324 switch (Triple.getOS()) {
7325 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007326 return *(TheTargetCodeGenInfo =
7327 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007328 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007329 return *(TheTargetCodeGenInfo =
7330 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007331 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007332 return *(TheTargetCodeGenInfo =
7333 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007334 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007335 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007336 case llvm::Triple::hexagon:
7337 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007338 case llvm::Triple::r600:
7339 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007340 case llvm::Triple::amdgcn:
7341 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007342 case llvm::Triple::sparcv9:
7343 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007344 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007345 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007346 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007347}