blob: 53154b513eb703d51e7871cc316ad2027a0a8c15 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000023#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000027#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000028#include <algorithm> // std::sort
29
Anton Korobeynikov244360d2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall943fae92010-05-27 06:19:26 +000033static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
34 llvm::Value *Array,
35 llvm::Value *Value,
36 unsigned FirstIndex,
37 unsigned LastIndex) {
38 // Alternatively, we could emit this as a loop in the source.
39 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000040 llvm::Value *Cell =
41 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall943fae92010-05-27 06:19:26 +000042 Builder.CreateStore(Value, Cell);
43 }
44}
45
John McCalla1dee5302010-08-22 10:59:02 +000046static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000047 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000048 T->isMemberFunctionPointerType();
49}
50
Anton Korobeynikov244360d2009-06-05 22:08:42 +000051ABIInfo::~ABIInfo() {}
52
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000053static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000054 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000055 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
56 if (!RD)
57 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000058 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000059}
60
61static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000062 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000063 const RecordType *RT = T->getAs<RecordType>();
64 if (!RT)
65 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000066 return getRecordArgABI(RT, CXXABI);
67}
68
Reid Klecknerb1be6832014-11-15 01:41:41 +000069/// Pass transparent unions as if they were the type of the first element. Sema
70/// should ensure that all elements of the union have the same "machine type".
71static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
72 if (const RecordType *UT = Ty->getAsUnionType()) {
73 const RecordDecl *UD = UT->getDecl();
74 if (UD->hasAttr<TransparentUnionAttr>()) {
75 assert(!UD->field_empty() && "sema created an empty transparent union");
76 return UD->field_begin()->getType();
77 }
78 }
79 return Ty;
80}
81
Mark Lacey3825e832013-10-06 01:33:34 +000082CGCXXABI &ABIInfo::getCXXABI() const {
83 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000084}
85
Chris Lattner2b037972010-07-29 02:01:43 +000086ASTContext &ABIInfo::getContext() const {
87 return CGT.getContext();
88}
89
90llvm::LLVMContext &ABIInfo::getVMContext() const {
91 return CGT.getLLVMContext();
92}
93
Micah Villmowdd31ca12012-10-08 16:25:52 +000094const llvm::DataLayout &ABIInfo::getDataLayout() const {
95 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000096}
97
John McCallc8e01702013-04-16 22:48:15 +000098const TargetInfo &ABIInfo::getTarget() const {
99 return CGT.getTarget();
100}
Chris Lattner2b037972010-07-29 02:01:43 +0000101
Reid Klecknere9f6a712014-10-31 17:10:41 +0000102bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
103 return false;
104}
105
106bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
107 uint64_t Members) const {
108 return false;
109}
110
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000111bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
112 return false;
113}
114
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000115void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000116 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000117 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000118 switch (TheKind) {
119 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000120 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000121 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000122 Ty->print(OS);
123 else
124 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000125 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000126 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000127 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000128 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000129 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000130 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000131 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000132 case InAlloca:
133 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
134 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000135 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000136 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000137 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000138 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000139 break;
140 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000141 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000142 break;
143 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000144 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000145}
146
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000147TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
148
John McCall3480ef22011-08-30 01:42:09 +0000149// If someone can figure out a general rule for this, that would be great.
150// It's probably just doomed to be platform-dependent, though.
151unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
152 // Verified for:
153 // x86-64 FreeBSD, Linux, Darwin
154 // x86-32 FreeBSD, Linux, Darwin
155 // PowerPC Linux, Darwin
156 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000157 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000158 return 32;
159}
160
John McCalla729c622012-02-17 03:33:10 +0000161bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
162 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000163 // The following conventions are known to require this to be false:
164 // x86_stdcall
165 // MIPS
166 // For everything else, we just prefer false unless we opt out.
167 return false;
168}
169
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000170void
171TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
172 llvm::SmallString<24> &Opt) const {
173 // This assumes the user is passing a library name like "rt" instead of a
174 // filename like "librt.a/so", and that they don't care whether it's static or
175 // dynamic.
176 Opt = "-l";
177 Opt += Lib;
178}
179
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000180static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000181
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000182/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000183/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000184static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
185 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000186 if (FD->isUnnamedBitfield())
187 return true;
188
189 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000190
Eli Friedman0b3f2012011-11-18 03:47:20 +0000191 // Constant arrays of empty records count as empty, strip them off.
192 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000194 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
195 if (AT->getSize() == 0)
196 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000197 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000198 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000199
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000200 const RecordType *RT = FT->getAs<RecordType>();
201 if (!RT)
202 return false;
203
204 // C++ record fields are never empty, at least in the Itanium ABI.
205 //
206 // FIXME: We should use a predicate for whether this behavior is true in the
207 // current ABI.
208 if (isa<CXXRecordDecl>(RT->getDecl()))
209 return false;
210
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000211 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000212}
213
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000214/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215/// fields. Note that a structure with a flexible array member is not
216/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000217static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000218 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000219 if (!RT)
220 return 0;
221 const RecordDecl *RD = RT->getDecl();
222 if (RD->hasFlexibleArrayMember())
223 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000224
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000225 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000226 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000227 for (const auto &I : CXXRD->bases())
228 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000229 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000230
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000231 for (const auto *I : RD->fields())
232 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000233 return false;
234 return true;
235}
236
237/// isSingleElementStruct - Determine if a structure is a "single
238/// element struct", i.e. it has exactly one non-empty field or
239/// exactly one field which is itself a single element
240/// struct. Structures with flexible array members are never
241/// considered single element structs.
242///
243/// \return The field declaration for the single non-empty field, if
244/// it exists.
245static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000246 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000247 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000248 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000249
250 const RecordDecl *RD = RT->getDecl();
251 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000252 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000253
Craig Topper8a13c412014-05-21 05:09:00 +0000254 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000255
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000256 // If this is a C++ record, check the bases first.
257 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000258 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000259 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000260 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000261 continue;
262
263 // If we already found an element then this isn't a single-element struct.
264 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000265 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000266
267 // If this is non-empty and not a single element struct, the composite
268 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000269 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000270 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000271 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000272 }
273 }
274
275 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000276 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000277 QualType FT = FD->getType();
278
279 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000280 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000281 continue;
282
283 // If we already found an element then this isn't a single-element
284 // struct.
285 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000286 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000287
288 // Treat single element arrays as the element.
289 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
290 if (AT->getSize().getZExtValue() != 1)
291 break;
292 FT = AT->getElementType();
293 }
294
John McCalla1dee5302010-08-22 10:59:02 +0000295 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000296 Found = FT.getTypePtr();
297 } else {
298 Found = isSingleElementStruct(FT, Context);
299 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000300 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000301 }
302 }
303
Eli Friedmanee945342011-11-18 01:25:50 +0000304 // We don't consider a struct a single-element struct if it has
305 // padding beyond the element type.
306 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000307 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000308
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000309 return Found;
310}
311
312static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000313 // Treat complex types as the element type.
314 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
315 Ty = CTy->getElementType();
316
317 // Check for a type which we know has a simple scalar argument-passing
318 // convention without any padding. (We're specifically looking for 32
319 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000320 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000321 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000322 return false;
323
324 uint64_t Size = Context.getTypeSize(Ty);
325 return Size == 32 || Size == 64;
326}
327
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000328/// canExpandIndirectArgument - Test whether an argument type which is to be
329/// passed indirectly (on the stack) would have the equivalent layout if it was
330/// expanded into separate arguments. If so, we prefer to do the latter to avoid
331/// inhibiting optimizations.
332///
333// FIXME: This predicate is missing many cases, currently it just follows
334// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
335// should probably make this smarter, or better yet make the LLVM backend
336// capable of handling it.
337static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
338 // We can only expand structure types.
339 const RecordType *RT = Ty->getAs<RecordType>();
340 if (!RT)
341 return false;
342
343 // We can only expand (C) structures.
344 //
345 // FIXME: This needs to be generalized to handle classes as well.
346 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000347 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000348 return false;
349
Manman Ren27382782015-04-03 18:10:29 +0000350 // We try to expand CLike CXXRecordDecl.
351 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
352 if (!CXXRD->isCLike())
353 return false;
354 }
355
Eli Friedmane5c85622011-11-18 01:32:26 +0000356 uint64_t Size = 0;
357
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000358 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000359 if (!is32Or64BitBasicType(FD->getType(), Context))
360 return false;
361
362 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
363 // how to expand them yet, and the predicate for telling if a bitfield still
364 // counts as "basic" is more complicated than what we were doing previously.
365 if (FD->isBitField())
366 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000367
368 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000369 }
370
Eli Friedmane5c85622011-11-18 01:32:26 +0000371 // Make sure there are not any holes in the struct.
372 if (Size != Context.getTypeSize(Ty))
373 return false;
374
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000375 return true;
376}
377
378namespace {
379/// DefaultABIInfo - The default implementation for ABI specific
380/// details. This implementation provides information which results in
381/// self-consistent and sensible LLVM IR generation, but does not
382/// conform to any particular ABI.
383class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000384public:
385 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000386
Chris Lattner458b2aa2010-07-29 02:16:43 +0000387 ABIArgInfo classifyReturnType(QualType RetTy) const;
388 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000389
Craig Topper4f12f102014-03-12 06:41:41 +0000390 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000391 if (!getCXXABI().classifyReturnType(FI))
392 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000393 for (auto &I : FI.arguments())
394 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000395 }
396
Craig Topper4f12f102014-03-12 06:41:41 +0000397 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
398 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000399};
400
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000401class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
402public:
Chris Lattner2b037972010-07-29 02:01:43 +0000403 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
404 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000405};
406
407llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
408 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000409 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000410}
411
Chris Lattner458b2aa2010-07-29 02:16:43 +0000412ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000413 Ty = useFirstFieldIfTransparentUnion(Ty);
414
415 if (isAggregateTypeForABI(Ty)) {
416 // Records with non-trivial destructors/copy-constructors should not be
417 // passed by value.
418 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
419 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
420
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000421 return ABIArgInfo::getIndirect(0);
Reid Klecknerac385062015-05-18 22:46:30 +0000422 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000423
Chris Lattner9723d6c2010-03-11 18:19:55 +0000424 // Treat an enum type as its underlying type.
425 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
426 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000427
Chris Lattner9723d6c2010-03-11 18:19:55 +0000428 return (Ty->isPromotableIntegerType() ?
429 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000430}
431
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000432ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
433 if (RetTy->isVoidType())
434 return ABIArgInfo::getIgnore();
435
436 if (isAggregateTypeForABI(RetTy))
437 return ABIArgInfo::getIndirect(0);
438
439 // Treat an enum type as its underlying type.
440 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
441 RetTy = EnumTy->getDecl()->getIntegerType();
442
443 return (RetTy->isPromotableIntegerType() ?
444 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
445}
446
Derek Schuff09338a22012-09-06 17:37:28 +0000447//===----------------------------------------------------------------------===//
448// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000449//
450// This is a simplified version of the x86_32 ABI. Arguments and return values
451// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000452//===----------------------------------------------------------------------===//
453
454class PNaClABIInfo : public ABIInfo {
455 public:
456 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
457
458 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000459 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000460
Craig Topper4f12f102014-03-12 06:41:41 +0000461 void computeInfo(CGFunctionInfo &FI) const override;
462 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
463 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000464};
465
466class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
467 public:
468 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
469 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
470};
471
472void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000473 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000474 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
475
Reid Kleckner40ca9132014-05-13 22:05:45 +0000476 for (auto &I : FI.arguments())
477 I.info = classifyArgumentType(I.type);
478}
Derek Schuff09338a22012-09-06 17:37:28 +0000479
480llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
481 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000482 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000483}
484
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000485/// \brief Classify argument of given type \p Ty.
486ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000487 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000488 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000489 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000490 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000491 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
492 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000493 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000494 } else if (Ty->isFloatingType()) {
495 // Floating-point types don't go inreg.
496 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000497 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000498
499 return (Ty->isPromotableIntegerType() ?
500 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000501}
502
503ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
504 if (RetTy->isVoidType())
505 return ABIArgInfo::getIgnore();
506
Eli Benderskye20dad62013-04-04 22:49:35 +0000507 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000508 if (isAggregateTypeForABI(RetTy))
509 return ABIArgInfo::getIndirect(0);
510
511 // Treat an enum type as its underlying type.
512 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
513 RetTy = EnumTy->getDecl()->getIntegerType();
514
515 return (RetTy->isPromotableIntegerType() ?
516 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
517}
518
Chad Rosier651c1832013-03-25 21:00:27 +0000519/// IsX86_MMXType - Return true if this is an MMX type.
520bool IsX86_MMXType(llvm::Type *IRType) {
521 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendling5cd41c42010-10-18 03:41:31 +0000522 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
523 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
524 IRType->getScalarSizeInBits() != 64;
525}
526
Jay Foad7c57be32011-07-11 09:56:20 +0000527static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000528 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000529 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000530 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
531 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
532 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000533 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000534 }
535
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000536 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000537 }
538
539 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000540 return Ty;
541}
542
Reid Kleckner80944df2014-10-31 22:00:51 +0000543/// Returns true if this type can be passed in SSE registers with the
544/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
545static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
546 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
547 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
548 return true;
549 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
550 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
551 // registers specially.
552 unsigned VecSize = Context.getTypeSize(VT);
553 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
554 return true;
555 }
556 return false;
557}
558
559/// Returns true if this aggregate is small enough to be passed in SSE registers
560/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
561static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
562 return NumMembers <= 4;
563}
564
Chris Lattner0cf24192010-06-28 20:05:43 +0000565//===----------------------------------------------------------------------===//
566// X86-32 ABI Implementation
567//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000568
Reid Kleckner661f35b2014-01-18 01:12:41 +0000569/// \brief Similar to llvm::CCState, but for Clang.
570struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000571 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000572
573 unsigned CC;
574 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000575 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000576};
577
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578/// X86_32ABIInfo - The X86-32 ABI information.
579class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000580 enum Class {
581 Integer,
582 Float
583 };
584
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000585 static const unsigned MinABIStackAlignInBytes = 4;
586
David Chisnallde3a0692009-08-17 23:08:21 +0000587 bool IsDarwinVectorABI;
588 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000589 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000590 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000591
592 static bool isRegisterSize(unsigned Size) {
593 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
594 }
595
Reid Kleckner80944df2014-10-31 22:00:51 +0000596 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
597 // FIXME: Assumes vectorcall is in use.
598 return isX86VectorTypeForVectorCall(getContext(), Ty);
599 }
600
601 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
602 uint64_t NumMembers) const override {
603 // FIXME: Assumes vectorcall is in use.
604 return isX86VectorCallAggregateSmallEnough(NumMembers);
605 }
606
Reid Kleckner40ca9132014-05-13 22:05:45 +0000607 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000608
Daniel Dunbar557893d2010-04-21 19:10:51 +0000609 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
610 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000611 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
612
613 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000614
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000615 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000616 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000617
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000618 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000619 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000620 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
621 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000622
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000623 /// \brief Rewrite the function info so that all memory arguments use
624 /// inalloca.
625 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
626
627 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
628 unsigned &StackOffset, ABIArgInfo &Info,
629 QualType Type) const;
630
Rafael Espindola75419dc2012-07-23 23:30:29 +0000631public:
632
Craig Topper4f12f102014-03-12 06:41:41 +0000633 void computeInfo(CGFunctionInfo &FI) const override;
634 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
635 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000636
Chad Rosier651c1832013-03-25 21:00:27 +0000637 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000638 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000639 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000640 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000641};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000642
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000643class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
644public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000645 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000646 bool d, bool p, bool w, unsigned r)
647 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000648
John McCall1fe2a8c2013-06-18 02:46:29 +0000649 static bool isStructReturnInRegABI(
650 const llvm::Triple &Triple, const CodeGenOptions &Opts);
651
Charles Davis4ea31ab2010-02-13 15:54:06 +0000652 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000653 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000654
Craig Topper4f12f102014-03-12 06:41:41 +0000655 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000656 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000657 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000658 return 4;
659 }
660
661 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000662 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000663
Jay Foad7c57be32011-07-11 09:56:20 +0000664 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000665 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000666 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000667 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
668 }
669
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000670 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
671 std::string &Constraints,
672 std::vector<llvm::Type *> &ResultRegTypes,
673 std::vector<llvm::Type *> &ResultTruncRegTypes,
674 std::vector<LValue> &ResultRegDests,
675 std::string &AsmString,
676 unsigned NumOutputs) const override;
677
Craig Topper4f12f102014-03-12 06:41:41 +0000678 llvm::Constant *
679 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000680 unsigned Sig = (0xeb << 0) | // jmp rel8
681 (0x06 << 8) | // .+0x08
682 ('F' << 16) |
683 ('T' << 24);
684 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
685 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000686};
687
688}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000689
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000690/// Rewrite input constraint references after adding some output constraints.
691/// In the case where there is one output and one input and we add one output,
692/// we need to replace all operand references greater than or equal to 1:
693/// mov $0, $1
694/// mov eax, $1
695/// The result will be:
696/// mov $0, $2
697/// mov eax, $2
698static void rewriteInputConstraintReferences(unsigned FirstIn,
699 unsigned NumNewOuts,
700 std::string &AsmString) {
701 std::string Buf;
702 llvm::raw_string_ostream OS(Buf);
703 size_t Pos = 0;
704 while (Pos < AsmString.size()) {
705 size_t DollarStart = AsmString.find('$', Pos);
706 if (DollarStart == std::string::npos)
707 DollarStart = AsmString.size();
708 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
709 if (DollarEnd == std::string::npos)
710 DollarEnd = AsmString.size();
711 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
712 Pos = DollarEnd;
713 size_t NumDollars = DollarEnd - DollarStart;
714 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
715 // We have an operand reference.
716 size_t DigitStart = Pos;
717 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
718 if (DigitEnd == std::string::npos)
719 DigitEnd = AsmString.size();
720 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
721 unsigned OperandIndex;
722 if (!OperandStr.getAsInteger(10, OperandIndex)) {
723 if (OperandIndex >= FirstIn)
724 OperandIndex += NumNewOuts;
725 OS << OperandIndex;
726 } else {
727 OS << OperandStr;
728 }
729 Pos = DigitEnd;
730 }
731 }
732 AsmString = std::move(OS.str());
733}
734
735/// Add output constraints for EAX:EDX because they are return registers.
736void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
737 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
738 std::vector<llvm::Type *> &ResultRegTypes,
739 std::vector<llvm::Type *> &ResultTruncRegTypes,
740 std::vector<LValue> &ResultRegDests, std::string &AsmString,
741 unsigned NumOutputs) const {
742 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
743
744 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
745 // larger.
746 if (!Constraints.empty())
747 Constraints += ',';
748 if (RetWidth <= 32) {
749 Constraints += "={eax}";
750 ResultRegTypes.push_back(CGF.Int32Ty);
751 } else {
752 // Use the 'A' constraint for EAX:EDX.
753 Constraints += "=A";
754 ResultRegTypes.push_back(CGF.Int64Ty);
755 }
756
757 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
758 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
759 ResultTruncRegTypes.push_back(CoerceTy);
760
761 // Coerce the integer by bitcasting the return slot pointer.
762 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
763 CoerceTy->getPointerTo()));
764 ResultRegDests.push_back(ReturnSlot);
765
766 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
767}
768
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000769/// shouldReturnTypeInRegister - Determine if the given type should be
770/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000771bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
772 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000773 uint64_t Size = Context.getTypeSize(Ty);
774
775 // Type must be register sized.
776 if (!isRegisterSize(Size))
777 return false;
778
779 if (Ty->isVectorType()) {
780 // 64- and 128- bit vectors inside structures are not returned in
781 // registers.
782 if (Size == 64 || Size == 128)
783 return false;
784
785 return true;
786 }
787
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000788 // If this is a builtin, pointer, enum, complex type, member pointer, or
789 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000790 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000791 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000792 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000793 return true;
794
795 // Arrays are treated like records.
796 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000797 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000798
799 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000800 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000801 if (!RT) return false;
802
Anders Carlsson40446e82010-01-27 03:25:19 +0000803 // FIXME: Traverse bases here too.
804
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000805 // Structure types are passed in register if all fields would be
806 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000807 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000808 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000809 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000810 continue;
811
812 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000813 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000814 return false;
815 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000816 return true;
817}
818
Reid Kleckner661f35b2014-01-18 01:12:41 +0000819ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
820 // If the return value is indirect, then the hidden argument is consuming one
821 // integer register.
822 if (State.FreeRegs) {
823 --State.FreeRegs;
824 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
825 }
826 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
827}
828
Reid Kleckner40ca9132014-05-13 22:05:45 +0000829ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000830 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000831 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000832
Reid Kleckner80944df2014-10-31 22:00:51 +0000833 const Type *Base = nullptr;
834 uint64_t NumElts = 0;
835 if (State.CC == llvm::CallingConv::X86_VectorCall &&
836 isHomogeneousAggregate(RetTy, Base, NumElts)) {
837 // The LLVM struct type for such an aggregate should lower properly.
838 return ABIArgInfo::getDirect();
839 }
840
Chris Lattner458b2aa2010-07-29 02:16:43 +0000841 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000842 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000843 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000844 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000845
846 // 128-bit vectors are a special case; they are returned in
847 // registers and we need to make sure to pick a type the LLVM
848 // backend will like.
849 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000850 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000851 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000852
853 // Always return in register if it fits in a general purpose
854 // register, or if it is 64 bits and has a single element.
855 if ((Size == 8 || Size == 16 || Size == 32) ||
856 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000857 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000858 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000859
Reid Kleckner661f35b2014-01-18 01:12:41 +0000860 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000861 }
862
863 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000864 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000865
John McCalla1dee5302010-08-22 10:59:02 +0000866 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000867 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000868 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000869 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000870 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000871 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000872
David Chisnallde3a0692009-08-17 23:08:21 +0000873 // If specified, structs and unions are always indirect.
874 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000875 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000876
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000877 // Small structures which are register sized are generally returned
878 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000879 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000880 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000881
882 // As a special-case, if the struct is a "single-element" struct, and
883 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000884 // floating-point register. (MSVC does not apply this special case.)
885 // We apply a similar transformation for pointer types to improve the
886 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000887 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000888 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000889 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000890 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
891
892 // FIXME: We should be able to narrow this integer in cases with dead
893 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000894 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000895 }
896
Reid Kleckner661f35b2014-01-18 01:12:41 +0000897 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000898 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000899
Chris Lattner458b2aa2010-07-29 02:16:43 +0000900 // Treat an enum type as its underlying type.
901 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
902 RetTy = EnumTy->getDecl()->getIntegerType();
903
904 return (RetTy->isPromotableIntegerType() ?
905 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000906}
907
Eli Friedman7919bea2012-06-05 19:40:46 +0000908static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
909 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
910}
911
Daniel Dunbared23de32010-09-16 20:42:00 +0000912static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
913 const RecordType *RT = Ty->getAs<RecordType>();
914 if (!RT)
915 return 0;
916 const RecordDecl *RD = RT->getDecl();
917
918 // If this is a C++ record, check the bases first.
919 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000920 for (const auto &I : CXXRD->bases())
921 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000922 return false;
923
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000924 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000925 QualType FT = i->getType();
926
Eli Friedman7919bea2012-06-05 19:40:46 +0000927 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000928 return true;
929
930 if (isRecordWithSSEVectorType(Context, FT))
931 return true;
932 }
933
934 return false;
935}
936
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000937unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
938 unsigned Align) const {
939 // Otherwise, if the alignment is less than or equal to the minimum ABI
940 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000941 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000942 return 0; // Use default alignment.
943
944 // On non-Darwin, the stack type alignment is always 4.
945 if (!IsDarwinVectorABI) {
946 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000947 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000948 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000949
Daniel Dunbared23de32010-09-16 20:42:00 +0000950 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000951 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
952 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000953 return 16;
954
955 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000956}
957
Rafael Espindola703c47f2012-10-19 05:04:37 +0000958ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000959 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000960 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000961 if (State.FreeRegs) {
962 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000963 return ABIArgInfo::getIndirectInReg(0, false);
964 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000965 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000966 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000967
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000968 // Compute the byval alignment.
969 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
970 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
971 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000972 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000973
974 // If the stack alignment is less than the type alignment, realign the
975 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000976 bool Realign = TypeAlign > StackAlign;
977 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000978}
979
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000980X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
981 const Type *T = isSingleElementStruct(Ty, getContext());
982 if (!T)
983 T = Ty.getTypePtr();
984
985 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
986 BuiltinType::Kind K = BT->getKind();
987 if (K == BuiltinType::Float || K == BuiltinType::Double)
988 return Float;
989 }
990 return Integer;
991}
992
Reid Kleckner661f35b2014-01-18 01:12:41 +0000993bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
994 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000995 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000996 Class C = classify(Ty);
997 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000998 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000999
Rafael Espindola077dd592012-10-24 01:58:58 +00001000 unsigned Size = getContext().getTypeSize(Ty);
1001 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001002
1003 if (SizeInRegs == 0)
1004 return false;
1005
Reid Kleckner661f35b2014-01-18 01:12:41 +00001006 if (SizeInRegs > State.FreeRegs) {
1007 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001008 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001009 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001010
Reid Kleckner661f35b2014-01-18 01:12:41 +00001011 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001012
Reid Kleckner80944df2014-10-31 22:00:51 +00001013 if (State.CC == llvm::CallingConv::X86_FastCall ||
1014 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001015 if (Size > 32)
1016 return false;
1017
1018 if (Ty->isIntegralOrEnumerationType())
1019 return true;
1020
1021 if (Ty->isPointerType())
1022 return true;
1023
1024 if (Ty->isReferenceType())
1025 return true;
1026
Reid Kleckner661f35b2014-01-18 01:12:41 +00001027 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001028 NeedsPadding = true;
1029
Rafael Espindola077dd592012-10-24 01:58:58 +00001030 return false;
1031 }
1032
Rafael Espindola703c47f2012-10-19 05:04:37 +00001033 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001034}
1035
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001036ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1037 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001038 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001039
Reid Klecknerb1be6832014-11-15 01:41:41 +00001040 Ty = useFirstFieldIfTransparentUnion(Ty);
1041
Reid Kleckner80944df2014-10-31 22:00:51 +00001042 // Check with the C++ ABI first.
1043 const RecordType *RT = Ty->getAs<RecordType>();
1044 if (RT) {
1045 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1046 if (RAA == CGCXXABI::RAA_Indirect) {
1047 return getIndirectResult(Ty, false, State);
1048 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1049 // The field index doesn't matter, we'll fix it up later.
1050 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1051 }
1052 }
1053
1054 // vectorcall adds the concept of a homogenous vector aggregate, similar
1055 // to other targets.
1056 const Type *Base = nullptr;
1057 uint64_t NumElts = 0;
1058 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1059 isHomogeneousAggregate(Ty, Base, NumElts)) {
1060 if (State.FreeSSERegs >= NumElts) {
1061 State.FreeSSERegs -= NumElts;
1062 if (Ty->isBuiltinType() || Ty->isVectorType())
1063 return ABIArgInfo::getDirect();
1064 return ABIArgInfo::getExpand();
1065 }
1066 return getIndirectResult(Ty, /*ByVal=*/false, State);
1067 }
1068
1069 if (isAggregateTypeForABI(Ty)) {
1070 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001071 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001072 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001073 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001074
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001075 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001076 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001077 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001078 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001079
Eli Friedman9f061a32011-11-18 00:28:11 +00001080 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001081 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001082 return ABIArgInfo::getIgnore();
1083
Rafael Espindolafad28de2012-10-24 01:59:00 +00001084 llvm::LLVMContext &LLVMContext = getVMContext();
1085 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1086 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001087 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001088 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001089 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001090 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1091 return ABIArgInfo::getDirectInReg(Result);
1092 }
Craig Topper8a13c412014-05-21 05:09:00 +00001093 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001094
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001095 // Expand small (<= 128-bit) record types when we know that the stack layout
1096 // of those arguments will match the struct. This is important because the
1097 // LLVM backend isn't smart enough to remove byval, which inhibits many
1098 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001099 if (getContext().getTypeSize(Ty) <= 4*32 &&
1100 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001101 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001102 State.CC == llvm::CallingConv::X86_FastCall ||
1103 State.CC == llvm::CallingConv::X86_VectorCall,
1104 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001105
Reid Kleckner661f35b2014-01-18 01:12:41 +00001106 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001107 }
1108
Chris Lattnerd774ae92010-08-26 20:05:13 +00001109 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001110 // On Darwin, some vectors are passed in memory, we handle this by passing
1111 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001112 if (IsDarwinVectorABI) {
1113 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001114 if ((Size == 8 || Size == 16 || Size == 32) ||
1115 (Size == 64 && VT->getNumElements() == 1))
1116 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1117 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001118 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001119
Chad Rosier651c1832013-03-25 21:00:27 +00001120 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1121 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001122
Chris Lattnerd774ae92010-08-26 20:05:13 +00001123 return ABIArgInfo::getDirect();
1124 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001125
1126
Chris Lattner458b2aa2010-07-29 02:16:43 +00001127 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1128 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001129
Rafael Espindolafad28de2012-10-24 01:59:00 +00001130 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001131 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001132
1133 if (Ty->isPromotableIntegerType()) {
1134 if (InReg)
1135 return ABIArgInfo::getExtendInReg();
1136 return ABIArgInfo::getExtend();
1137 }
1138 if (InReg)
1139 return ABIArgInfo::getDirectInReg();
1140 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001141}
1142
Rafael Espindolaa6472962012-07-24 00:01:07 +00001143void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001144 CCState State(FI.getCallingConvention());
1145 if (State.CC == llvm::CallingConv::X86_FastCall)
1146 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001147 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1148 State.FreeRegs = 2;
1149 State.FreeSSERegs = 6;
1150 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001151 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001152 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001153 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001154
Reid Kleckner677539d2014-07-10 01:58:55 +00001155 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001156 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001157 } else if (FI.getReturnInfo().isIndirect()) {
1158 // The C++ ABI is not aware of register usage, so we have to check if the
1159 // return value was sret and put it in a register ourselves if appropriate.
1160 if (State.FreeRegs) {
1161 --State.FreeRegs; // The sret parameter consumes a register.
1162 FI.getReturnInfo().setInReg(true);
1163 }
1164 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001165
Peter Collingbournef7706832014-12-12 23:41:25 +00001166 // The chain argument effectively gives us another free register.
1167 if (FI.isChainCall())
1168 ++State.FreeRegs;
1169
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001170 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001171 for (auto &I : FI.arguments()) {
1172 I.info = classifyArgumentType(I.type, State);
1173 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001174 }
1175
1176 // If we needed to use inalloca for any argument, do a second pass and rewrite
1177 // all the memory arguments to use inalloca.
1178 if (UsedInAlloca)
1179 rewriteWithInAlloca(FI);
1180}
1181
1182void
1183X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1184 unsigned &StackOffset,
1185 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001186 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1187 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1188 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1189 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1190
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001191 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1192 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001193 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001194 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001195 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001196 unsigned NumBytes = StackOffset - OldOffset;
1197 assert(NumBytes);
1198 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1199 Ty = llvm::ArrayType::get(Ty, NumBytes);
1200 FrameFields.push_back(Ty);
1201 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001202}
1203
Reid Kleckner852361d2014-07-26 00:12:26 +00001204static bool isArgInAlloca(const ABIArgInfo &Info) {
1205 // Leave ignored and inreg arguments alone.
1206 switch (Info.getKind()) {
1207 case ABIArgInfo::InAlloca:
1208 return true;
1209 case ABIArgInfo::Indirect:
1210 assert(Info.getIndirectByVal());
1211 return true;
1212 case ABIArgInfo::Ignore:
1213 return false;
1214 case ABIArgInfo::Direct:
1215 case ABIArgInfo::Extend:
1216 case ABIArgInfo::Expand:
1217 if (Info.getInReg())
1218 return false;
1219 return true;
1220 }
1221 llvm_unreachable("invalid enum");
1222}
1223
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001224void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1225 assert(IsWin32StructABI && "inalloca only supported on win32");
1226
1227 // Build a packed struct type for all of the arguments in memory.
1228 SmallVector<llvm::Type *, 6> FrameFields;
1229
1230 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001231 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1232
1233 // Put 'this' into the struct before 'sret', if necessary.
1234 bool IsThisCall =
1235 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1236 ABIArgInfo &Ret = FI.getReturnInfo();
1237 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1238 isArgInAlloca(I->info)) {
1239 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1240 ++I;
1241 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001242
1243 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001244 if (Ret.isIndirect() && !Ret.getInReg()) {
1245 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1246 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001247 // On Windows, the hidden sret parameter is always returned in eax.
1248 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001249 }
1250
1251 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001252 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001253 ++I;
1254
1255 // Put arguments passed in memory into the struct.
1256 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001257 if (isArgInAlloca(I->info))
1258 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001259 }
1260
1261 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1262 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001263}
1264
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001265llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1266 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001267 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001268
1269 CGBuilderTy &Builder = CGF.Builder;
1270 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1271 "ap");
1272 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001273
1274 // Compute if the address needs to be aligned
1275 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1276 Align = getTypeStackAlignInBytes(Ty, Align);
1277 Align = std::max(Align, 4U);
1278 if (Align > 4) {
1279 // addr = (addr + align - 1) & -align;
1280 llvm::Value *Offset =
1281 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1282 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1283 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1284 CGF.Int32Ty);
1285 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1286 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1287 Addr->getType(),
1288 "ap.cur.aligned");
1289 }
1290
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001291 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001292 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001293 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1294
1295 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001296 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001297 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001298 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001299 "ap.next");
1300 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1301
1302 return AddrTyped;
1303}
1304
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001305bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1306 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1307 assert(Triple.getArch() == llvm::Triple::x86);
1308
1309 switch (Opts.getStructReturnConvention()) {
1310 case CodeGenOptions::SRCK_Default:
1311 break;
1312 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1313 return false;
1314 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1315 return true;
1316 }
1317
1318 if (Triple.isOSDarwin())
1319 return true;
1320
1321 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001322 case llvm::Triple::DragonFly:
1323 case llvm::Triple::FreeBSD:
1324 case llvm::Triple::OpenBSD:
1325 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001326 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001327 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001328 default:
1329 return false;
1330 }
1331}
1332
Charles Davis4ea31ab2010-02-13 15:54:06 +00001333void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1334 llvm::GlobalValue *GV,
1335 CodeGen::CodeGenModule &CGM) const {
1336 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1337 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1338 // Get the LLVM function.
1339 llvm::Function *Fn = cast<llvm::Function>(GV);
1340
1341 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001342 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001343 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001344 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1345 llvm::AttributeSet::get(CGM.getLLVMContext(),
1346 llvm::AttributeSet::FunctionIndex,
1347 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001348 }
1349 }
1350}
1351
John McCallbeec5a02010-03-06 00:35:14 +00001352bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1353 CodeGen::CodeGenFunction &CGF,
1354 llvm::Value *Address) const {
1355 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001356
Chris Lattnerece04092012-02-07 00:39:47 +00001357 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001358
John McCallbeec5a02010-03-06 00:35:14 +00001359 // 0-7 are the eight integer registers; the order is different
1360 // on Darwin (for EH), but the range is the same.
1361 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001362 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001363
John McCallc8e01702013-04-16 22:48:15 +00001364 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001365 // 12-16 are st(0..4). Not sure why we stop at 4.
1366 // These have size 16, which is sizeof(long double) on
1367 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001368 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001369 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001370
John McCallbeec5a02010-03-06 00:35:14 +00001371 } else {
1372 // 9 is %eflags, which doesn't get a size on Darwin for some
1373 // reason.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001374 Builder.CreateStore(
1375 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9));
John McCallbeec5a02010-03-06 00:35:14 +00001376
1377 // 11-16 are st(0..5). Not sure why we stop at 5.
1378 // These have size 12, which is sizeof(long double) on
1379 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001380 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001381 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1382 }
John McCallbeec5a02010-03-06 00:35:14 +00001383
1384 return false;
1385}
1386
Chris Lattner0cf24192010-06-28 20:05:43 +00001387//===----------------------------------------------------------------------===//
1388// X86-64 ABI Implementation
1389//===----------------------------------------------------------------------===//
1390
1391
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001392namespace {
1393/// X86_64ABIInfo - The X86_64 ABI information.
1394class X86_64ABIInfo : public ABIInfo {
1395 enum Class {
1396 Integer = 0,
1397 SSE,
1398 SSEUp,
1399 X87,
1400 X87Up,
1401 ComplexX87,
1402 NoClass,
1403 Memory
1404 };
1405
1406 /// merge - Implement the X86_64 ABI merging algorithm.
1407 ///
1408 /// Merge an accumulating classification \arg Accum with a field
1409 /// classification \arg Field.
1410 ///
1411 /// \param Accum - The accumulating classification. This should
1412 /// always be either NoClass or the result of a previous merge
1413 /// call. In addition, this should never be Memory (the caller
1414 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001415 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001416
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001417 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1418 ///
1419 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1420 /// final MEMORY or SSE classes when necessary.
1421 ///
1422 /// \param AggregateSize - The size of the current aggregate in
1423 /// the classification process.
1424 ///
1425 /// \param Lo - The classification for the parts of the type
1426 /// residing in the low word of the containing object.
1427 ///
1428 /// \param Hi - The classification for the parts of the type
1429 /// residing in the higher words of the containing object.
1430 ///
1431 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1432
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001433 /// classify - Determine the x86_64 register classes in which the
1434 /// given type T should be passed.
1435 ///
1436 /// \param Lo - The classification for the parts of the type
1437 /// residing in the low word of the containing object.
1438 ///
1439 /// \param Hi - The classification for the parts of the type
1440 /// residing in the high word of the containing object.
1441 ///
1442 /// \param OffsetBase - The bit offset of this type in the
1443 /// containing object. Some parameters are classified different
1444 /// depending on whether they straddle an eightbyte boundary.
1445 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001446 /// \param isNamedArg - Whether the argument in question is a "named"
1447 /// argument, as used in AMD64-ABI 3.5.7.
1448 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001449 /// If a word is unused its result will be NoClass; if a type should
1450 /// be passed in Memory then at least the classification of \arg Lo
1451 /// will be Memory.
1452 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001453 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001454 ///
1455 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1456 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001457 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1458 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001459
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001460 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001461 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1462 unsigned IROffset, QualType SourceTy,
1463 unsigned SourceOffset) const;
1464 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1465 unsigned IROffset, QualType SourceTy,
1466 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001467
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001468 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001469 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001470 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001471
1472 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001473 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001474 ///
1475 /// \param freeIntRegs - The number of free integer registers remaining
1476 /// available.
1477 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001478
Chris Lattner458b2aa2010-07-29 02:16:43 +00001479 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001480
Bill Wendling5cd41c42010-10-18 03:41:31 +00001481 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001482 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001483 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001484 unsigned &neededSSE,
1485 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001486
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001487 bool IsIllegalVectorType(QualType Ty) const;
1488
John McCalle0fda732011-04-21 01:20:55 +00001489 /// The 0.98 ABI revision clarified a lot of ambiguities,
1490 /// unfortunately in ways that were not always consistent with
1491 /// certain previous compilers. In particular, platforms which
1492 /// required strict binary compatibility with older versions of GCC
1493 /// may need to exempt themselves.
1494 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001495 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001496 }
1497
Derek Schuffc7dd7222012-10-11 15:52:22 +00001498 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1499 // 64-bit hardware.
1500 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001501
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001502public:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001503 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT) :
1504 ABIInfo(CGT),
Derek Schuff8a872f32012-10-11 18:21:13 +00001505 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001506 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001507
John McCalla729c622012-02-17 03:33:10 +00001508 bool isPassedUsingAVXType(QualType type) const {
1509 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001510 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001511 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1512 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001513 if (info.isDirect()) {
1514 llvm::Type *ty = info.getCoerceToType();
1515 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1516 return (vectorTy->getBitWidth() > 128);
1517 }
1518 return false;
1519 }
1520
Craig Topper4f12f102014-03-12 06:41:41 +00001521 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001522
Craig Topper4f12f102014-03-12 06:41:41 +00001523 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1524 CodeGenFunction &CGF) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001525
1526 bool has64BitPointers() const {
1527 return Has64BitPointers;
1528 }
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001529
1530 bool hasAVX() const {
1531 return getTarget().getABI() == "avx";
1532 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001533};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001534
Chris Lattner04dc9572010-08-31 16:44:54 +00001535/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001536class WinX86_64ABIInfo : public ABIInfo {
1537
Reid Kleckner80944df2014-10-31 22:00:51 +00001538 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1539 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001540
Chris Lattner04dc9572010-08-31 16:44:54 +00001541public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001542 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1543
Craig Topper4f12f102014-03-12 06:41:41 +00001544 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001545
Craig Topper4f12f102014-03-12 06:41:41 +00001546 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1547 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001548
1549 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1550 // FIXME: Assumes vectorcall is in use.
1551 return isX86VectorTypeForVectorCall(getContext(), Ty);
1552 }
1553
1554 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1555 uint64_t NumMembers) const override {
1556 // FIXME: Assumes vectorcall is in use.
1557 return isX86VectorCallAggregateSmallEnough(NumMembers);
1558 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001559};
1560
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001561class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1562public:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001563 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1564 : TargetCodeGenInfo(new X86_64ABIInfo(CGT)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001565
John McCalla729c622012-02-17 03:33:10 +00001566 const X86_64ABIInfo &getABIInfo() const {
1567 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1568 }
1569
Craig Topper4f12f102014-03-12 06:41:41 +00001570 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001571 return 7;
1572 }
1573
1574 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001575 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001576 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001577
John McCall943fae92010-05-27 06:19:26 +00001578 // 0-15 are the 16 integer registers.
1579 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001580 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001581 return false;
1582 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001583
Jay Foad7c57be32011-07-11 09:56:20 +00001584 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001585 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001586 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001587 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1588 }
1589
John McCalla729c622012-02-17 03:33:10 +00001590 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001591 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001592 // The default CC on x86-64 sets %al to the number of SSA
1593 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001594 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001595 // that when AVX types are involved: the ABI explicitly states it is
1596 // undefined, and it doesn't work in practice because of how the ABI
1597 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001598 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001599 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001600 for (CallArgList::const_iterator
1601 it = args.begin(), ie = args.end(); it != ie; ++it) {
1602 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1603 HasAVXType = true;
1604 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001605 }
1606 }
John McCalla729c622012-02-17 03:33:10 +00001607
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001608 if (!HasAVXType)
1609 return true;
1610 }
John McCallcbc038a2011-09-21 08:08:30 +00001611
John McCalla729c622012-02-17 03:33:10 +00001612 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001613 }
1614
Craig Topper4f12f102014-03-12 06:41:41 +00001615 llvm::Constant *
1616 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001617 unsigned Sig;
1618 if (getABIInfo().has64BitPointers())
1619 Sig = (0xeb << 0) | // jmp rel8
1620 (0x0a << 8) | // .+0x0c
1621 ('F' << 16) |
1622 ('T' << 24);
1623 else
1624 Sig = (0xeb << 0) | // jmp rel8
1625 (0x06 << 8) | // .+0x08
1626 ('F' << 16) |
1627 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001628 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1629 }
1630
Alexander Musman09184fe2014-09-30 05:29:28 +00001631 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001632 return getABIInfo().hasAVX() ? 32 : 16;
Alexander Musman09184fe2014-09-30 05:29:28 +00001633 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001634};
1635
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001636class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1637public:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001638 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1639 : X86_64TargetCodeGenInfo(CGT) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001640
1641 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001642 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001643 Opt = "\01";
1644 Opt += Lib;
1645 }
1646};
1647
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001648static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001649 // If the argument does not end in .lib, automatically add the suffix.
1650 // If the argument contains a space, enclose it in quotes.
1651 // This matches the behavior of MSVC.
1652 bool Quote = (Lib.find(" ") != StringRef::npos);
1653 std::string ArgStr = Quote ? "\"" : "";
1654 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001655 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001656 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001657 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001658 return ArgStr;
1659}
1660
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001661class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1662public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001663 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1664 bool d, bool p, bool w, unsigned RegParms)
1665 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001666
Hans Wennborg77dc2362015-01-20 19:45:50 +00001667 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1668 CodeGen::CodeGenModule &CGM) const override;
1669
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001670 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001671 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001672 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001673 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001674 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001675
1676 void getDetectMismatchOption(llvm::StringRef Name,
1677 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001678 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001679 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001680 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001681};
1682
Hans Wennborg77dc2362015-01-20 19:45:50 +00001683static void addStackProbeSizeTargetAttribute(const Decl *D,
1684 llvm::GlobalValue *GV,
1685 CodeGen::CodeGenModule &CGM) {
1686 if (isa<FunctionDecl>(D)) {
1687 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1688 llvm::Function *Fn = cast<llvm::Function>(GV);
1689
1690 Fn->addFnAttr("stack-probe-size", llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
1691 }
1692 }
1693}
1694
1695void WinX86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1696 llvm::GlobalValue *GV,
1697 CodeGen::CodeGenModule &CGM) const {
1698 X86_32TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1699
1700 addStackProbeSizeTargetAttribute(D, GV, CGM);
1701}
1702
Chris Lattner04dc9572010-08-31 16:44:54 +00001703class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001704 bool hasAVX() const { return getABIInfo().getTarget().getABI() == "avx"; }
1705
Chris Lattner04dc9572010-08-31 16:44:54 +00001706public:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001707 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1708 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001709
Hans Wennborg77dc2362015-01-20 19:45:50 +00001710 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1711 CodeGen::CodeGenModule &CGM) const override;
1712
Craig Topper4f12f102014-03-12 06:41:41 +00001713 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001714 return 7;
1715 }
1716
1717 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001718 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001719 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001720
Chris Lattner04dc9572010-08-31 16:44:54 +00001721 // 0-15 are the 16 integer registers.
1722 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001723 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001724 return false;
1725 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001726
1727 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001728 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001729 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001730 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001731 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001732
1733 void getDetectMismatchOption(llvm::StringRef Name,
1734 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001735 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001736 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001737 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001738
1739 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001740 return hasAVX() ? 32 : 16;
Alexander Musman09184fe2014-09-30 05:29:28 +00001741 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001742};
1743
Hans Wennborg77dc2362015-01-20 19:45:50 +00001744void WinX86_64TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1745 llvm::GlobalValue *GV,
1746 CodeGen::CodeGenModule &CGM) const {
1747 TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1748
1749 addStackProbeSizeTargetAttribute(D, GV, CGM);
1750}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001751}
1752
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001753void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1754 Class &Hi) const {
1755 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1756 //
1757 // (a) If one of the classes is Memory, the whole argument is passed in
1758 // memory.
1759 //
1760 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1761 // memory.
1762 //
1763 // (c) If the size of the aggregate exceeds two eightbytes and the first
1764 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1765 // argument is passed in memory. NOTE: This is necessary to keep the
1766 // ABI working for processors that don't support the __m256 type.
1767 //
1768 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1769 //
1770 // Some of these are enforced by the merging logic. Others can arise
1771 // only with unions; for example:
1772 // union { _Complex double; unsigned; }
1773 //
1774 // Note that clauses (b) and (c) were added in 0.98.
1775 //
1776 if (Hi == Memory)
1777 Lo = Memory;
1778 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1779 Lo = Memory;
1780 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1781 Lo = Memory;
1782 if (Hi == SSEUp && Lo != SSE)
1783 Hi = SSE;
1784}
1785
Chris Lattnerd776fb12010-06-28 21:43:59 +00001786X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001787 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1788 // classified recursively so that always two fields are
1789 // considered. The resulting class is calculated according to
1790 // the classes of the fields in the eightbyte:
1791 //
1792 // (a) If both classes are equal, this is the resulting class.
1793 //
1794 // (b) If one of the classes is NO_CLASS, the resulting class is
1795 // the other class.
1796 //
1797 // (c) If one of the classes is MEMORY, the result is the MEMORY
1798 // class.
1799 //
1800 // (d) If one of the classes is INTEGER, the result is the
1801 // INTEGER.
1802 //
1803 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1804 // MEMORY is used as class.
1805 //
1806 // (f) Otherwise class SSE is used.
1807
1808 // Accum should never be memory (we should have returned) or
1809 // ComplexX87 (because this cannot be passed in a structure).
1810 assert((Accum != Memory && Accum != ComplexX87) &&
1811 "Invalid accumulated classification during merge.");
1812 if (Accum == Field || Field == NoClass)
1813 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001814 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001815 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001816 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001817 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001818 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001819 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001820 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1821 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001822 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001823 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001824}
1825
Chris Lattner5c740f12010-06-30 19:14:05 +00001826void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001827 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001828 // FIXME: This code can be simplified by introducing a simple value class for
1829 // Class pairs with appropriate constructor methods for the various
1830 // situations.
1831
1832 // FIXME: Some of the split computations are wrong; unaligned vectors
1833 // shouldn't be passed in registers for example, so there is no chance they
1834 // can straddle an eightbyte. Verify & simplify.
1835
1836 Lo = Hi = NoClass;
1837
1838 Class &Current = OffsetBase < 64 ? Lo : Hi;
1839 Current = Memory;
1840
John McCall9dd450b2009-09-21 23:43:11 +00001841 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001842 BuiltinType::Kind k = BT->getKind();
1843
1844 if (k == BuiltinType::Void) {
1845 Current = NoClass;
1846 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1847 Lo = Integer;
1848 Hi = Integer;
1849 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1850 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001851 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1852 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001853 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001854 Current = SSE;
1855 } else if (k == BuiltinType::LongDouble) {
1856 Lo = X87;
1857 Hi = X87Up;
1858 }
1859 // FIXME: _Decimal32 and _Decimal64 are SSE.
1860 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001861 return;
1862 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001863
Chris Lattnerd776fb12010-06-28 21:43:59 +00001864 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001865 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001866 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001867 return;
1868 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001869
Chris Lattnerd776fb12010-06-28 21:43:59 +00001870 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001871 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001872 return;
1873 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001874
Chris Lattnerd776fb12010-06-28 21:43:59 +00001875 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001876 if (Ty->isMemberFunctionPointerType()) {
1877 if (Has64BitPointers) {
1878 // If Has64BitPointers, this is an {i64, i64}, so classify both
1879 // Lo and Hi now.
1880 Lo = Hi = Integer;
1881 } else {
1882 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1883 // straddles an eightbyte boundary, Hi should be classified as well.
1884 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1885 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1886 if (EB_FuncPtr != EB_ThisAdj) {
1887 Lo = Hi = Integer;
1888 } else {
1889 Current = Integer;
1890 }
1891 }
1892 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001893 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001894 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001895 return;
1896 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001897
Chris Lattnerd776fb12010-06-28 21:43:59 +00001898 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001899 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001900 if (Size == 32) {
1901 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1902 // float> as integer.
1903 Current = Integer;
1904
1905 // If this type crosses an eightbyte boundary, it should be
1906 // split.
1907 uint64_t EB_Real = (OffsetBase) / 64;
1908 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1909 if (EB_Real != EB_Imag)
1910 Hi = Lo;
1911 } else if (Size == 64) {
1912 // gcc passes <1 x double> in memory. :(
1913 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1914 return;
1915
1916 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001917 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001918 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1919 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1920 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001921 Current = Integer;
1922 else
1923 Current = SSE;
1924
1925 // If this type crosses an eightbyte boundary, it should be
1926 // split.
1927 if (OffsetBase && OffsetBase != 64)
1928 Hi = Lo;
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00001929 } else if (Size == 128 || (hasAVX() && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001930 // Arguments of 256-bits are split into four eightbyte chunks. The
1931 // least significant one belongs to class SSE and all the others to class
1932 // SSEUP. The original Lo and Hi design considers that types can't be
1933 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1934 // This design isn't correct for 256-bits, but since there're no cases
1935 // where the upper parts would need to be inspected, avoid adding
1936 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001937 //
1938 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1939 // registers if they are "named", i.e. not part of the "..." of a
1940 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001941 Lo = SSE;
1942 Hi = SSEUp;
1943 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001944 return;
1945 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001946
Chris Lattnerd776fb12010-06-28 21:43:59 +00001947 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001948 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001949
Chris Lattner2b037972010-07-29 02:01:43 +00001950 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001951 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001952 if (Size <= 64)
1953 Current = Integer;
1954 else if (Size <= 128)
1955 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001956 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001957 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001958 else if (ET == getContext().DoubleTy ||
1959 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001960 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001961 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001962 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001963 Current = ComplexX87;
1964
1965 // If this complex type crosses an eightbyte boundary then it
1966 // should be split.
1967 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001968 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001969 if (Hi == NoClass && EB_Real != EB_Imag)
1970 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001971
Chris Lattnerd776fb12010-06-28 21:43:59 +00001972 return;
1973 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001974
Chris Lattner2b037972010-07-29 02:01:43 +00001975 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001976 // Arrays are treated like structures.
1977
Chris Lattner2b037972010-07-29 02:01:43 +00001978 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001979
1980 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001981 // than four eightbytes, ..., it has class MEMORY.
1982 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001983 return;
1984
1985 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1986 // fields, it has class MEMORY.
1987 //
1988 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001989 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001990 return;
1991
1992 // Otherwise implement simplified merge. We could be smarter about
1993 // this, but it isn't worth it and would be harder to verify.
1994 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001995 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001996 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001997
1998 // The only case a 256-bit wide vector could be used is when the array
1999 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2000 // to work for sizes wider than 128, early check and fallback to memory.
2001 if (Size > 128 && EltSize != 256)
2002 return;
2003
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002004 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2005 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002006 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002007 Lo = merge(Lo, FieldLo);
2008 Hi = merge(Hi, FieldHi);
2009 if (Lo == Memory || Hi == Memory)
2010 break;
2011 }
2012
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002013 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002014 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002015 return;
2016 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002017
Chris Lattnerd776fb12010-06-28 21:43:59 +00002018 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002019 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002020
2021 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002022 // than four eightbytes, ..., it has class MEMORY.
2023 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002024 return;
2025
Anders Carlsson20759ad2009-09-16 15:53:40 +00002026 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2027 // copy constructor or a non-trivial destructor, it is passed by invisible
2028 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002029 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002030 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002031
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002032 const RecordDecl *RD = RT->getDecl();
2033
2034 // Assume variable sized types are passed in memory.
2035 if (RD->hasFlexibleArrayMember())
2036 return;
2037
Chris Lattner2b037972010-07-29 02:01:43 +00002038 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002039
2040 // Reset Lo class, this will be recomputed.
2041 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002042
2043 // If this is a C++ record, classify the bases first.
2044 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002045 for (const auto &I : CXXRD->bases()) {
2046 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002047 "Unexpected base class!");
2048 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002049 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002050
2051 // Classify this field.
2052 //
2053 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2054 // single eightbyte, each is classified separately. Each eightbyte gets
2055 // initialized to class NO_CLASS.
2056 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002057 uint64_t Offset =
2058 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002059 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002060 Lo = merge(Lo, FieldLo);
2061 Hi = merge(Hi, FieldHi);
2062 if (Lo == Memory || Hi == Memory)
2063 break;
2064 }
2065 }
2066
2067 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002068 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002069 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002070 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002071 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2072 bool BitField = i->isBitField();
2073
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002074 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2075 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002076 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002077 // The only case a 256-bit wide vector could be used is when the struct
2078 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2079 // to work for sizes wider than 128, early check and fallback to memory.
2080 //
2081 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2082 Lo = Memory;
2083 return;
2084 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002085 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002086 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002087 Lo = Memory;
2088 return;
2089 }
2090
2091 // Classify this field.
2092 //
2093 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2094 // exceeds a single eightbyte, each is classified
2095 // separately. Each eightbyte gets initialized to class
2096 // NO_CLASS.
2097 Class FieldLo, FieldHi;
2098
2099 // Bit-fields require special handling, they do not force the
2100 // structure to be passed in memory even if unaligned, and
2101 // therefore they can straddle an eightbyte.
2102 if (BitField) {
2103 // Ignore padding bit-fields.
2104 if (i->isUnnamedBitfield())
2105 continue;
2106
2107 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002108 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002109
2110 uint64_t EB_Lo = Offset / 64;
2111 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002112
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002113 if (EB_Lo) {
2114 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2115 FieldLo = NoClass;
2116 FieldHi = Integer;
2117 } else {
2118 FieldLo = Integer;
2119 FieldHi = EB_Hi ? Integer : NoClass;
2120 }
2121 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002122 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002123 Lo = merge(Lo, FieldLo);
2124 Hi = merge(Hi, FieldHi);
2125 if (Lo == Memory || Hi == Memory)
2126 break;
2127 }
2128
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002129 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002130 }
2131}
2132
Chris Lattner22a931e2010-06-29 06:01:59 +00002133ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002134 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2135 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002136 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002137 // Treat an enum type as its underlying type.
2138 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2139 Ty = EnumTy->getDecl()->getIntegerType();
2140
2141 return (Ty->isPromotableIntegerType() ?
2142 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2143 }
2144
2145 return ABIArgInfo::getIndirect(0);
2146}
2147
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002148bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2149 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2150 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00002151 unsigned LargestVector = hasAVX() ? 256 : 128;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002152 if (Size <= 64 || Size > LargestVector)
2153 return true;
2154 }
2155
2156 return false;
2157}
2158
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002159ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2160 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002161 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2162 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002163 //
2164 // This assumption is optimistic, as there could be free registers available
2165 // when we need to pass this argument in memory, and LLVM could try to pass
2166 // the argument in the free register. This does not seem to happen currently,
2167 // but this code would be much safer if we could mark the argument with
2168 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002169 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002170 // Treat an enum type as its underlying type.
2171 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2172 Ty = EnumTy->getDecl()->getIntegerType();
2173
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002174 return (Ty->isPromotableIntegerType() ?
2175 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002176 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002177
Mark Lacey3825e832013-10-06 01:33:34 +00002178 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002179 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002180
Chris Lattner44c2b902011-05-22 23:21:23 +00002181 // Compute the byval alignment. We specify the alignment of the byval in all
2182 // cases so that the mid-level optimizer knows the alignment of the byval.
2183 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002184
2185 // Attempt to avoid passing indirect results using byval when possible. This
2186 // is important for good codegen.
2187 //
2188 // We do this by coercing the value into a scalar type which the backend can
2189 // handle naturally (i.e., without using byval).
2190 //
2191 // For simplicity, we currently only do this when we have exhausted all of the
2192 // free integer registers. Doing this when there are free integer registers
2193 // would require more care, as we would have to ensure that the coerced value
2194 // did not claim the unused register. That would require either reording the
2195 // arguments to the function (so that any subsequent inreg values came first),
2196 // or only doing this optimization when there were no following arguments that
2197 // might be inreg.
2198 //
2199 // We currently expect it to be rare (particularly in well written code) for
2200 // arguments to be passed on the stack when there are still free integer
2201 // registers available (this would typically imply large structs being passed
2202 // by value), so this seems like a fair tradeoff for now.
2203 //
2204 // We can revisit this if the backend grows support for 'onstack' parameter
2205 // attributes. See PR12193.
2206 if (freeIntRegs == 0) {
2207 uint64_t Size = getContext().getTypeSize(Ty);
2208
2209 // If this type fits in an eightbyte, coerce it into the matching integral
2210 // type, which will end up on the stack (with alignment 8).
2211 if (Align == 8 && Size <= 64)
2212 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2213 Size));
2214 }
2215
Chris Lattner44c2b902011-05-22 23:21:23 +00002216 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002217}
2218
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002219/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2220/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002221llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002222 // Wrapper structs/arrays that only contain vectors are passed just like
2223 // vectors; strip them off if present.
2224 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2225 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002226
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002227 llvm::Type *IRType = CGT.ConvertType(Ty);
Benjamin Kramer83b1bf32015-03-02 16:09:24 +00002228 assert(isa<llvm::VectorType>(IRType) &&
2229 "Trying to return a non-vector type in a vector register!");
2230 return IRType;
Chris Lattner4200fe42010-07-29 04:56:46 +00002231}
2232
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002233/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2234/// is known to either be off the end of the specified type or being in
2235/// alignment padding. The user type specified is known to be at most 128 bits
2236/// in size, and have passed through X86_64ABIInfo::classify with a successful
2237/// classification that put one of the two halves in the INTEGER class.
2238///
2239/// It is conservatively correct to return false.
2240static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2241 unsigned EndBit, ASTContext &Context) {
2242 // If the bytes being queried are off the end of the type, there is no user
2243 // data hiding here. This handles analysis of builtins, vectors and other
2244 // types that don't contain interesting padding.
2245 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2246 if (TySize <= StartBit)
2247 return true;
2248
Chris Lattner98076a22010-07-29 07:43:55 +00002249 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2250 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2251 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2252
2253 // Check each element to see if the element overlaps with the queried range.
2254 for (unsigned i = 0; i != NumElts; ++i) {
2255 // If the element is after the span we care about, then we're done..
2256 unsigned EltOffset = i*EltSize;
2257 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002258
Chris Lattner98076a22010-07-29 07:43:55 +00002259 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2260 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2261 EndBit-EltOffset, Context))
2262 return false;
2263 }
2264 // If it overlaps no elements, then it is safe to process as padding.
2265 return true;
2266 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002267
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002268 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2269 const RecordDecl *RD = RT->getDecl();
2270 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002271
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002272 // If this is a C++ record, check the bases first.
2273 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002274 for (const auto &I : CXXRD->bases()) {
2275 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002276 "Unexpected base class!");
2277 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002278 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002279
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002280 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002281 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002282 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002283
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002284 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002285 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002286 EndBit-BaseOffset, Context))
2287 return false;
2288 }
2289 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002290
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002291 // Verify that no field has data that overlaps the region of interest. Yes
2292 // this could be sped up a lot by being smarter about queried fields,
2293 // however we're only looking at structs up to 16 bytes, so we don't care
2294 // much.
2295 unsigned idx = 0;
2296 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2297 i != e; ++i, ++idx) {
2298 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002299
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002300 // If we found a field after the region we care about, then we're done.
2301 if (FieldOffset >= EndBit) break;
2302
2303 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2304 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2305 Context))
2306 return false;
2307 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002308
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002309 // If nothing in this record overlapped the area of interest, then we're
2310 // clean.
2311 return true;
2312 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002313
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002314 return false;
2315}
2316
Chris Lattnere556a712010-07-29 18:39:32 +00002317/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2318/// float member at the specified offset. For example, {int,{float}} has a
2319/// float at offset 4. It is conservatively correct for this routine to return
2320/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002321static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002322 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002323 // Base case if we find a float.
2324 if (IROffset == 0 && IRType->isFloatTy())
2325 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002326
Chris Lattnere556a712010-07-29 18:39:32 +00002327 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002328 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002329 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2330 unsigned Elt = SL->getElementContainingOffset(IROffset);
2331 IROffset -= SL->getElementOffset(Elt);
2332 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2333 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002334
Chris Lattnere556a712010-07-29 18:39:32 +00002335 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002336 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2337 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002338 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2339 IROffset -= IROffset/EltSize*EltSize;
2340 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2341 }
2342
2343 return false;
2344}
2345
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002346
2347/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2348/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002349llvm::Type *X86_64ABIInfo::
2350GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002351 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002352 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002353 // pass as float if the last 4 bytes is just padding. This happens for
2354 // structs that contain 3 floats.
2355 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2356 SourceOffset*8+64, getContext()))
2357 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002358
Chris Lattnere556a712010-07-29 18:39:32 +00002359 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2360 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2361 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002362 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2363 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002364 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002365
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002366 return llvm::Type::getDoubleTy(getVMContext());
2367}
2368
2369
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002370/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2371/// an 8-byte GPR. This means that we either have a scalar or we are talking
2372/// about the high or low part of an up-to-16-byte struct. This routine picks
2373/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002374/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2375/// etc).
2376///
2377/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2378/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2379/// the 8-byte value references. PrefType may be null.
2380///
Alp Toker9907f082014-07-09 14:06:35 +00002381/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002382/// an offset into this that we're processing (which is always either 0 or 8).
2383///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002384llvm::Type *X86_64ABIInfo::
2385GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002386 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002387 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2388 // returning an 8-byte unit starting with it. See if we can safely use it.
2389 if (IROffset == 0) {
2390 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002391 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2392 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002393 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002394
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002395 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2396 // goodness in the source type is just tail padding. This is allowed to
2397 // kick in for struct {double,int} on the int, but not on
2398 // struct{double,int,int} because we wouldn't return the second int. We
2399 // have to do this analysis on the source type because we can't depend on
2400 // unions being lowered a specific way etc.
2401 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002402 IRType->isIntegerTy(32) ||
2403 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2404 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2405 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002406
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002407 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2408 SourceOffset*8+64, getContext()))
2409 return IRType;
2410 }
2411 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002412
Chris Lattner2192fe52011-07-18 04:24:23 +00002413 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002414 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002415 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002416 if (IROffset < SL->getSizeInBytes()) {
2417 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2418 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002419
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002420 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2421 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002422 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002423 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002424
Chris Lattner2192fe52011-07-18 04:24:23 +00002425 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002426 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002427 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002428 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002429 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2430 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002431 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002432
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002433 // Okay, we don't have any better idea of what to pass, so we pass this in an
2434 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002435 unsigned TySizeInBytes =
2436 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002437
Chris Lattner3f763422010-07-29 17:34:39 +00002438 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002439
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002440 // It is always safe to classify this as an integer type up to i64 that
2441 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002442 return llvm::IntegerType::get(getVMContext(),
2443 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002444}
2445
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002446
2447/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2448/// be used as elements of a two register pair to pass or return, return a
2449/// first class aggregate to represent them. For example, if the low part of
2450/// a by-value argument should be passed as i32* and the high part as float,
2451/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002452static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002453GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002454 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002455 // In order to correctly satisfy the ABI, we need to the high part to start
2456 // at offset 8. If the high and low parts we inferred are both 4-byte types
2457 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2458 // the second element at offset 8. Check for this:
2459 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2460 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002461 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002462 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002463
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002464 // To handle this, we have to increase the size of the low part so that the
2465 // second element will start at an 8 byte offset. We can't increase the size
2466 // of the second element because it might make us access off the end of the
2467 // struct.
2468 if (HiStart != 8) {
2469 // There are only two sorts of types the ABI generation code can produce for
2470 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2471 // Promote these to a larger type.
2472 if (Lo->isFloatTy())
2473 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2474 else {
2475 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2476 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2477 }
2478 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002479
Reid Kleckneree7cf842014-12-01 22:02:27 +00002480 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002481
2482
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002483 // Verify that the second element is at an 8-byte offset.
2484 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2485 "Invalid x86-64 argument pair!");
2486 return Result;
2487}
2488
Chris Lattner31faff52010-07-28 23:06:14 +00002489ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002490classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002491 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2492 // classification algorithm.
2493 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002494 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002495
2496 // Check some invariants.
2497 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002498 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2499
Craig Topper8a13c412014-05-21 05:09:00 +00002500 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002501 switch (Lo) {
2502 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002503 if (Hi == NoClass)
2504 return ABIArgInfo::getIgnore();
2505 // If the low part is just padding, it takes no register, leave ResType
2506 // null.
2507 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2508 "Unknown missing lo part");
2509 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002510
2511 case SSEUp:
2512 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002513 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002514
2515 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2516 // hidden argument.
2517 case Memory:
2518 return getIndirectReturnResult(RetTy);
2519
2520 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2521 // available register of the sequence %rax, %rdx is used.
2522 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002523 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002524
Chris Lattner1f3a0632010-07-29 21:42:50 +00002525 // If we have a sign or zero extended integer, make sure to return Extend
2526 // so that the parameter gets the right LLVM IR attributes.
2527 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2528 // Treat an enum type as its underlying type.
2529 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2530 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002531
Chris Lattner1f3a0632010-07-29 21:42:50 +00002532 if (RetTy->isIntegralOrEnumerationType() &&
2533 RetTy->isPromotableIntegerType())
2534 return ABIArgInfo::getExtend();
2535 }
Chris Lattner31faff52010-07-28 23:06:14 +00002536 break;
2537
2538 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2539 // available SSE register of the sequence %xmm0, %xmm1 is used.
2540 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002541 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002542 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002543
2544 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2545 // returned on the X87 stack in %st0 as 80-bit x87 number.
2546 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002547 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002548 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002549
2550 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2551 // part of the value is returned in %st0 and the imaginary part in
2552 // %st1.
2553 case ComplexX87:
2554 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002555 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002556 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002557 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002558 break;
2559 }
2560
Craig Topper8a13c412014-05-21 05:09:00 +00002561 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002562 switch (Hi) {
2563 // Memory was handled previously and X87 should
2564 // never occur as a hi class.
2565 case Memory:
2566 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002567 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002568
2569 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002570 case NoClass:
2571 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002572
Chris Lattner52b3c132010-09-01 00:20:33 +00002573 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002574 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002575 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2576 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002577 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002578 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002579 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002580 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2581 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002582 break;
2583
2584 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002585 // is passed in the next available eightbyte chunk if the last used
2586 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002587 //
Chris Lattner57540c52011-04-15 05:22:18 +00002588 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002589 case SSEUp:
2590 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002591 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002592 break;
2593
2594 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2595 // returned together with the previous X87 value in %st0.
2596 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002597 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002598 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002599 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002600 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002601 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002602 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002603 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2604 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002605 }
Chris Lattner31faff52010-07-28 23:06:14 +00002606 break;
2607 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002608
Chris Lattner52b3c132010-09-01 00:20:33 +00002609 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002610 // known to pass in the high eightbyte of the result. We do this by forming a
2611 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002612 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002613 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002614
Chris Lattner1f3a0632010-07-29 21:42:50 +00002615 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002616}
2617
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002618ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002619 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2620 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002621 const
2622{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002623 Ty = useFirstFieldIfTransparentUnion(Ty);
2624
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002625 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002626 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002627
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002628 // Check some invariants.
2629 // FIXME: Enforce these by construction.
2630 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002631 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2632
2633 neededInt = 0;
2634 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002635 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002636 switch (Lo) {
2637 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002638 if (Hi == NoClass)
2639 return ABIArgInfo::getIgnore();
2640 // If the low part is just padding, it takes no register, leave ResType
2641 // null.
2642 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2643 "Unknown missing lo part");
2644 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002645
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002646 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2647 // on the stack.
2648 case Memory:
2649
2650 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2651 // COMPLEX_X87, it is passed in memory.
2652 case X87:
2653 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002654 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002655 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002656 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002657
2658 case SSEUp:
2659 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002660 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661
2662 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2663 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2664 // and %r9 is used.
2665 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002666 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002667
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002668 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002669 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002670
2671 // If we have a sign or zero extended integer, make sure to return Extend
2672 // so that the parameter gets the right LLVM IR attributes.
2673 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2674 // Treat an enum type as its underlying type.
2675 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2676 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002677
Chris Lattner1f3a0632010-07-29 21:42:50 +00002678 if (Ty->isIntegralOrEnumerationType() &&
2679 Ty->isPromotableIntegerType())
2680 return ABIArgInfo::getExtend();
2681 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002682
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002683 break;
2684
2685 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2686 // available SSE register is used, the registers are taken in the
2687 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002688 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002689 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002690 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002691 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002692 break;
2693 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002694 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002695
Craig Topper8a13c412014-05-21 05:09:00 +00002696 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002697 switch (Hi) {
2698 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002699 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002700 // which is passed in memory.
2701 case Memory:
2702 case X87:
2703 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002704 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002705
2706 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002707
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002708 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002709 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002710 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002711 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002712
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002713 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2714 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002715 break;
2716
2717 // X87Up generally doesn't occur here (long double is passed in
2718 // memory), except in situations involving unions.
2719 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002720 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002721 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002722
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002723 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2724 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002725
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002726 ++neededSSE;
2727 break;
2728
2729 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2730 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002731 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002732 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002733 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002734 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002735 break;
2736 }
2737
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002738 // If a high part was specified, merge it together with the low part. It is
2739 // known to pass in the high eightbyte of the result. We do this by forming a
2740 // first class struct aggregate with the high and low part: {low, high}
2741 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002742 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002743
Chris Lattner1f3a0632010-07-29 21:42:50 +00002744 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002745}
2746
Chris Lattner22326a12010-07-29 02:31:05 +00002747void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002748
Reid Kleckner40ca9132014-05-13 22:05:45 +00002749 if (!getCXXABI().classifyReturnType(FI))
2750 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002751
2752 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002753 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002754
2755 // If the return value is indirect, then the hidden argument is consuming one
2756 // integer register.
2757 if (FI.getReturnInfo().isIndirect())
2758 --freeIntRegs;
2759
Peter Collingbournef7706832014-12-12 23:41:25 +00002760 // The chain argument effectively gives us another free register.
2761 if (FI.isChainCall())
2762 ++freeIntRegs;
2763
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002764 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002765 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2766 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002767 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002768 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002769 it != ie; ++it, ++ArgNo) {
2770 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002771
Bill Wendling9987c0e2010-10-18 23:51:38 +00002772 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002773 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002774 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002775
2776 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2777 // eightbyte of an argument, the whole argument is passed on the
2778 // stack. If registers have already been assigned for some
2779 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002780 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002781 freeIntRegs -= neededInt;
2782 freeSSERegs -= neededSSE;
2783 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002784 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002785 }
2786 }
2787}
2788
2789static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2790 QualType Ty,
2791 CodeGenFunction &CGF) {
David Blaikie2e804282015-04-05 22:47:07 +00002792 llvm::Value *overflow_arg_area_p = CGF.Builder.CreateStructGEP(
2793 nullptr, VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002794 llvm::Value *overflow_arg_area =
2795 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2796
2797 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2798 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002799 // It isn't stated explicitly in the standard, but in practice we use
2800 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002801 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2802 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002803 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002804 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002805 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002806 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2807 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002808 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002809 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002810 overflow_arg_area =
2811 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2812 overflow_arg_area->getType(),
2813 "overflow_arg_area.align");
2814 }
2815
2816 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002817 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002818 llvm::Value *Res =
2819 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002820 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002821
2822 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2823 // l->overflow_arg_area + sizeof(type).
2824 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2825 // an 8 byte boundary.
2826
2827 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002828 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002829 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002830 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2831 "overflow_arg_area.next");
2832 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2833
2834 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2835 return Res;
2836}
2837
2838llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2839 CodeGenFunction &CGF) const {
2840 // Assume that va_list type is correct; should be pointer to LLVM type:
2841 // struct {
2842 // i32 gp_offset;
2843 // i32 fp_offset;
2844 // i8* overflow_arg_area;
2845 // i8* reg_save_area;
2846 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002847 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002848
Chris Lattner9723d6c2010-03-11 18:19:55 +00002849 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002850 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2851 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002852
2853 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2854 // in the registers. If not go to step 7.
2855 if (!neededInt && !neededSSE)
2856 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2857
2858 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2859 // general purpose registers needed to pass type and num_fp to hold
2860 // the number of floating point registers needed.
2861
2862 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2863 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2864 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2865 //
2866 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2867 // register save space).
2868
Craig Topper8a13c412014-05-21 05:09:00 +00002869 llvm::Value *InRegs = nullptr;
2870 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2871 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002872 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002873 gp_offset_p =
2874 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002875 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002876 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2877 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002878 }
2879
2880 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002881 fp_offset_p =
2882 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002883 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2884 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002885 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2886 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002887 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2888 }
2889
2890 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2891 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2892 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2893 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2894
2895 // Emit code to load the value if it was passed in registers.
2896
2897 CGF.EmitBlock(InRegBlock);
2898
2899 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2900 // an offset of l->gp_offset and/or l->fp_offset. This may require
2901 // copying to a temporary location in case the parameter is passed
2902 // in different register classes or requires an alignment greater
2903 // than 8 for general purpose registers and 16 for XMM registers.
2904 //
2905 // FIXME: This really results in shameful code when we end up needing to
2906 // collect arguments from different places; often what should result in a
2907 // simple assembling of a structure from scattered addresses has many more
2908 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002909 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
David Blaikie1ed728c2015-04-05 22:45:47 +00002910 llvm::Value *RegAddr = CGF.Builder.CreateLoad(
2911 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3), "reg_save_area");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002912 if (neededInt && neededSSE) {
2913 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002914 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002915 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002916 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2917 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002918 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002919 llvm::Type *TyLo = ST->getElementType(0);
2920 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002921 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002922 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002923 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2924 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002925 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2926 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002927 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2928 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002929 llvm::Value *V =
2930 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
David Blaikie1ed728c2015-04-05 22:45:47 +00002931 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002932 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
David Blaikie1ed728c2015-04-05 22:45:47 +00002933 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002934
Owen Anderson170229f2009-07-14 23:10:40 +00002935 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002936 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002937 } else if (neededInt) {
2938 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2939 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002940 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002941
2942 // Copy to a temporary if necessary to ensure the appropriate alignment.
2943 std::pair<CharUnits, CharUnits> SizeAlign =
2944 CGF.getContext().getTypeInfoInChars(Ty);
2945 uint64_t TySize = SizeAlign.first.getQuantity();
2946 unsigned TyAlign = SizeAlign.second.getQuantity();
2947 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002948 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2949 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2950 RegAddr = Tmp;
2951 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002952 } else if (neededSSE == 1) {
2953 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2954 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2955 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002956 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002957 assert(neededSSE == 2 && "Invalid number of needed registers!");
2958 // SSE registers are spaced 16 bytes apart in the register save
2959 // area, we need to collect the two eightbytes together.
2960 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002961 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002962 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002963 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002964 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00002965 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002966 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2967 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002968 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2969 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002970 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Chris Lattner0cf24192010-06-28 20:05:43 +00002971 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2972 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002973 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Chris Lattner0cf24192010-06-28 20:05:43 +00002974 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2975 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002976 }
2977
2978 // AMD64-ABI 3.5.7p5: Step 5. Set:
2979 // l->gp_offset = l->gp_offset + num_gp * 8
2980 // l->fp_offset = l->fp_offset + num_fp * 16.
2981 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002982 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002983 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2984 gp_offset_p);
2985 }
2986 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002987 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002988 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2989 fp_offset_p);
2990 }
2991 CGF.EmitBranch(ContBlock);
2992
2993 // Emit code to load the value if it was passed in memory.
2994
2995 CGF.EmitBlock(InMemBlock);
2996 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2997
2998 // Return the appropriate result.
2999
3000 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00003001 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003002 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003003 ResAddr->addIncoming(RegAddr, InRegBlock);
3004 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003005 return ResAddr;
3006}
3007
Reid Kleckner80944df2014-10-31 22:00:51 +00003008ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3009 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003010
3011 if (Ty->isVoidType())
3012 return ABIArgInfo::getIgnore();
3013
3014 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3015 Ty = EnumTy->getDecl()->getIntegerType();
3016
Reid Kleckner80944df2014-10-31 22:00:51 +00003017 TypeInfo Info = getContext().getTypeInfo(Ty);
3018 uint64_t Width = Info.Width;
3019 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003020
Reid Kleckner9005f412014-05-02 00:51:20 +00003021 const RecordType *RT = Ty->getAs<RecordType>();
3022 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003023 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003024 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003025 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3026 }
3027
3028 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003029 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3030
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003031 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003032 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003033 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003034 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003035 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003036
Reid Kleckner80944df2014-10-31 22:00:51 +00003037 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3038 // other targets.
3039 const Type *Base = nullptr;
3040 uint64_t NumElts = 0;
3041 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3042 if (FreeSSERegs >= NumElts) {
3043 FreeSSERegs -= NumElts;
3044 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3045 return ABIArgInfo::getDirect();
3046 return ABIArgInfo::getExpand();
3047 }
3048 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3049 }
3050
3051
Reid Klecknerec87fec2014-05-02 01:17:12 +00003052 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003053 // If the member pointer is represented by an LLVM int or ptr, pass it
3054 // directly.
3055 llvm::Type *LLTy = CGT.ConvertType(Ty);
3056 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3057 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003058 }
3059
Michael Kuperstein4f818702015-02-24 09:35:58 +00003060 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003061 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3062 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003063 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003064 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003065
Reid Kleckner9005f412014-05-02 00:51:20 +00003066 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003067 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003068 }
3069
Julien Lerouge10dcff82014-08-27 00:36:55 +00003070 // Bool type is always extended to the ABI, other builtin types are not
3071 // extended.
3072 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3073 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003074 return ABIArgInfo::getExtend();
3075
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003076 return ABIArgInfo::getDirect();
3077}
3078
3079void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003080 bool IsVectorCall =
3081 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003082
Reid Kleckner80944df2014-10-31 22:00:51 +00003083 // We can use up to 4 SSE return registers with vectorcall.
3084 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3085 if (!getCXXABI().classifyReturnType(FI))
3086 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3087
3088 // We can use up to 6 SSE register parameters with vectorcall.
3089 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003090 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003091 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003092}
3093
Chris Lattner04dc9572010-08-31 16:44:54 +00003094llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3095 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003096 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003097
Chris Lattner04dc9572010-08-31 16:44:54 +00003098 CGBuilderTy &Builder = CGF.Builder;
3099 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3100 "ap");
3101 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3102 llvm::Type *PTy =
3103 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3104 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3105
3106 uint64_t Offset =
3107 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3108 llvm::Value *NextAddr =
3109 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3110 "ap.next");
3111 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3112
3113 return AddrTyped;
3114}
Chris Lattner0cf24192010-06-28 20:05:43 +00003115
John McCallea8d8bb2010-03-11 00:10:12 +00003116// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003117namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003118/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3119class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003120public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003121 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3122
3123 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3124 CodeGenFunction &CGF) const override;
3125};
3126
3127class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3128public:
3129 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003130
Craig Topper4f12f102014-03-12 06:41:41 +00003131 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003132 // This is recovered from gcc output.
3133 return 1; // r1 is the dedicated stack pointer
3134 }
3135
3136 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003137 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003138
3139 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3140 return 16; // Natural alignment for Altivec vectors.
3141 }
John McCallea8d8bb2010-03-11 00:10:12 +00003142};
3143
3144}
3145
Roman Divacky8a12d842014-11-03 18:32:54 +00003146llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3147 QualType Ty,
3148 CodeGenFunction &CGF) const {
3149 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3150 // TODO: Implement this. For now ignore.
3151 (void)CTy;
3152 return nullptr;
3153 }
3154
3155 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3156 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3157 llvm::Type *CharPtr = CGF.Int8PtrTy;
3158 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3159
3160 CGBuilderTy &Builder = CGF.Builder;
3161 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3162 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3163 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3164 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3165 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3166 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3167 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3168 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3169 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3170 // Align GPR when TY is i64.
3171 if (isI64) {
3172 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3173 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3174 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3175 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3176 }
3177 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3178 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3179 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3180 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3181 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3182
3183 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3184 Builder.getInt8(8), "cond");
3185
3186 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3187 Builder.getInt8(isInt ? 4 : 8));
3188
3189 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3190
3191 if (Ty->isFloatingType())
3192 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3193
3194 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3195 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3196 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3197
3198 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3199
3200 CGF.EmitBlock(UsingRegs);
3201
3202 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3203 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3204 // Increase the GPR/FPR indexes.
3205 if (isInt) {
3206 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3207 Builder.CreateStore(GPR, GPRPtr);
3208 } else {
3209 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3210 Builder.CreateStore(FPR, FPRPtr);
3211 }
3212 CGF.EmitBranch(Cont);
3213
3214 CGF.EmitBlock(UsingOverflow);
3215
3216 // Increase the overflow area.
3217 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3218 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3219 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3220 CGF.EmitBranch(Cont);
3221
3222 CGF.EmitBlock(Cont);
3223
3224 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3225 Result->addIncoming(Result1, UsingRegs);
3226 Result->addIncoming(Result2, UsingOverflow);
3227
3228 if (Ty->isAggregateType()) {
3229 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3230 return Builder.CreateLoad(AGGPtr, false, "aggr");
3231 }
3232
3233 return Result;
3234}
3235
John McCallea8d8bb2010-03-11 00:10:12 +00003236bool
3237PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3238 llvm::Value *Address) const {
3239 // This is calculated from the LLVM and GCC tables and verified
3240 // against gcc output. AFAIK all ABIs use the same encoding.
3241
3242 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003243
Chris Lattnerece04092012-02-07 00:39:47 +00003244 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003245 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3246 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3247 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3248
3249 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003250 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003251
3252 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003253 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003254
3255 // 64-76 are various 4-byte special-purpose registers:
3256 // 64: mq
3257 // 65: lr
3258 // 66: ctr
3259 // 67: ap
3260 // 68-75 cr0-7
3261 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003262 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003263
3264 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003265 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003266
3267 // 109: vrsave
3268 // 110: vscr
3269 // 111: spe_acc
3270 // 112: spefscr
3271 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003272 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003273
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003274 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003275}
3276
Roman Divackyd966e722012-05-09 18:22:46 +00003277// PowerPC-64
3278
3279namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003280/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3281class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003282public:
3283 enum ABIKind {
3284 ELFv1 = 0,
3285 ELFv2
3286 };
3287
3288private:
3289 static const unsigned GPRBits = 64;
3290 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003291 bool HasQPX;
3292
3293 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3294 // will be passed in a QPX register.
3295 bool IsQPXVectorTy(const Type *Ty) const {
3296 if (!HasQPX)
3297 return false;
3298
3299 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3300 unsigned NumElements = VT->getNumElements();
3301 if (NumElements == 1)
3302 return false;
3303
3304 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3305 if (getContext().getTypeSize(Ty) <= 256)
3306 return true;
3307 } else if (VT->getElementType()->
3308 isSpecificBuiltinType(BuiltinType::Float)) {
3309 if (getContext().getTypeSize(Ty) <= 128)
3310 return true;
3311 }
3312 }
3313
3314 return false;
3315 }
3316
3317 bool IsQPXVectorTy(QualType Ty) const {
3318 return IsQPXVectorTy(Ty.getTypePtr());
3319 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003320
3321public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003322 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3323 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003324
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003325 bool isPromotableTypeForABI(QualType Ty) const;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003326 bool isAlignedParamType(QualType Ty, bool &Align32) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003327
3328 ABIArgInfo classifyReturnType(QualType RetTy) const;
3329 ABIArgInfo classifyArgumentType(QualType Ty) const;
3330
Reid Klecknere9f6a712014-10-31 17:10:41 +00003331 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3332 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3333 uint64_t Members) const override;
3334
Bill Schmidt84d37792012-10-12 19:26:17 +00003335 // TODO: We can add more logic to computeInfo to improve performance.
3336 // Example: For aggregate arguments that fit in a register, we could
3337 // use getDirectInReg (as is done below for structs containing a single
3338 // floating-point value) to avoid pushing them to memory on function
3339 // entry. This would require changing the logic in PPCISelLowering
3340 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003341 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003342 if (!getCXXABI().classifyReturnType(FI))
3343 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003344 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003345 // We rely on the default argument classification for the most part.
3346 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003347 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003348 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003349 if (T) {
3350 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003351 if (IsQPXVectorTy(T) ||
3352 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003353 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003354 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003355 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003356 continue;
3357 }
3358 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003359 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003360 }
3361 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003362
Craig Topper4f12f102014-03-12 06:41:41 +00003363 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3364 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003365};
3366
3367class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003368 bool HasQPX;
3369
Bill Schmidt25cb3492012-10-03 19:18:57 +00003370public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003371 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003372 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
3373 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)),
3374 HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003375
Craig Topper4f12f102014-03-12 06:41:41 +00003376 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003377 // This is recovered from gcc output.
3378 return 1; // r1 is the dedicated stack pointer
3379 }
3380
3381 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003382 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003383
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003384 unsigned getOpenMPSimdDefaultAlignment(QualType QT) const override {
3385 if (HasQPX)
3386 if (const PointerType *PT = QT->getAs<PointerType>())
3387 if (PT->getPointeeType()->isSpecificBuiltinType(BuiltinType::Double))
3388 return 32; // Natural alignment for QPX doubles.
3389
Hal Finkel92e31a52014-10-03 17:45:20 +00003390 return 16; // Natural alignment for Altivec and VSX vectors.
3391 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003392};
3393
Roman Divackyd966e722012-05-09 18:22:46 +00003394class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3395public:
3396 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3397
Craig Topper4f12f102014-03-12 06:41:41 +00003398 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003399 // This is recovered from gcc output.
3400 return 1; // r1 is the dedicated stack pointer
3401 }
3402
3403 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003404 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003405
3406 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3407 return 16; // Natural alignment for Altivec vectors.
3408 }
Roman Divackyd966e722012-05-09 18:22:46 +00003409};
3410
3411}
3412
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003413// Return true if the ABI requires Ty to be passed sign- or zero-
3414// extended to 64 bits.
3415bool
3416PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3417 // Treat an enum type as its underlying type.
3418 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3419 Ty = EnumTy->getDecl()->getIntegerType();
3420
3421 // Promotable integer types are required to be promoted by the ABI.
3422 if (Ty->isPromotableIntegerType())
3423 return true;
3424
3425 // In addition to the usual promotable integer types, we also need to
3426 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3427 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3428 switch (BT->getKind()) {
3429 case BuiltinType::Int:
3430 case BuiltinType::UInt:
3431 return true;
3432 default:
3433 break;
3434 }
3435
3436 return false;
3437}
3438
Ulrich Weigand581badc2014-07-10 17:20:07 +00003439/// isAlignedParamType - Determine whether a type requires 16-byte
3440/// alignment in the parameter area.
3441bool
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003442PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty, bool &Align32) const {
3443 Align32 = false;
3444
Ulrich Weigand581badc2014-07-10 17:20:07 +00003445 // Complex types are passed just like their elements.
3446 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3447 Ty = CTy->getElementType();
3448
3449 // Only vector types of size 16 bytes need alignment (larger types are
3450 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003451 if (IsQPXVectorTy(Ty)) {
3452 if (getContext().getTypeSize(Ty) > 128)
3453 Align32 = true;
3454
3455 return true;
3456 } else if (Ty->isVectorType()) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003457 return getContext().getTypeSize(Ty) == 128;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003458 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003459
3460 // For single-element float/vector structs, we consider the whole type
3461 // to have the same alignment requirements as its single element.
3462 const Type *AlignAsType = nullptr;
3463 const Type *EltType = isSingleElementStruct(Ty, getContext());
3464 if (EltType) {
3465 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003466 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003467 getContext().getTypeSize(EltType) == 128) ||
3468 (BT && BT->isFloatingPoint()))
3469 AlignAsType = EltType;
3470 }
3471
Ulrich Weigandb7122372014-07-21 00:48:09 +00003472 // Likewise for ELFv2 homogeneous aggregates.
3473 const Type *Base = nullptr;
3474 uint64_t Members = 0;
3475 if (!AlignAsType && Kind == ELFv2 &&
3476 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3477 AlignAsType = Base;
3478
Ulrich Weigand581badc2014-07-10 17:20:07 +00003479 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003480 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3481 if (getContext().getTypeSize(AlignAsType) > 128)
3482 Align32 = true;
3483
3484 return true;
3485 } else if (AlignAsType) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003486 return AlignAsType->isVectorType();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003487 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003488
3489 // Otherwise, we only need alignment for any aggregate type that
3490 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003491 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3492 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
3493 Align32 = true;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003494 return true;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003495 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003496
3497 return false;
3498}
3499
Ulrich Weigandb7122372014-07-21 00:48:09 +00003500/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3501/// aggregate. Base is set to the base element type, and Members is set
3502/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003503bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3504 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003505 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3506 uint64_t NElements = AT->getSize().getZExtValue();
3507 if (NElements == 0)
3508 return false;
3509 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3510 return false;
3511 Members *= NElements;
3512 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3513 const RecordDecl *RD = RT->getDecl();
3514 if (RD->hasFlexibleArrayMember())
3515 return false;
3516
3517 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003518
3519 // If this is a C++ record, check the bases first.
3520 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3521 for (const auto &I : CXXRD->bases()) {
3522 // Ignore empty records.
3523 if (isEmptyRecord(getContext(), I.getType(), true))
3524 continue;
3525
3526 uint64_t FldMembers;
3527 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3528 return false;
3529
3530 Members += FldMembers;
3531 }
3532 }
3533
Ulrich Weigandb7122372014-07-21 00:48:09 +00003534 for (const auto *FD : RD->fields()) {
3535 // Ignore (non-zero arrays of) empty records.
3536 QualType FT = FD->getType();
3537 while (const ConstantArrayType *AT =
3538 getContext().getAsConstantArrayType(FT)) {
3539 if (AT->getSize().getZExtValue() == 0)
3540 return false;
3541 FT = AT->getElementType();
3542 }
3543 if (isEmptyRecord(getContext(), FT, true))
3544 continue;
3545
3546 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3547 if (getContext().getLangOpts().CPlusPlus &&
3548 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3549 continue;
3550
3551 uint64_t FldMembers;
3552 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3553 return false;
3554
3555 Members = (RD->isUnion() ?
3556 std::max(Members, FldMembers) : Members + FldMembers);
3557 }
3558
3559 if (!Base)
3560 return false;
3561
3562 // Ensure there is no padding.
3563 if (getContext().getTypeSize(Base) * Members !=
3564 getContext().getTypeSize(Ty))
3565 return false;
3566 } else {
3567 Members = 1;
3568 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3569 Members = 2;
3570 Ty = CT->getElementType();
3571 }
3572
Reid Klecknere9f6a712014-10-31 17:10:41 +00003573 // Most ABIs only support float, double, and some vector type widths.
3574 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003575 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003576
3577 // The base type must be the same for all members. Types that
3578 // agree in both total size and mode (float vs. vector) are
3579 // treated as being equivalent here.
3580 const Type *TyPtr = Ty.getTypePtr();
3581 if (!Base)
3582 Base = TyPtr;
3583
3584 if (Base->isVectorType() != TyPtr->isVectorType() ||
3585 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3586 return false;
3587 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003588 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3589}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003590
Reid Klecknere9f6a712014-10-31 17:10:41 +00003591bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3592 // Homogeneous aggregates for ELFv2 must have base types of float,
3593 // double, long double, or 128-bit vectors.
3594 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3595 if (BT->getKind() == BuiltinType::Float ||
3596 BT->getKind() == BuiltinType::Double ||
3597 BT->getKind() == BuiltinType::LongDouble)
3598 return true;
3599 }
3600 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003601 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003602 return true;
3603 }
3604 return false;
3605}
3606
3607bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3608 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003609 // Vector types require one register, floating point types require one
3610 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003611 uint32_t NumRegs =
3612 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003613
3614 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003615 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003616}
3617
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003618ABIArgInfo
3619PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003620 Ty = useFirstFieldIfTransparentUnion(Ty);
3621
Bill Schmidt90b22c92012-11-27 02:46:43 +00003622 if (Ty->isAnyComplexType())
3623 return ABIArgInfo::getDirect();
3624
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003625 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3626 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003627 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003628 uint64_t Size = getContext().getTypeSize(Ty);
3629 if (Size > 128)
3630 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3631 else if (Size < 128) {
3632 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3633 return ABIArgInfo::getDirect(CoerceTy);
3634 }
3635 }
3636
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003637 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003638 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003639 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003640
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003641 bool Align32;
3642 uint64_t ABIAlign = isAlignedParamType(Ty, Align32) ?
3643 (Align32 ? 32 : 16) : 8;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003644 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003645
3646 // ELFv2 homogeneous aggregates are passed as array types.
3647 const Type *Base = nullptr;
3648 uint64_t Members = 0;
3649 if (Kind == ELFv2 &&
3650 isHomogeneousAggregate(Ty, Base, Members)) {
3651 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3652 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3653 return ABIArgInfo::getDirect(CoerceTy);
3654 }
3655
Ulrich Weigand601957f2014-07-21 00:56:36 +00003656 // If an aggregate may end up fully in registers, we do not
3657 // use the ByVal method, but pass the aggregate as array.
3658 // This is usually beneficial since we avoid forcing the
3659 // back-end to store the argument to memory.
3660 uint64_t Bits = getContext().getTypeSize(Ty);
3661 if (Bits > 0 && Bits <= 8 * GPRBits) {
3662 llvm::Type *CoerceTy;
3663
3664 // Types up to 8 bytes are passed as integer type (which will be
3665 // properly aligned in the argument save area doubleword).
3666 if (Bits <= GPRBits)
3667 CoerceTy = llvm::IntegerType::get(getVMContext(),
3668 llvm::RoundUpToAlignment(Bits, 8));
3669 // Larger types are passed as arrays, with the base type selected
3670 // according to the required alignment in the save area.
3671 else {
3672 uint64_t RegBits = ABIAlign * 8;
3673 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3674 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3675 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3676 }
3677
3678 return ABIArgInfo::getDirect(CoerceTy);
3679 }
3680
Ulrich Weigandb7122372014-07-21 00:48:09 +00003681 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003682 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3683 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003684 }
3685
3686 return (isPromotableTypeForABI(Ty) ?
3687 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3688}
3689
3690ABIArgInfo
3691PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3692 if (RetTy->isVoidType())
3693 return ABIArgInfo::getIgnore();
3694
Bill Schmidta3d121c2012-12-17 04:20:17 +00003695 if (RetTy->isAnyComplexType())
3696 return ABIArgInfo::getDirect();
3697
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003698 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3699 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003700 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003701 uint64_t Size = getContext().getTypeSize(RetTy);
3702 if (Size > 128)
3703 return ABIArgInfo::getIndirect(0);
3704 else if (Size < 128) {
3705 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3706 return ABIArgInfo::getDirect(CoerceTy);
3707 }
3708 }
3709
Ulrich Weigandb7122372014-07-21 00:48:09 +00003710 if (isAggregateTypeForABI(RetTy)) {
3711 // ELFv2 homogeneous aggregates are returned as array types.
3712 const Type *Base = nullptr;
3713 uint64_t Members = 0;
3714 if (Kind == ELFv2 &&
3715 isHomogeneousAggregate(RetTy, Base, Members)) {
3716 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3717 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3718 return ABIArgInfo::getDirect(CoerceTy);
3719 }
3720
3721 // ELFv2 small aggregates are returned in up to two registers.
3722 uint64_t Bits = getContext().getTypeSize(RetTy);
3723 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3724 if (Bits == 0)
3725 return ABIArgInfo::getIgnore();
3726
3727 llvm::Type *CoerceTy;
3728 if (Bits > GPRBits) {
3729 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003730 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003731 } else
3732 CoerceTy = llvm::IntegerType::get(getVMContext(),
3733 llvm::RoundUpToAlignment(Bits, 8));
3734 return ABIArgInfo::getDirect(CoerceTy);
3735 }
3736
3737 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003738 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003739 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003740
3741 return (isPromotableTypeForABI(RetTy) ?
3742 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3743}
3744
Bill Schmidt25cb3492012-10-03 19:18:57 +00003745// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3746llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3747 QualType Ty,
3748 CodeGenFunction &CGF) const {
3749 llvm::Type *BP = CGF.Int8PtrTy;
3750 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3751
3752 CGBuilderTy &Builder = CGF.Builder;
3753 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3754 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3755
Ulrich Weigand581badc2014-07-10 17:20:07 +00003756 // Handle types that require 16-byte alignment in the parameter save area.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003757 bool Align32;
3758 if (isAlignedParamType(Ty, Align32)) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003759 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003760 AddrAsInt = Builder.CreateAdd(AddrAsInt,
3761 Builder.getInt64(Align32 ? 31 : 15));
3762 AddrAsInt = Builder.CreateAnd(AddrAsInt,
3763 Builder.getInt64(Align32 ? -32 : -16));
Ulrich Weigand581badc2014-07-10 17:20:07 +00003764 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3765 }
3766
Bill Schmidt924c4782013-01-14 17:45:36 +00003767 // Update the va_list pointer. The pointer should be bumped by the
3768 // size of the object. We can trust getTypeSize() except for a complex
3769 // type whose base type is smaller than a doubleword. For these, the
3770 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003771 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003772 QualType BaseTy;
3773 unsigned CplxBaseSize = 0;
3774
3775 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3776 BaseTy = CTy->getElementType();
3777 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3778 if (CplxBaseSize < 8)
3779 SizeInBytes = 16;
3780 }
3781
Bill Schmidt25cb3492012-10-03 19:18:57 +00003782 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3783 llvm::Value *NextAddr =
3784 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3785 "ap.next");
3786 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3787
Bill Schmidt924c4782013-01-14 17:45:36 +00003788 // If we have a complex type and the base type is smaller than 8 bytes,
3789 // the ABI calls for the real and imaginary parts to be right-adjusted
3790 // in separate doublewords. However, Clang expects us to produce a
3791 // pointer to a structure with the two parts packed tightly. So generate
3792 // loads of the real and imaginary parts relative to the va_list pointer,
3793 // and store them to a temporary structure.
3794 if (CplxBaseSize && CplxBaseSize < 8) {
3795 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3796 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003797 if (CGF.CGM.getDataLayout().isBigEndian()) {
3798 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3799 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3800 } else {
3801 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3802 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003803 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3804 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3805 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3806 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3807 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
David Blaikie2e804282015-04-05 22:47:07 +00003808 llvm::AllocaInst *Ptr =
3809 CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), "vacplx");
3810 llvm::Value *RealPtr =
3811 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 0, ".real");
3812 llvm::Value *ImagPtr =
3813 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 1, ".imag");
Bill Schmidt924c4782013-01-14 17:45:36 +00003814 Builder.CreateStore(Real, RealPtr, false);
3815 Builder.CreateStore(Imag, ImagPtr, false);
3816 return Ptr;
3817 }
3818
Bill Schmidt25cb3492012-10-03 19:18:57 +00003819 // If the argument is smaller than 8 bytes, it is right-adjusted in
3820 // its doubleword slot. Adjust the pointer to pick it up from the
3821 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003822 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003823 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3824 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3825 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3826 }
3827
3828 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3829 return Builder.CreateBitCast(Addr, PTy);
3830}
3831
3832static bool
3833PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3834 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003835 // This is calculated from the LLVM and GCC tables and verified
3836 // against gcc output. AFAIK all ABIs use the same encoding.
3837
3838 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3839
3840 llvm::IntegerType *i8 = CGF.Int8Ty;
3841 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3842 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3843 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3844
3845 // 0-31: r0-31, the 8-byte general-purpose registers
3846 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3847
3848 // 32-63: fp0-31, the 8-byte floating-point registers
3849 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3850
3851 // 64-76 are various 4-byte special-purpose registers:
3852 // 64: mq
3853 // 65: lr
3854 // 66: ctr
3855 // 67: ap
3856 // 68-75 cr0-7
3857 // 76: xer
3858 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3859
3860 // 77-108: v0-31, the 16-byte vector registers
3861 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3862
3863 // 109: vrsave
3864 // 110: vscr
3865 // 111: spe_acc
3866 // 112: spefscr
3867 // 113: sfp
3868 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3869
3870 return false;
3871}
John McCallea8d8bb2010-03-11 00:10:12 +00003872
Bill Schmidt25cb3492012-10-03 19:18:57 +00003873bool
3874PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3875 CodeGen::CodeGenFunction &CGF,
3876 llvm::Value *Address) const {
3877
3878 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3879}
3880
3881bool
3882PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3883 llvm::Value *Address) const {
3884
3885 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3886}
3887
Chris Lattner0cf24192010-06-28 20:05:43 +00003888//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003889// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003890//===----------------------------------------------------------------------===//
3891
3892namespace {
3893
Tim Northover573cbee2014-05-24 12:52:07 +00003894class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003895public:
3896 enum ABIKind {
3897 AAPCS = 0,
3898 DarwinPCS
3899 };
3900
3901private:
3902 ABIKind Kind;
3903
3904public:
Tim Northover573cbee2014-05-24 12:52:07 +00003905 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003906
3907private:
3908 ABIKind getABIKind() const { return Kind; }
3909 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3910
3911 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003912 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003913 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3914 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3915 uint64_t Members) const override;
3916
Tim Northovera2ee4332014-03-29 15:09:45 +00003917 bool isIllegalVectorType(QualType Ty) const;
3918
David Blaikie1cbb9712014-11-14 19:09:44 +00003919 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003920 if (!getCXXABI().classifyReturnType(FI))
3921 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003922
Tim Northoverb047bfa2014-11-27 21:02:49 +00003923 for (auto &it : FI.arguments())
3924 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003925 }
3926
3927 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3928 CodeGenFunction &CGF) const;
3929
3930 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3931 CodeGenFunction &CGF) const;
3932
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003933 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3934 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003935 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3936 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3937 }
3938};
3939
Tim Northover573cbee2014-05-24 12:52:07 +00003940class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003941public:
Tim Northover573cbee2014-05-24 12:52:07 +00003942 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3943 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003944
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003945 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003946 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3947 }
3948
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003949 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3950 return 31;
3951 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003952
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003953 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00003954};
3955}
3956
Tim Northoverb047bfa2014-11-27 21:02:49 +00003957ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003958 Ty = useFirstFieldIfTransparentUnion(Ty);
3959
Tim Northovera2ee4332014-03-29 15:09:45 +00003960 // Handle illegal vector types here.
3961 if (isIllegalVectorType(Ty)) {
3962 uint64_t Size = getContext().getTypeSize(Ty);
3963 if (Size <= 32) {
3964 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00003965 return ABIArgInfo::getDirect(ResType);
3966 }
3967 if (Size == 64) {
3968 llvm::Type *ResType =
3969 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00003970 return ABIArgInfo::getDirect(ResType);
3971 }
3972 if (Size == 128) {
3973 llvm::Type *ResType =
3974 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00003975 return ABIArgInfo::getDirect(ResType);
3976 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003977 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3978 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003979
3980 if (!isAggregateTypeForABI(Ty)) {
3981 // Treat an enum type as its underlying type.
3982 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3983 Ty = EnumTy->getDecl()->getIntegerType();
3984
Tim Northovera2ee4332014-03-29 15:09:45 +00003985 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3986 ? ABIArgInfo::getExtend()
3987 : ABIArgInfo::getDirect());
3988 }
3989
3990 // Structures with either a non-trivial destructor or a non-trivial
3991 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003992 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003993 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00003994 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003995 }
3996
3997 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3998 // elsewhere for GNU compatibility.
3999 if (isEmptyRecord(getContext(), Ty, true)) {
4000 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4001 return ABIArgInfo::getIgnore();
4002
Tim Northovera2ee4332014-03-29 15:09:45 +00004003 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4004 }
4005
4006 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004007 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004008 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004009 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004010 return ABIArgInfo::getDirect(
4011 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004012 }
4013
4014 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4015 uint64_t Size = getContext().getTypeSize(Ty);
4016 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004017 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004018 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004019
Tim Northovera2ee4332014-03-29 15:09:45 +00004020 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4021 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004022 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004023 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4024 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4025 }
4026 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4027 }
4028
Tim Northovera2ee4332014-03-29 15:09:45 +00004029 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4030}
4031
Tim Northover573cbee2014-05-24 12:52:07 +00004032ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004033 if (RetTy->isVoidType())
4034 return ABIArgInfo::getIgnore();
4035
4036 // Large vector types should be returned via memory.
4037 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4038 return ABIArgInfo::getIndirect(0);
4039
4040 if (!isAggregateTypeForABI(RetTy)) {
4041 // Treat an enum type as its underlying type.
4042 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4043 RetTy = EnumTy->getDecl()->getIntegerType();
4044
Tim Northover4dab6982014-04-18 13:46:08 +00004045 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4046 ? ABIArgInfo::getExtend()
4047 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004048 }
4049
Tim Northovera2ee4332014-03-29 15:09:45 +00004050 if (isEmptyRecord(getContext(), RetTy, true))
4051 return ABIArgInfo::getIgnore();
4052
Craig Topper8a13c412014-05-21 05:09:00 +00004053 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004054 uint64_t Members = 0;
4055 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004056 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4057 return ABIArgInfo::getDirect();
4058
4059 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4060 uint64_t Size = getContext().getTypeSize(RetTy);
4061 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004062 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004063 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004064
4065 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4066 // For aggregates with 16-byte alignment, we use i128.
4067 if (Alignment < 128 && Size == 128) {
4068 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4069 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4070 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004071 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4072 }
4073
4074 return ABIArgInfo::getIndirect(0);
4075}
4076
Tim Northover573cbee2014-05-24 12:52:07 +00004077/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4078bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004079 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4080 // Check whether VT is legal.
4081 unsigned NumElements = VT->getNumElements();
4082 uint64_t Size = getContext().getTypeSize(VT);
4083 // NumElements should be power of 2 between 1 and 16.
4084 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4085 return true;
4086 return Size != 64 && (Size != 128 || NumElements == 1);
4087 }
4088 return false;
4089}
4090
Reid Klecknere9f6a712014-10-31 17:10:41 +00004091bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4092 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4093 // point type or a short-vector type. This is the same as the 32-bit ABI,
4094 // but with the difference that any floating-point type is allowed,
4095 // including __fp16.
4096 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4097 if (BT->isFloatingPoint())
4098 return true;
4099 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4100 unsigned VecSize = getContext().getTypeSize(VT);
4101 if (VecSize == 64 || VecSize == 128)
4102 return true;
4103 }
4104 return false;
4105}
4106
4107bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4108 uint64_t Members) const {
4109 return Members <= 4;
4110}
4111
Tim Northoverb047bfa2014-11-27 21:02:49 +00004112llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4113 QualType Ty,
4114 CodeGenFunction &CGF) const {
4115 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004116 bool IsIndirect = AI.isIndirect();
4117
Tim Northoverb047bfa2014-11-27 21:02:49 +00004118 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4119 if (IsIndirect)
4120 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4121 else if (AI.getCoerceToType())
4122 BaseTy = AI.getCoerceToType();
4123
4124 unsigned NumRegs = 1;
4125 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4126 BaseTy = ArrTy->getElementType();
4127 NumRegs = ArrTy->getNumElements();
4128 }
4129 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4130
Tim Northovera2ee4332014-03-29 15:09:45 +00004131 // The AArch64 va_list type and handling is specified in the Procedure Call
4132 // Standard, section B.4:
4133 //
4134 // struct {
4135 // void *__stack;
4136 // void *__gr_top;
4137 // void *__vr_top;
4138 // int __gr_offs;
4139 // int __vr_offs;
4140 // };
4141
4142 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4143 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4144 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4145 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4146 auto &Ctx = CGF.getContext();
4147
Craig Topper8a13c412014-05-21 05:09:00 +00004148 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004149 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004150 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4151 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004152 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004153 reg_offs_p =
4154 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004155 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4156 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004157 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004158 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004159 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004160 reg_offs_p =
4161 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004162 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4163 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004164 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004165 }
4166
4167 //=======================================
4168 // Find out where argument was passed
4169 //=======================================
4170
4171 // If reg_offs >= 0 we're already using the stack for this type of
4172 // argument. We don't want to keep updating reg_offs (in case it overflows,
4173 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4174 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004175 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004176 UsingStack = CGF.Builder.CreateICmpSGE(
4177 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4178
4179 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4180
4181 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004182 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004183 CGF.EmitBlock(MaybeRegBlock);
4184
4185 // Integer arguments may need to correct register alignment (for example a
4186 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4187 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004188 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004189 int Align = Ctx.getTypeAlign(Ty) / 8;
4190
4191 reg_offs = CGF.Builder.CreateAdd(
4192 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4193 "align_regoffs");
4194 reg_offs = CGF.Builder.CreateAnd(
4195 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4196 "aligned_regoffs");
4197 }
4198
4199 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004200 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004201 NewOffset = CGF.Builder.CreateAdd(
4202 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4203 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4204
4205 // Now we're in a position to decide whether this argument really was in
4206 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004207 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004208 InRegs = CGF.Builder.CreateICmpSLE(
4209 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4210
4211 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4212
4213 //=======================================
4214 // Argument was in registers
4215 //=======================================
4216
4217 // Now we emit the code for if the argument was originally passed in
4218 // registers. First start the appropriate block:
4219 CGF.EmitBlock(InRegBlock);
4220
Craig Topper8a13c412014-05-21 05:09:00 +00004221 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
David Blaikie2e804282015-04-05 22:47:07 +00004222 reg_top_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, reg_top_index,
4223 "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004224 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4225 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004226 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004227 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4228
4229 if (IsIndirect) {
4230 // If it's been passed indirectly (actually a struct), whatever we find from
4231 // stored registers or on the stack will actually be a struct **.
4232 MemTy = llvm::PointerType::getUnqual(MemTy);
4233 }
4234
Craig Topper8a13c412014-05-21 05:09:00 +00004235 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004236 uint64_t NumMembers = 0;
4237 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004238 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004239 // Homogeneous aggregates passed in registers will have their elements split
4240 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4241 // qN+1, ...). We reload and store into a temporary local variable
4242 // contiguously.
4243 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4244 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4245 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
David Blaikie1ed728c2015-04-05 22:45:47 +00004246 llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(HFATy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004247 int Offset = 0;
4248
4249 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4250 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4251 for (unsigned i = 0; i < NumMembers; ++i) {
4252 llvm::Value *BaseOffset =
4253 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4254 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4255 LoadAddr = CGF.Builder.CreateBitCast(
4256 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
David Blaikie2e804282015-04-05 22:47:07 +00004257 llvm::Value *StoreAddr =
4258 CGF.Builder.CreateStructGEP(Tmp->getAllocatedType(), Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00004259
4260 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4261 CGF.Builder.CreateStore(Elem, StoreAddr);
4262 }
4263
4264 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4265 } else {
4266 // Otherwise the object is contiguous in memory
4267 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004268 if (CGF.CGM.getDataLayout().isBigEndian() &&
4269 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004270 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4271 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4272 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4273
4274 BaseAddr = CGF.Builder.CreateAdd(
4275 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4276
4277 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4278 }
4279
4280 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4281 }
4282
4283 CGF.EmitBranch(ContBlock);
4284
4285 //=======================================
4286 // Argument was on the stack
4287 //=======================================
4288 CGF.EmitBlock(OnStackBlock);
4289
Craig Topper8a13c412014-05-21 05:09:00 +00004290 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
David Blaikie1ed728c2015-04-05 22:45:47 +00004291 stack_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "stack_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004292 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4293
4294 // Again, stack arguments may need realigmnent. In this case both integer and
4295 // floating-point ones might be affected.
4296 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4297 int Align = Ctx.getTypeAlign(Ty) / 8;
4298
4299 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4300
4301 OnStackAddr = CGF.Builder.CreateAdd(
4302 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4303 "align_stack");
4304 OnStackAddr = CGF.Builder.CreateAnd(
4305 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4306 "align_stack");
4307
4308 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4309 }
4310
4311 uint64_t StackSize;
4312 if (IsIndirect)
4313 StackSize = 8;
4314 else
4315 StackSize = Ctx.getTypeSize(Ty) / 8;
4316
4317 // All stack slots are 8 bytes
4318 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4319
4320 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4321 llvm::Value *NewStack =
4322 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4323
4324 // Write the new value of __stack for the next call to va_arg
4325 CGF.Builder.CreateStore(NewStack, stack_p);
4326
4327 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4328 Ctx.getTypeSize(Ty) < 64) {
4329 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4330 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4331
4332 OnStackAddr = CGF.Builder.CreateAdd(
4333 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4334
4335 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4336 }
4337
4338 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4339
4340 CGF.EmitBranch(ContBlock);
4341
4342 //=======================================
4343 // Tidy up
4344 //=======================================
4345 CGF.EmitBlock(ContBlock);
4346
4347 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4348 ResAddr->addIncoming(RegAddr, InRegBlock);
4349 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4350
4351 if (IsIndirect)
4352 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4353
4354 return ResAddr;
4355}
4356
Tim Northover573cbee2014-05-24 12:52:07 +00004357llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004358 CodeGenFunction &CGF) const {
4359 // We do not support va_arg for aggregates or illegal vector types.
4360 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4361 // other cases.
4362 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004363 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004364
4365 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4366 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4367
Craig Topper8a13c412014-05-21 05:09:00 +00004368 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004369 uint64_t Members = 0;
4370 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004371
4372 bool isIndirect = false;
4373 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4374 // be passed indirectly.
4375 if (Size > 16 && !isHA) {
4376 isIndirect = true;
4377 Size = 8;
4378 Align = 8;
4379 }
4380
4381 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4382 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4383
4384 CGBuilderTy &Builder = CGF.Builder;
4385 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4386 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4387
4388 if (isEmptyRecord(getContext(), Ty, true)) {
4389 // These are ignored for parameter passing purposes.
4390 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4391 return Builder.CreateBitCast(Addr, PTy);
4392 }
4393
4394 const uint64_t MinABIAlign = 8;
4395 if (Align > MinABIAlign) {
4396 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4397 Addr = Builder.CreateGEP(Addr, Offset);
4398 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4399 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4400 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4401 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4402 }
4403
4404 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4405 llvm::Value *NextAddr = Builder.CreateGEP(
4406 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4407 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4408
4409 if (isIndirect)
4410 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4411 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4412 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4413
4414 return AddrTyped;
4415}
4416
4417//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004418// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004419//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004420
4421namespace {
4422
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004423class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004424public:
4425 enum ABIKind {
4426 APCS = 0,
4427 AAPCS = 1,
4428 AAPCS_VFP
4429 };
4430
4431private:
4432 ABIKind Kind;
4433
4434public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004435 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004436 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004437 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004438
John McCall3480ef22011-08-30 01:42:09 +00004439 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004440 switch (getTarget().getTriple().getEnvironment()) {
4441 case llvm::Triple::Android:
4442 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004443 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004444 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004445 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004446 return true;
4447 default:
4448 return false;
4449 }
John McCall3480ef22011-08-30 01:42:09 +00004450 }
4451
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004452 bool isEABIHF() const {
4453 switch (getTarget().getTriple().getEnvironment()) {
4454 case llvm::Triple::EABIHF:
4455 case llvm::Triple::GNUEABIHF:
4456 return true;
4457 default:
4458 return false;
4459 }
4460 }
4461
Daniel Dunbar020daa92009-09-12 01:00:39 +00004462 ABIKind getABIKind() const { return Kind; }
4463
Tim Northovera484bc02013-10-01 14:34:25 +00004464private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004465 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004466 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004467 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004468
Reid Klecknere9f6a712014-10-31 17:10:41 +00004469 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4470 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4471 uint64_t Members) const override;
4472
Craig Topper4f12f102014-03-12 06:41:41 +00004473 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004474
Craig Topper4f12f102014-03-12 06:41:41 +00004475 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4476 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004477
4478 llvm::CallingConv::ID getLLVMDefaultCC() const;
4479 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004480 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004481};
4482
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004483class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4484public:
Chris Lattner2b037972010-07-29 02:01:43 +00004485 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4486 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004487
John McCall3480ef22011-08-30 01:42:09 +00004488 const ARMABIInfo &getABIInfo() const {
4489 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4490 }
4491
Craig Topper4f12f102014-03-12 06:41:41 +00004492 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004493 return 13;
4494 }
Roman Divackyc1617352011-05-18 19:36:54 +00004495
Craig Topper4f12f102014-03-12 06:41:41 +00004496 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004497 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4498 }
4499
Roman Divackyc1617352011-05-18 19:36:54 +00004500 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004501 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004502 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004503
4504 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004505 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004506 return false;
4507 }
John McCall3480ef22011-08-30 01:42:09 +00004508
Craig Topper4f12f102014-03-12 06:41:41 +00004509 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004510 if (getABIInfo().isEABI()) return 88;
4511 return TargetCodeGenInfo::getSizeOfUnwindException();
4512 }
Tim Northovera484bc02013-10-01 14:34:25 +00004513
4514 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004515 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004516 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4517 if (!FD)
4518 return;
4519
4520 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4521 if (!Attr)
4522 return;
4523
4524 const char *Kind;
4525 switch (Attr->getInterrupt()) {
4526 case ARMInterruptAttr::Generic: Kind = ""; break;
4527 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4528 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4529 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4530 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4531 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4532 }
4533
4534 llvm::Function *Fn = cast<llvm::Function>(GV);
4535
4536 Fn->addFnAttr("interrupt", Kind);
4537
4538 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4539 return;
4540
4541 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4542 // however this is not necessarily true on taking any interrupt. Instruct
4543 // the backend to perform a realignment as part of the function prologue.
4544 llvm::AttrBuilder B;
4545 B.addStackAlignmentAttr(8);
4546 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4547 llvm::AttributeSet::get(CGM.getLLVMContext(),
4548 llvm::AttributeSet::FunctionIndex,
4549 B));
4550 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004551};
4552
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004553class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4554 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4555 CodeGen::CodeGenModule &CGM) const;
4556
4557public:
4558 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4559 : ARMTargetCodeGenInfo(CGT, K) {}
4560
4561 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4562 CodeGen::CodeGenModule &CGM) const override;
4563};
4564
4565void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4566 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4567 if (!isa<FunctionDecl>(D))
4568 return;
4569 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4570 return;
4571
4572 llvm::Function *F = cast<llvm::Function>(GV);
4573 F->addFnAttr("stack-probe-size",
4574 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4575}
4576
4577void WindowsARMTargetCodeGenInfo::SetTargetAttributes(
4578 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4579 ARMTargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
4580 addStackProbeSizeTargetAttribute(D, GV, CGM);
4581}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004582}
4583
Chris Lattner22326a12010-07-29 02:31:05 +00004584void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004585 if (!getCXXABI().classifyReturnType(FI))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004586 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004587
Tim Northoverbc784d12015-02-24 17:22:40 +00004588 for (auto &I : FI.arguments())
4589 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004590
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004591 // Always honor user-specified calling convention.
4592 if (FI.getCallingConvention() != llvm::CallingConv::C)
4593 return;
4594
John McCall882987f2013-02-28 19:01:20 +00004595 llvm::CallingConv::ID cc = getRuntimeCC();
4596 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004597 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004598}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004599
John McCall882987f2013-02-28 19:01:20 +00004600/// Return the default calling convention that LLVM will use.
4601llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4602 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004603 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004604 return llvm::CallingConv::ARM_AAPCS_VFP;
4605 else if (isEABI())
4606 return llvm::CallingConv::ARM_AAPCS;
4607 else
4608 return llvm::CallingConv::ARM_APCS;
4609}
4610
4611/// Return the calling convention that our ABI would like us to use
4612/// as the C calling convention.
4613llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004614 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004615 case APCS: return llvm::CallingConv::ARM_APCS;
4616 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4617 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004618 }
John McCall882987f2013-02-28 19:01:20 +00004619 llvm_unreachable("bad ABI kind");
4620}
4621
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004622void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004623 assert(getRuntimeCC() == llvm::CallingConv::C);
4624
4625 // Don't muddy up the IR with a ton of explicit annotations if
4626 // they'd just match what LLVM will infer from the triple.
4627 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4628 if (abiCC != getLLVMDefaultCC())
4629 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004630
4631 BuiltinCC = (getABIKind() == APCS ?
4632 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004633}
4634
Tim Northoverbc784d12015-02-24 17:22:40 +00004635ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4636 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004637 // 6.1.2.1 The following argument types are VFP CPRCs:
4638 // A single-precision floating-point type (including promoted
4639 // half-precision types); A double-precision floating-point type;
4640 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4641 // with a Base Type of a single- or double-precision floating-point type,
4642 // 64-bit containerized vectors or 128-bit containerized vectors with one
4643 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004644 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004645
Reid Klecknerb1be6832014-11-15 01:41:41 +00004646 Ty = useFirstFieldIfTransparentUnion(Ty);
4647
Manman Renfef9e312012-10-16 19:18:39 +00004648 // Handle illegal vector types here.
4649 if (isIllegalVectorType(Ty)) {
4650 uint64_t Size = getContext().getTypeSize(Ty);
4651 if (Size <= 32) {
4652 llvm::Type *ResType =
4653 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004654 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004655 }
4656 if (Size == 64) {
4657 llvm::Type *ResType = llvm::VectorType::get(
4658 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004659 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004660 }
4661 if (Size == 128) {
4662 llvm::Type *ResType = llvm::VectorType::get(
4663 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004664 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004665 }
4666 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4667 }
4668
John McCalla1dee5302010-08-22 10:59:02 +00004669 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004670 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004671 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004672 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004673 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004674
Tim Northover5a1558e2014-11-07 22:30:50 +00004675 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4676 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004677 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004678
Oliver Stannard405bded2014-02-11 09:25:50 +00004679 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northover1060eae2013-06-21 22:49:34 +00004680 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004681 }
Tim Northover1060eae2013-06-21 22:49:34 +00004682
Daniel Dunbar09d33622009-09-14 21:54:03 +00004683 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004684 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004685 return ABIArgInfo::getIgnore();
4686
Tim Northover5a1558e2014-11-07 22:30:50 +00004687 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004688 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4689 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004690 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004691 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004692 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004693 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004694 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004695 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004696 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004697 }
4698
Manman Ren6c30e132012-08-13 21:23:55 +00004699 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004700 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4701 // most 8-byte. We realign the indirect argument if type alignment is bigger
4702 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004703 uint64_t ABIAlign = 4;
4704 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4705 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004706 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004707 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004708
Manman Ren8cd99812012-11-06 04:58:01 +00004709 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northoverd157e192015-03-09 21:40:42 +00004710 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004711 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004712 }
4713
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004714 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004715 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004716 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004717 // FIXME: Try to match the types of the arguments more accurately where
4718 // we can.
4719 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004720 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4721 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004722 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004723 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4724 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004725 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004726
Tim Northover5a1558e2014-11-07 22:30:50 +00004727 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004728}
4729
Chris Lattner458b2aa2010-07-29 02:16:43 +00004730static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004731 llvm::LLVMContext &VMContext) {
4732 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4733 // is called integer-like if its size is less than or equal to one word, and
4734 // the offset of each of its addressable sub-fields is zero.
4735
4736 uint64_t Size = Context.getTypeSize(Ty);
4737
4738 // Check that the type fits in a word.
4739 if (Size > 32)
4740 return false;
4741
4742 // FIXME: Handle vector types!
4743 if (Ty->isVectorType())
4744 return false;
4745
Daniel Dunbard53bac72009-09-14 02:20:34 +00004746 // Float types are never treated as "integer like".
4747 if (Ty->isRealFloatingType())
4748 return false;
4749
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004750 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004751 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004752 return true;
4753
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004754 // Small complex integer types are "integer like".
4755 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4756 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004757
4758 // Single element and zero sized arrays should be allowed, by the definition
4759 // above, but they are not.
4760
4761 // Otherwise, it must be a record type.
4762 const RecordType *RT = Ty->getAs<RecordType>();
4763 if (!RT) return false;
4764
4765 // Ignore records with flexible arrays.
4766 const RecordDecl *RD = RT->getDecl();
4767 if (RD->hasFlexibleArrayMember())
4768 return false;
4769
4770 // Check that all sub-fields are at offset 0, and are themselves "integer
4771 // like".
4772 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4773
4774 bool HadField = false;
4775 unsigned idx = 0;
4776 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4777 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004778 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004779
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004780 // Bit-fields are not addressable, we only need to verify they are "integer
4781 // like". We still have to disallow a subsequent non-bitfield, for example:
4782 // struct { int : 0; int x }
4783 // is non-integer like according to gcc.
4784 if (FD->isBitField()) {
4785 if (!RD->isUnion())
4786 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004787
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004788 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4789 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004790
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004791 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004792 }
4793
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004794 // Check if this field is at offset 0.
4795 if (Layout.getFieldOffset(idx) != 0)
4796 return false;
4797
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004798 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4799 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004800
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004801 // Only allow at most one field in a structure. This doesn't match the
4802 // wording above, but follows gcc in situations with a field following an
4803 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004804 if (!RD->isUnion()) {
4805 if (HadField)
4806 return false;
4807
4808 HadField = true;
4809 }
4810 }
4811
4812 return true;
4813}
4814
Oliver Stannard405bded2014-02-11 09:25:50 +00004815ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4816 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004817 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004818
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004819 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004820 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004821
Daniel Dunbar19964db2010-09-23 01:54:32 +00004822 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004823 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbar19964db2010-09-23 01:54:32 +00004824 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004825 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004826
John McCalla1dee5302010-08-22 10:59:02 +00004827 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004828 // Treat an enum type as its underlying type.
4829 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4830 RetTy = EnumTy->getDecl()->getIntegerType();
4831
Tim Northover5a1558e2014-11-07 22:30:50 +00004832 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4833 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004834 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004835
4836 // Are we following APCS?
4837 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004838 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004839 return ABIArgInfo::getIgnore();
4840
Daniel Dunbareedf1512010-02-01 23:31:19 +00004841 // Complex types are all returned as packed integers.
4842 //
4843 // FIXME: Consider using 2 x vector types if the back end handles them
4844 // correctly.
4845 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004846 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4847 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004848
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004849 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004850 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004851 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004852 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004853 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004854 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004855 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004856 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4857 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004858 }
4859
4860 // Otherwise return in memory.
4861 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004862 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004863
4864 // Otherwise this is an AAPCS variant.
4865
Chris Lattner458b2aa2010-07-29 02:16:43 +00004866 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004867 return ABIArgInfo::getIgnore();
4868
Bob Wilson1d9269a2011-11-02 04:51:36 +00004869 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004870 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004871 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004872 uint64_t Members;
4873 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004874 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004875 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004876 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004877 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004878 }
4879
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004880 // Aggregates <= 4 bytes are returned in r0; other aggregates
4881 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004882 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004883 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004884 if (getDataLayout().isBigEndian())
4885 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004886 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004887
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004888 // Return in the smallest viable integer type.
4889 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004890 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004891 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004892 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4893 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004894 }
4895
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004896 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004897}
4898
Manman Renfef9e312012-10-16 19:18:39 +00004899/// isIllegalVector - check whether Ty is an illegal vector type.
4900bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4901 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4902 // Check whether VT is legal.
4903 unsigned NumElements = VT->getNumElements();
4904 uint64_t Size = getContext().getTypeSize(VT);
4905 // NumElements should be power of 2.
4906 if ((NumElements & (NumElements - 1)) != 0)
4907 return true;
4908 // Size should be greater than 32 bits.
4909 return Size <= 32;
4910 }
4911 return false;
4912}
4913
Reid Klecknere9f6a712014-10-31 17:10:41 +00004914bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4915 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4916 // double, or 64-bit or 128-bit vectors.
4917 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4918 if (BT->getKind() == BuiltinType::Float ||
4919 BT->getKind() == BuiltinType::Double ||
4920 BT->getKind() == BuiltinType::LongDouble)
4921 return true;
4922 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4923 unsigned VecSize = getContext().getTypeSize(VT);
4924 if (VecSize == 64 || VecSize == 128)
4925 return true;
4926 }
4927 return false;
4928}
4929
4930bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4931 uint64_t Members) const {
4932 return Members <= 4;
4933}
4934
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004935llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004936 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004937 llvm::Type *BP = CGF.Int8PtrTy;
4938 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004939
4940 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004941 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004942 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004943
Tim Northover1711cc92013-06-21 23:05:33 +00004944 if (isEmptyRecord(getContext(), Ty, true)) {
4945 // These are ignored for parameter passing purposes.
4946 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4947 return Builder.CreateBitCast(Addr, PTy);
4948 }
4949
Manman Rencca54d02012-10-16 19:01:37 +00004950 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004951 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004952 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004953
4954 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4955 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004956 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4957 getABIKind() == ARMABIInfo::AAPCS)
4958 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4959 else
4960 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004961 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4962 if (isIllegalVectorType(Ty) && Size > 16) {
4963 IsIndirect = true;
4964 Size = 4;
4965 TyAlign = 4;
4966 }
Manman Rencca54d02012-10-16 19:01:37 +00004967
4968 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004969 if (TyAlign > 4) {
4970 assert((TyAlign & (TyAlign - 1)) == 0 &&
4971 "Alignment is not power of 2!");
4972 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4973 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4974 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004975 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004976 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004977
4978 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004979 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004980 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004981 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004982 "ap.next");
4983 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4984
Manman Renfef9e312012-10-16 19:18:39 +00004985 if (IsIndirect)
4986 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004987 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004988 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4989 // may not be correctly aligned for the vector type. We create an aligned
4990 // temporary space and copy the content over from ap.cur to the temporary
4991 // space. This is necessary if the natural alignment of the type is greater
4992 // than the ABI alignment.
4993 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4994 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4995 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4996 "var.align");
4997 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4998 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4999 Builder.CreateMemCpy(Dst, Src,
5000 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5001 TyAlign, false);
5002 Addr = AlignedTemp; //The content is in aligned location.
5003 }
5004 llvm::Type *PTy =
5005 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5006 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5007
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005008 return AddrTyped;
5009}
5010
Chris Lattner0cf24192010-06-28 20:05:43 +00005011//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005012// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005013//===----------------------------------------------------------------------===//
5014
5015namespace {
5016
Justin Holewinski83e96682012-05-24 17:43:12 +00005017class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005018public:
Justin Holewinski36837432013-03-30 14:38:24 +00005019 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005020
5021 ABIArgInfo classifyReturnType(QualType RetTy) const;
5022 ABIArgInfo classifyArgumentType(QualType Ty) const;
5023
Craig Topper4f12f102014-03-12 06:41:41 +00005024 void computeInfo(CGFunctionInfo &FI) const override;
5025 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5026 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005027};
5028
Justin Holewinski83e96682012-05-24 17:43:12 +00005029class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005030public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005031 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5032 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005033
5034 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5035 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005036private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005037 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5038 // resulting MDNode to the nvvm.annotations MDNode.
5039 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005040};
5041
Justin Holewinski83e96682012-05-24 17:43:12 +00005042ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005043 if (RetTy->isVoidType())
5044 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005045
5046 // note: this is different from default ABI
5047 if (!RetTy->isScalarType())
5048 return ABIArgInfo::getDirect();
5049
5050 // Treat an enum type as its underlying type.
5051 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5052 RetTy = EnumTy->getDecl()->getIntegerType();
5053
5054 return (RetTy->isPromotableIntegerType() ?
5055 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005056}
5057
Justin Holewinski83e96682012-05-24 17:43:12 +00005058ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005059 // Treat an enum type as its underlying type.
5060 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5061 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005062
Eli Bendersky95338a02014-10-29 13:43:21 +00005063 // Return aggregates type as indirect by value
5064 if (isAggregateTypeForABI(Ty))
5065 return ABIArgInfo::getIndirect(0, /* byval */ true);
5066
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005067 return (Ty->isPromotableIntegerType() ?
5068 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005069}
5070
Justin Holewinski83e96682012-05-24 17:43:12 +00005071void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005072 if (!getCXXABI().classifyReturnType(FI))
5073 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005074 for (auto &I : FI.arguments())
5075 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005076
5077 // Always honor user-specified calling convention.
5078 if (FI.getCallingConvention() != llvm::CallingConv::C)
5079 return;
5080
John McCall882987f2013-02-28 19:01:20 +00005081 FI.setEffectiveCallingConvention(getRuntimeCC());
5082}
5083
Justin Holewinski83e96682012-05-24 17:43:12 +00005084llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5085 CodeGenFunction &CFG) const {
5086 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005087}
5088
Justin Holewinski83e96682012-05-24 17:43:12 +00005089void NVPTXTargetCodeGenInfo::
5090SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5091 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005092 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5093 if (!FD) return;
5094
5095 llvm::Function *F = cast<llvm::Function>(GV);
5096
5097 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005098 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005099 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005100 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005101 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005102 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005103 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5104 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005105 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005106 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005107 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005108 }
Justin Holewinski38031972011-10-05 17:58:44 +00005109
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005110 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005111 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005112 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005113 // __global__ functions cannot be called from the device, we do not
5114 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005115 if (FD->hasAttr<CUDAGlobalAttr>()) {
5116 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5117 addNVVMMetadata(F, "kernel", 1);
5118 }
Artem Belevich7093e402015-04-21 22:55:54 +00005119 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005120 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005121 llvm::APSInt MaxThreads(32);
5122 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5123 if (MaxThreads > 0)
5124 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5125
5126 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5127 // not specified in __launch_bounds__ or if the user specified a 0 value,
5128 // we don't have to add a PTX directive.
5129 if (Attr->getMinBlocks()) {
5130 llvm::APSInt MinBlocks(32);
5131 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5132 if (MinBlocks > 0)
5133 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5134 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005135 }
5136 }
Justin Holewinski38031972011-10-05 17:58:44 +00005137 }
5138}
5139
Eli Benderskye06a2c42014-04-15 16:57:05 +00005140void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5141 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005142 llvm::Module *M = F->getParent();
5143 llvm::LLVMContext &Ctx = M->getContext();
5144
5145 // Get "nvvm.annotations" metadata node
5146 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5147
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005148 llvm::Metadata *MDVals[] = {
5149 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5150 llvm::ConstantAsMetadata::get(
5151 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005152 // Append metadata to nvvm.annotations
5153 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5154}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005155}
5156
5157//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005158// SystemZ ABI Implementation
5159//===----------------------------------------------------------------------===//
5160
5161namespace {
5162
5163class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005164 bool HasVector;
5165
Ulrich Weigand47445072013-05-06 16:26:41 +00005166public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005167 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5168 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005169
5170 bool isPromotableIntegerType(QualType Ty) const;
5171 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005172 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005173 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005174 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005175
5176 ABIArgInfo classifyReturnType(QualType RetTy) const;
5177 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5178
Craig Topper4f12f102014-03-12 06:41:41 +00005179 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005180 if (!getCXXABI().classifyReturnType(FI))
5181 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005182 for (auto &I : FI.arguments())
5183 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005184 }
5185
Craig Topper4f12f102014-03-12 06:41:41 +00005186 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5187 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005188};
5189
5190class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5191public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005192 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5193 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005194};
5195
5196}
5197
5198bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5199 // Treat an enum type as its underlying type.
5200 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5201 Ty = EnumTy->getDecl()->getIntegerType();
5202
5203 // Promotable integer types are required to be promoted by the ABI.
5204 if (Ty->isPromotableIntegerType())
5205 return true;
5206
5207 // 32-bit values must also be promoted.
5208 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5209 switch (BT->getKind()) {
5210 case BuiltinType::Int:
5211 case BuiltinType::UInt:
5212 return true;
5213 default:
5214 return false;
5215 }
5216 return false;
5217}
5218
5219bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005220 return (Ty->isAnyComplexType() ||
5221 Ty->isVectorType() ||
5222 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005223}
5224
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005225bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5226 return (HasVector &&
5227 Ty->isVectorType() &&
5228 getContext().getTypeSize(Ty) <= 128);
5229}
5230
Ulrich Weigand47445072013-05-06 16:26:41 +00005231bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5232 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5233 switch (BT->getKind()) {
5234 case BuiltinType::Float:
5235 case BuiltinType::Double:
5236 return true;
5237 default:
5238 return false;
5239 }
5240
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005241 return false;
5242}
5243
5244QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005245 if (const RecordType *RT = Ty->getAsStructureType()) {
5246 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005247 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005248
5249 // If this is a C++ record, check the bases first.
5250 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005251 for (const auto &I : CXXRD->bases()) {
5252 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005253
5254 // Empty bases don't affect things either way.
5255 if (isEmptyRecord(getContext(), Base, true))
5256 continue;
5257
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005258 if (!Found.isNull())
5259 return Ty;
5260 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005261 }
5262
5263 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005264 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005265 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005266 // Unlike isSingleElementStruct(), empty structure and array fields
5267 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005268 if (getContext().getLangOpts().CPlusPlus &&
5269 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5270 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005271
5272 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005273 // Nested structures still do though.
5274 if (!Found.isNull())
5275 return Ty;
5276 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005277 }
5278
5279 // Unlike isSingleElementStruct(), trailing padding is allowed.
5280 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005281 if (!Found.isNull())
5282 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005283 }
5284
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005285 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005286}
5287
5288llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5289 CodeGenFunction &CGF) const {
5290 // Assume that va_list type is correct; should be pointer to LLVM type:
5291 // struct {
5292 // i64 __gpr;
5293 // i64 __fpr;
5294 // i8 *__overflow_arg_area;
5295 // i8 *__reg_save_area;
5296 // };
5297
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005298 // Every non-vector argument occupies 8 bytes and is passed by preference
5299 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5300 // always passed on the stack.
Ulrich Weigand47445072013-05-06 16:26:41 +00005301 Ty = CGF.getContext().getCanonicalType(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005302 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
5303 llvm::Type *APTy = llvm::PointerType::getUnqual(ArgTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005304 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005305 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005306 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005307 bool IsVector = false;
Ulrich Weigand47445072013-05-06 16:26:41 +00005308 unsigned UnpaddedBitSize;
5309 if (IsIndirect) {
5310 APTy = llvm::PointerType::getUnqual(APTy);
5311 UnpaddedBitSize = 64;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005312 } else {
5313 if (AI.getCoerceToType())
5314 ArgTy = AI.getCoerceToType();
5315 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005316 IsVector = ArgTy->isVectorTy();
Ulrich Weigand47445072013-05-06 16:26:41 +00005317 UnpaddedBitSize = getContext().getTypeSize(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005318 }
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005319 unsigned PaddedBitSize = (IsVector && UnpaddedBitSize > 64) ? 128 : 64;
Ulrich Weigand47445072013-05-06 16:26:41 +00005320 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5321
5322 unsigned PaddedSize = PaddedBitSize / 8;
5323 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5324
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005325 llvm::Type *IndexTy = CGF.Int64Ty;
5326 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5327
5328 if (IsVector) {
5329 // Work out the address of a vector argument on the stack.
5330 // Vector arguments are always passed in the high bits of a
5331 // single (8 byte) or double (16 byte) stack slot.
5332 llvm::Value *OverflowArgAreaPtr =
5333 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 2,
5334 "overflow_arg_area_ptr");
5335 llvm::Value *OverflowArgArea =
5336 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5337 llvm::Value *MemAddr =
5338 CGF.Builder.CreateBitCast(OverflowArgArea, APTy, "mem_addr");
5339
5340 // Update overflow_arg_area_ptr pointer
5341 llvm::Value *NewOverflowArgArea =
5342 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5343 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5344
5345 return MemAddr;
5346 }
5347
Ulrich Weigand47445072013-05-06 16:26:41 +00005348 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5349 if (InFPRs) {
5350 MaxRegs = 4; // Maximum of 4 FPR arguments
5351 RegCountField = 1; // __fpr
5352 RegSaveIndex = 16; // save offset for f0
5353 RegPadding = 0; // floats are passed in the high bits of an FPR
5354 } else {
5355 MaxRegs = 5; // Maximum of 5 GPR arguments
5356 RegCountField = 0; // __gpr
5357 RegSaveIndex = 2; // save offset for r2
5358 RegPadding = Padding; // values are passed in the low bits of a GPR
5359 }
5360
David Blaikie2e804282015-04-05 22:47:07 +00005361 llvm::Value *RegCountPtr = CGF.Builder.CreateStructGEP(
5362 nullptr, VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005363 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005364 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5365 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005366 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005367
5368 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5369 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5370 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5371 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5372
5373 // Emit code to load the value if it was passed in registers.
5374 CGF.EmitBlock(InRegBlock);
5375
5376 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005377 llvm::Value *ScaledRegCount =
5378 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5379 llvm::Value *RegBase =
5380 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5381 llvm::Value *RegOffset =
5382 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5383 llvm::Value *RegSaveAreaPtr =
David Blaikie2e804282015-04-05 22:47:07 +00005384 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005385 llvm::Value *RegSaveArea =
5386 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5387 llvm::Value *RawRegAddr =
5388 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5389 llvm::Value *RegAddr =
5390 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5391
5392 // Update the register count
5393 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5394 llvm::Value *NewRegCount =
5395 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5396 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5397 CGF.EmitBranch(ContBlock);
5398
5399 // Emit code to load the value if it was passed in memory.
5400 CGF.EmitBlock(InMemBlock);
5401
5402 // Work out the address of a stack argument.
David Blaikie2e804282015-04-05 22:47:07 +00005403 llvm::Value *OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5404 nullptr, VAListAddr, 2, "overflow_arg_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005405 llvm::Value *OverflowArgArea =
5406 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5407 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5408 llvm::Value *RawMemAddr =
5409 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5410 llvm::Value *MemAddr =
5411 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5412
5413 // Update overflow_arg_area_ptr pointer
5414 llvm::Value *NewOverflowArgArea =
5415 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5416 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5417 CGF.EmitBranch(ContBlock);
5418
5419 // Return the appropriate result.
5420 CGF.EmitBlock(ContBlock);
5421 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5422 ResAddr->addIncoming(RegAddr, InRegBlock);
5423 ResAddr->addIncoming(MemAddr, InMemBlock);
5424
5425 if (IsIndirect)
5426 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5427
5428 return ResAddr;
5429}
5430
Ulrich Weigand47445072013-05-06 16:26:41 +00005431ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5432 if (RetTy->isVoidType())
5433 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005434 if (isVectorArgumentType(RetTy))
5435 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005436 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5437 return ABIArgInfo::getIndirect(0);
5438 return (isPromotableIntegerType(RetTy) ?
5439 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5440}
5441
5442ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5443 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005444 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005445 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5446
5447 // Integers and enums are extended to full register width.
5448 if (isPromotableIntegerType(Ty))
5449 return ABIArgInfo::getExtend();
5450
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005451 // Handle vector types and vector-like structure types. Note that
5452 // as opposed to float-like structure types, we do not allow any
5453 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005454 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005455 QualType SingleElementTy = GetSingleElementType(Ty);
5456 if (isVectorArgumentType(SingleElementTy) &&
5457 getContext().getTypeSize(SingleElementTy) == Size)
5458 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5459
5460 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005461 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005462 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005463
5464 // Handle small structures.
5465 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5466 // Structures with flexible arrays have variable length, so really
5467 // fail the size test above.
5468 const RecordDecl *RD = RT->getDecl();
5469 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005470 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005471
5472 // The structure is passed as an unextended integer, a float, or a double.
5473 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005474 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005475 assert(Size == 32 || Size == 64);
5476 if (Size == 32)
5477 PassTy = llvm::Type::getFloatTy(getVMContext());
5478 else
5479 PassTy = llvm::Type::getDoubleTy(getVMContext());
5480 } else
5481 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5482 return ABIArgInfo::getDirect(PassTy);
5483 }
5484
5485 // Non-structure compounds are passed indirectly.
5486 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005487 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005488
Craig Topper8a13c412014-05-21 05:09:00 +00005489 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005490}
5491
5492//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005493// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005494//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005495
5496namespace {
5497
5498class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5499public:
Chris Lattner2b037972010-07-29 02:01:43 +00005500 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5501 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005502 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005503 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005504};
5505
5506}
5507
5508void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5509 llvm::GlobalValue *GV,
5510 CodeGen::CodeGenModule &M) const {
5511 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5512 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5513 // Handle 'interrupt' attribute:
5514 llvm::Function *F = cast<llvm::Function>(GV);
5515
5516 // Step 1: Set ISR calling convention.
5517 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5518
5519 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005520 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005521
5522 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005523 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005524 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5525 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005526 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005527 }
5528}
5529
Chris Lattner0cf24192010-06-28 20:05:43 +00005530//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005531// MIPS ABI Implementation. This works for both little-endian and
5532// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005533//===----------------------------------------------------------------------===//
5534
John McCall943fae92010-05-27 06:19:26 +00005535namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005536class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005537 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005538 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5539 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005540 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005541 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005542 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005543 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005544public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005545 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005546 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005547 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005548
5549 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005550 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005551 void computeInfo(CGFunctionInfo &FI) const override;
5552 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5553 CodeGenFunction &CGF) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005554 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005555};
5556
John McCall943fae92010-05-27 06:19:26 +00005557class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005558 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005559public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005560 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5561 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005562 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005563
Craig Topper4f12f102014-03-12 06:41:41 +00005564 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005565 return 29;
5566 }
5567
Reed Kotler373feca2013-01-16 17:10:28 +00005568 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005569 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005570 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5571 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005572 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005573 if (FD->hasAttr<Mips16Attr>()) {
5574 Fn->addFnAttr("mips16");
5575 }
5576 else if (FD->hasAttr<NoMips16Attr>()) {
5577 Fn->addFnAttr("nomips16");
5578 }
Reed Kotler373feca2013-01-16 17:10:28 +00005579 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005580
John McCall943fae92010-05-27 06:19:26 +00005581 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005582 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005583
Craig Topper4f12f102014-03-12 06:41:41 +00005584 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005585 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005586 }
John McCall943fae92010-05-27 06:19:26 +00005587};
5588}
5589
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005590void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005591 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005592 llvm::IntegerType *IntTy =
5593 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005594
5595 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5596 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5597 ArgList.push_back(IntTy);
5598
5599 // If necessary, add one more integer type to ArgList.
5600 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5601
5602 if (R)
5603 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005604}
5605
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005606// In N32/64, an aligned double precision floating point field is passed in
5607// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005608llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005609 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5610
5611 if (IsO32) {
5612 CoerceToIntArgs(TySize, ArgList);
5613 return llvm::StructType::get(getVMContext(), ArgList);
5614 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005615
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005616 if (Ty->isComplexType())
5617 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005618
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005619 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005620
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005621 // Unions/vectors are passed in integer registers.
5622 if (!RT || !RT->isStructureOrClassType()) {
5623 CoerceToIntArgs(TySize, ArgList);
5624 return llvm::StructType::get(getVMContext(), ArgList);
5625 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005626
5627 const RecordDecl *RD = RT->getDecl();
5628 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005629 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005630
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005631 uint64_t LastOffset = 0;
5632 unsigned idx = 0;
5633 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5634
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005635 // Iterate over fields in the struct/class and check if there are any aligned
5636 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005637 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5638 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005639 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005640 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5641
5642 if (!BT || BT->getKind() != BuiltinType::Double)
5643 continue;
5644
5645 uint64_t Offset = Layout.getFieldOffset(idx);
5646 if (Offset % 64) // Ignore doubles that are not aligned.
5647 continue;
5648
5649 // Add ((Offset - LastOffset) / 64) args of type i64.
5650 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5651 ArgList.push_back(I64);
5652
5653 // Add double type.
5654 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5655 LastOffset = Offset + 64;
5656 }
5657
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005658 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5659 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005660
5661 return llvm::StructType::get(getVMContext(), ArgList);
5662}
5663
Akira Hatanakaddd66342013-10-29 18:41:15 +00005664llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5665 uint64_t Offset) const {
5666 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005667 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005668
Akira Hatanakaddd66342013-10-29 18:41:15 +00005669 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005670}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005671
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005672ABIArgInfo
5673MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005674 Ty = useFirstFieldIfTransparentUnion(Ty);
5675
Akira Hatanaka1632af62012-01-09 19:31:25 +00005676 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005677 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005678 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005679
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005680 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5681 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005682 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5683 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005684
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005685 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005686 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005687 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005688 return ABIArgInfo::getIgnore();
5689
Mark Lacey3825e832013-10-06 01:33:34 +00005690 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005691 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005692 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005693 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005694
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005695 // If we have reached here, aggregates are passed directly by coercing to
5696 // another structure type. Padding is inserted if the offset of the
5697 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005698 ABIArgInfo ArgInfo =
5699 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5700 getPaddingType(OrigOffset, CurrOffset));
5701 ArgInfo.setInReg(true);
5702 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005703 }
5704
5705 // Treat an enum type as its underlying type.
5706 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5707 Ty = EnumTy->getDecl()->getIntegerType();
5708
Daniel Sanders5b445b32014-10-24 14:42:42 +00005709 // All integral types are promoted to the GPR width.
5710 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005711 return ABIArgInfo::getExtend();
5712
Akira Hatanakaddd66342013-10-29 18:41:15 +00005713 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005714 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005715}
5716
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005717llvm::Type*
5718MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005719 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005720 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005721
Akira Hatanakab6f74432012-02-09 18:49:26 +00005722 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005723 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005724 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5725 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005726
Akira Hatanakab6f74432012-02-09 18:49:26 +00005727 // N32/64 returns struct/classes in floating point registers if the
5728 // following conditions are met:
5729 // 1. The size of the struct/class is no larger than 128-bit.
5730 // 2. The struct/class has one or two fields all of which are floating
5731 // point types.
5732 // 3. The offset of the first field is zero (this follows what gcc does).
5733 //
5734 // Any other composite results are returned in integer registers.
5735 //
5736 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5737 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5738 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005739 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005740
Akira Hatanakab6f74432012-02-09 18:49:26 +00005741 if (!BT || !BT->isFloatingPoint())
5742 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005743
David Blaikie2d7c57e2012-04-30 02:36:29 +00005744 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005745 }
5746
5747 if (b == e)
5748 return llvm::StructType::get(getVMContext(), RTList,
5749 RD->hasAttr<PackedAttr>());
5750
5751 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005752 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005753 }
5754
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005755 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005756 return llvm::StructType::get(getVMContext(), RTList);
5757}
5758
Akira Hatanakab579fe52011-06-02 00:09:17 +00005759ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005760 uint64_t Size = getContext().getTypeSize(RetTy);
5761
Daniel Sandersed39f582014-09-04 13:28:14 +00005762 if (RetTy->isVoidType())
5763 return ABIArgInfo::getIgnore();
5764
5765 // O32 doesn't treat zero-sized structs differently from other structs.
5766 // However, N32/N64 ignores zero sized return values.
5767 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005768 return ABIArgInfo::getIgnore();
5769
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005770 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005771 if (Size <= 128) {
5772 if (RetTy->isAnyComplexType())
5773 return ABIArgInfo::getDirect();
5774
Daniel Sanderse5018b62014-09-04 15:05:39 +00005775 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005776 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005777 if (!IsO32 ||
5778 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5779 ABIArgInfo ArgInfo =
5780 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5781 ArgInfo.setInReg(true);
5782 return ArgInfo;
5783 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005784 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005785
5786 return ABIArgInfo::getIndirect(0);
5787 }
5788
5789 // Treat an enum type as its underlying type.
5790 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5791 RetTy = EnumTy->getDecl()->getIntegerType();
5792
5793 return (RetTy->isPromotableIntegerType() ?
5794 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5795}
5796
5797void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005798 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005799 if (!getCXXABI().classifyReturnType(FI))
5800 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005801
5802 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005803 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005804
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005805 for (auto &I : FI.arguments())
5806 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005807}
5808
5809llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5810 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005811 llvm::Type *BP = CGF.Int8PtrTy;
5812 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005813
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005814 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5815 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005816 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005817 unsigned PtrWidth = getTarget().getPointerWidth(0);
5818 if ((Ty->isIntegerType() &&
5819 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5820 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005821 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5822 Ty->isSignedIntegerType());
5823 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005824
5825 CGBuilderTy &Builder = CGF.Builder;
5826 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5827 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005828 int64_t TypeAlign =
5829 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005830 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5831 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005832 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5833
5834 if (TypeAlign > MinABIStackAlignInBytes) {
5835 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5836 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5837 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5838 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5839 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5840 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5841 }
5842 else
5843 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5844
5845 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5846 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005847 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5848 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005849 llvm::Value *NextAddr =
5850 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5851 "ap.next");
5852 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5853
5854 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005855}
5856
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005857bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
5858 int TySize = getContext().getTypeSize(Ty);
5859
5860 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
5861 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
5862 return true;
5863
5864 return false;
5865}
5866
John McCall943fae92010-05-27 06:19:26 +00005867bool
5868MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5869 llvm::Value *Address) const {
5870 // This information comes from gcc's implementation, which seems to
5871 // as canonical as it gets.
5872
John McCall943fae92010-05-27 06:19:26 +00005873 // Everything on MIPS is 4 bytes. Double-precision FP registers
5874 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005875 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005876
5877 // 0-31 are the general purpose registers, $0 - $31.
5878 // 32-63 are the floating-point registers, $f0 - $f31.
5879 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5880 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005881 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005882
5883 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5884 // They are one bit wide and ignored here.
5885
5886 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5887 // (coprocessor 1 is the FP unit)
5888 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5889 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5890 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005891 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005892 return false;
5893}
5894
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005895//===----------------------------------------------------------------------===//
5896// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5897// Currently subclassed only to implement custom OpenCL C function attribute
5898// handling.
5899//===----------------------------------------------------------------------===//
5900
5901namespace {
5902
5903class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5904public:
5905 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5906 : DefaultTargetCodeGenInfo(CGT) {}
5907
Craig Topper4f12f102014-03-12 06:41:41 +00005908 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5909 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005910};
5911
5912void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5913 llvm::GlobalValue *GV,
5914 CodeGen::CodeGenModule &M) const {
5915 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5916 if (!FD) return;
5917
5918 llvm::Function *F = cast<llvm::Function>(GV);
5919
David Blaikiebbafb8a2012-03-11 07:00:24 +00005920 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005921 if (FD->hasAttr<OpenCLKernelAttr>()) {
5922 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005923 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005924 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5925 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005926 // Convert the reqd_work_group_size() attributes to metadata.
5927 llvm::LLVMContext &Context = F->getContext();
5928 llvm::NamedMDNode *OpenCLMetadata =
5929 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5930
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005931 SmallVector<llvm::Metadata *, 5> Operands;
5932 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005933
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005934 Operands.push_back(
5935 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5936 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5937 Operands.push_back(
5938 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5939 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5940 Operands.push_back(
5941 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5942 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005943
5944 // Add a boolean constant operand for "required" (true) or "hint" (false)
5945 // for implementing the work_group_size_hint attr later. Currently
5946 // always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005947 Operands.push_back(
5948 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005949 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5950 }
5951 }
5952 }
5953}
5954
5955}
John McCall943fae92010-05-27 06:19:26 +00005956
Tony Linthicum76329bf2011-12-12 21:14:55 +00005957//===----------------------------------------------------------------------===//
5958// Hexagon ABI Implementation
5959//===----------------------------------------------------------------------===//
5960
5961namespace {
5962
5963class HexagonABIInfo : public ABIInfo {
5964
5965
5966public:
5967 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5968
5969private:
5970
5971 ABIArgInfo classifyReturnType(QualType RetTy) const;
5972 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5973
Craig Topper4f12f102014-03-12 06:41:41 +00005974 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005975
Craig Topper4f12f102014-03-12 06:41:41 +00005976 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5977 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005978};
5979
5980class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5981public:
5982 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5983 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5984
Craig Topper4f12f102014-03-12 06:41:41 +00005985 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005986 return 29;
5987 }
5988};
5989
5990}
5991
5992void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005993 if (!getCXXABI().classifyReturnType(FI))
5994 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005995 for (auto &I : FI.arguments())
5996 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005997}
5998
5999ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6000 if (!isAggregateTypeForABI(Ty)) {
6001 // Treat an enum type as its underlying type.
6002 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6003 Ty = EnumTy->getDecl()->getIntegerType();
6004
6005 return (Ty->isPromotableIntegerType() ?
6006 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6007 }
6008
6009 // Ignore empty records.
6010 if (isEmptyRecord(getContext(), Ty, true))
6011 return ABIArgInfo::getIgnore();
6012
Mark Lacey3825e832013-10-06 01:33:34 +00006013 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00006014 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006015
6016 uint64_t Size = getContext().getTypeSize(Ty);
6017 if (Size > 64)
6018 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6019 // Pass in the smallest viable integer type.
6020 else if (Size > 32)
6021 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6022 else if (Size > 16)
6023 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6024 else if (Size > 8)
6025 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6026 else
6027 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6028}
6029
6030ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6031 if (RetTy->isVoidType())
6032 return ABIArgInfo::getIgnore();
6033
6034 // Large vector types should be returned via memory.
6035 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6036 return ABIArgInfo::getIndirect(0);
6037
6038 if (!isAggregateTypeForABI(RetTy)) {
6039 // Treat an enum type as its underlying type.
6040 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6041 RetTy = EnumTy->getDecl()->getIntegerType();
6042
6043 return (RetTy->isPromotableIntegerType() ?
6044 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6045 }
6046
Tony Linthicum76329bf2011-12-12 21:14:55 +00006047 if (isEmptyRecord(getContext(), RetTy, true))
6048 return ABIArgInfo::getIgnore();
6049
6050 // Aggregates <= 8 bytes are returned in r0; other aggregates
6051 // are returned indirectly.
6052 uint64_t Size = getContext().getTypeSize(RetTy);
6053 if (Size <= 64) {
6054 // Return in the smallest viable integer type.
6055 if (Size <= 8)
6056 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6057 if (Size <= 16)
6058 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6059 if (Size <= 32)
6060 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6061 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6062 }
6063
6064 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6065}
6066
6067llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006068 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006069 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006070 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006071
6072 CGBuilderTy &Builder = CGF.Builder;
6073 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6074 "ap");
6075 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6076 llvm::Type *PTy =
6077 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6078 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6079
6080 uint64_t Offset =
6081 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6082 llvm::Value *NextAddr =
6083 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6084 "ap.next");
6085 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6086
6087 return AddrTyped;
6088}
6089
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006090//===----------------------------------------------------------------------===//
6091// AMDGPU ABI Implementation
6092//===----------------------------------------------------------------------===//
6093
6094namespace {
6095
6096class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6097public:
6098 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6099 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6100 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6101 CodeGen::CodeGenModule &M) const override;
6102};
6103
6104}
6105
6106void AMDGPUTargetCodeGenInfo::SetTargetAttributes(
6107 const Decl *D,
6108 llvm::GlobalValue *GV,
6109 CodeGen::CodeGenModule &M) const {
6110 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6111 if (!FD)
6112 return;
6113
6114 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6115 llvm::Function *F = cast<llvm::Function>(GV);
6116 uint32_t NumVGPR = Attr->getNumVGPR();
6117 if (NumVGPR != 0)
6118 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6119 }
6120
6121 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6122 llvm::Function *F = cast<llvm::Function>(GV);
6123 unsigned NumSGPR = Attr->getNumSGPR();
6124 if (NumSGPR != 0)
6125 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6126 }
6127}
6128
Tony Linthicum76329bf2011-12-12 21:14:55 +00006129
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006130//===----------------------------------------------------------------------===//
6131// SPARC v9 ABI Implementation.
6132// Based on the SPARC Compliance Definition version 2.4.1.
6133//
6134// Function arguments a mapped to a nominal "parameter array" and promoted to
6135// registers depending on their type. Each argument occupies 8 or 16 bytes in
6136// the array, structs larger than 16 bytes are passed indirectly.
6137//
6138// One case requires special care:
6139//
6140// struct mixed {
6141// int i;
6142// float f;
6143// };
6144//
6145// When a struct mixed is passed by value, it only occupies 8 bytes in the
6146// parameter array, but the int is passed in an integer register, and the float
6147// is passed in a floating point register. This is represented as two arguments
6148// with the LLVM IR inreg attribute:
6149//
6150// declare void f(i32 inreg %i, float inreg %f)
6151//
6152// The code generator will only allocate 4 bytes from the parameter array for
6153// the inreg arguments. All other arguments are allocated a multiple of 8
6154// bytes.
6155//
6156namespace {
6157class SparcV9ABIInfo : public ABIInfo {
6158public:
6159 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6160
6161private:
6162 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006163 void computeInfo(CGFunctionInfo &FI) const override;
6164 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6165 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006166
6167 // Coercion type builder for structs passed in registers. The coercion type
6168 // serves two purposes:
6169 //
6170 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6171 // in registers.
6172 // 2. Expose aligned floating point elements as first-level elements, so the
6173 // code generator knows to pass them in floating point registers.
6174 //
6175 // We also compute the InReg flag which indicates that the struct contains
6176 // aligned 32-bit floats.
6177 //
6178 struct CoerceBuilder {
6179 llvm::LLVMContext &Context;
6180 const llvm::DataLayout &DL;
6181 SmallVector<llvm::Type*, 8> Elems;
6182 uint64_t Size;
6183 bool InReg;
6184
6185 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6186 : Context(c), DL(dl), Size(0), InReg(false) {}
6187
6188 // Pad Elems with integers until Size is ToSize.
6189 void pad(uint64_t ToSize) {
6190 assert(ToSize >= Size && "Cannot remove elements");
6191 if (ToSize == Size)
6192 return;
6193
6194 // Finish the current 64-bit word.
6195 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6196 if (Aligned > Size && Aligned <= ToSize) {
6197 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6198 Size = Aligned;
6199 }
6200
6201 // Add whole 64-bit words.
6202 while (Size + 64 <= ToSize) {
6203 Elems.push_back(llvm::Type::getInt64Ty(Context));
6204 Size += 64;
6205 }
6206
6207 // Final in-word padding.
6208 if (Size < ToSize) {
6209 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6210 Size = ToSize;
6211 }
6212 }
6213
6214 // Add a floating point element at Offset.
6215 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6216 // Unaligned floats are treated as integers.
6217 if (Offset % Bits)
6218 return;
6219 // The InReg flag is only required if there are any floats < 64 bits.
6220 if (Bits < 64)
6221 InReg = true;
6222 pad(Offset);
6223 Elems.push_back(Ty);
6224 Size = Offset + Bits;
6225 }
6226
6227 // Add a struct type to the coercion type, starting at Offset (in bits).
6228 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6229 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6230 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6231 llvm::Type *ElemTy = StrTy->getElementType(i);
6232 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6233 switch (ElemTy->getTypeID()) {
6234 case llvm::Type::StructTyID:
6235 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6236 break;
6237 case llvm::Type::FloatTyID:
6238 addFloat(ElemOffset, ElemTy, 32);
6239 break;
6240 case llvm::Type::DoubleTyID:
6241 addFloat(ElemOffset, ElemTy, 64);
6242 break;
6243 case llvm::Type::FP128TyID:
6244 addFloat(ElemOffset, ElemTy, 128);
6245 break;
6246 case llvm::Type::PointerTyID:
6247 if (ElemOffset % 64 == 0) {
6248 pad(ElemOffset);
6249 Elems.push_back(ElemTy);
6250 Size += 64;
6251 }
6252 break;
6253 default:
6254 break;
6255 }
6256 }
6257 }
6258
6259 // Check if Ty is a usable substitute for the coercion type.
6260 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006261 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006262 }
6263
6264 // Get the coercion type as a literal struct type.
6265 llvm::Type *getType() const {
6266 if (Elems.size() == 1)
6267 return Elems.front();
6268 else
6269 return llvm::StructType::get(Context, Elems);
6270 }
6271 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006272};
6273} // end anonymous namespace
6274
6275ABIArgInfo
6276SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6277 if (Ty->isVoidType())
6278 return ABIArgInfo::getIgnore();
6279
6280 uint64_t Size = getContext().getTypeSize(Ty);
6281
6282 // Anything too big to fit in registers is passed with an explicit indirect
6283 // pointer / sret pointer.
6284 if (Size > SizeLimit)
6285 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6286
6287 // Treat an enum type as its underlying type.
6288 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6289 Ty = EnumTy->getDecl()->getIntegerType();
6290
6291 // Integer types smaller than a register are extended.
6292 if (Size < 64 && Ty->isIntegerType())
6293 return ABIArgInfo::getExtend();
6294
6295 // Other non-aggregates go in registers.
6296 if (!isAggregateTypeForABI(Ty))
6297 return ABIArgInfo::getDirect();
6298
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006299 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6300 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6301 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6302 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6303
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006304 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006305 // Build a coercion type from the LLVM struct type.
6306 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6307 if (!StrTy)
6308 return ABIArgInfo::getDirect();
6309
6310 CoerceBuilder CB(getVMContext(), getDataLayout());
6311 CB.addStruct(0, StrTy);
6312 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6313
6314 // Try to use the original type for coercion.
6315 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6316
6317 if (CB.InReg)
6318 return ABIArgInfo::getDirectInReg(CoerceTy);
6319 else
6320 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006321}
6322
6323llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6324 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006325 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6326 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6327 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6328 AI.setCoerceToType(ArgTy);
6329
6330 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6331 CGBuilderTy &Builder = CGF.Builder;
6332 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6333 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6334 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6335 llvm::Value *ArgAddr;
6336 unsigned Stride;
6337
6338 switch (AI.getKind()) {
6339 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006340 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006341 llvm_unreachable("Unsupported ABI kind for va_arg");
6342
6343 case ABIArgInfo::Extend:
6344 Stride = 8;
6345 ArgAddr = Builder
6346 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6347 "extend");
6348 break;
6349
6350 case ABIArgInfo::Direct:
6351 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6352 ArgAddr = Addr;
6353 break;
6354
6355 case ABIArgInfo::Indirect:
6356 Stride = 8;
6357 ArgAddr = Builder.CreateBitCast(Addr,
6358 llvm::PointerType::getUnqual(ArgPtrTy),
6359 "indirect");
6360 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6361 break;
6362
6363 case ABIArgInfo::Ignore:
6364 return llvm::UndefValue::get(ArgPtrTy);
6365 }
6366
6367 // Update VAList.
6368 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6369 Builder.CreateStore(Addr, VAListAddrAsBPP);
6370
6371 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006372}
6373
6374void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6375 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006376 for (auto &I : FI.arguments())
6377 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006378}
6379
6380namespace {
6381class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6382public:
6383 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6384 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006385
Craig Topper4f12f102014-03-12 06:41:41 +00006386 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006387 return 14;
6388 }
6389
6390 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006391 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006392};
6393} // end anonymous namespace
6394
Roman Divackyf02c9942014-02-24 18:46:27 +00006395bool
6396SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6397 llvm::Value *Address) const {
6398 // This is calculated from the LLVM and GCC tables and verified
6399 // against gcc output. AFAIK all ABIs use the same encoding.
6400
6401 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6402
6403 llvm::IntegerType *i8 = CGF.Int8Ty;
6404 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6405 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6406
6407 // 0-31: the 8-byte general-purpose registers
6408 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6409
6410 // 32-63: f0-31, the 4-byte floating-point registers
6411 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6412
6413 // Y = 64
6414 // PSR = 65
6415 // WIM = 66
6416 // TBR = 67
6417 // PC = 68
6418 // NPC = 69
6419 // FSR = 70
6420 // CSR = 71
6421 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6422
6423 // 72-87: d0-15, the 8-byte floating-point registers
6424 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6425
6426 return false;
6427}
6428
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006429
Robert Lytton0e076492013-08-13 09:43:10 +00006430//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006431// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006432//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006433
Robert Lytton0e076492013-08-13 09:43:10 +00006434namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006435
6436/// A SmallStringEnc instance is used to build up the TypeString by passing
6437/// it by reference between functions that append to it.
6438typedef llvm::SmallString<128> SmallStringEnc;
6439
6440/// TypeStringCache caches the meta encodings of Types.
6441///
6442/// The reason for caching TypeStrings is two fold:
6443/// 1. To cache a type's encoding for later uses;
6444/// 2. As a means to break recursive member type inclusion.
6445///
6446/// A cache Entry can have a Status of:
6447/// NonRecursive: The type encoding is not recursive;
6448/// Recursive: The type encoding is recursive;
6449/// Incomplete: An incomplete TypeString;
6450/// IncompleteUsed: An incomplete TypeString that has been used in a
6451/// Recursive type encoding.
6452///
6453/// A NonRecursive entry will have all of its sub-members expanded as fully
6454/// as possible. Whilst it may contain types which are recursive, the type
6455/// itself is not recursive and thus its encoding may be safely used whenever
6456/// the type is encountered.
6457///
6458/// A Recursive entry will have all of its sub-members expanded as fully as
6459/// possible. The type itself is recursive and it may contain other types which
6460/// are recursive. The Recursive encoding must not be used during the expansion
6461/// of a recursive type's recursive branch. For simplicity the code uses
6462/// IncompleteCount to reject all usage of Recursive encodings for member types.
6463///
6464/// An Incomplete entry is always a RecordType and only encodes its
6465/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6466/// are placed into the cache during type expansion as a means to identify and
6467/// handle recursive inclusion of types as sub-members. If there is recursion
6468/// the entry becomes IncompleteUsed.
6469///
6470/// During the expansion of a RecordType's members:
6471///
6472/// If the cache contains a NonRecursive encoding for the member type, the
6473/// cached encoding is used;
6474///
6475/// If the cache contains a Recursive encoding for the member type, the
6476/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6477///
6478/// If the member is a RecordType, an Incomplete encoding is placed into the
6479/// cache to break potential recursive inclusion of itself as a sub-member;
6480///
6481/// Once a member RecordType has been expanded, its temporary incomplete
6482/// entry is removed from the cache. If a Recursive encoding was swapped out
6483/// it is swapped back in;
6484///
6485/// If an incomplete entry is used to expand a sub-member, the incomplete
6486/// entry is marked as IncompleteUsed. The cache keeps count of how many
6487/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6488///
6489/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6490/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6491/// Else the member is part of a recursive type and thus the recursion has
6492/// been exited too soon for the encoding to be correct for the member.
6493///
6494class TypeStringCache {
6495 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6496 struct Entry {
6497 std::string Str; // The encoded TypeString for the type.
6498 enum Status State; // Information about the encoding in 'Str'.
6499 std::string Swapped; // A temporary place holder for a Recursive encoding
6500 // during the expansion of RecordType's members.
6501 };
6502 std::map<const IdentifierInfo *, struct Entry> Map;
6503 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6504 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6505public:
Robert Lyttond263f142014-05-06 09:38:54 +00006506 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006507 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6508 bool removeIncomplete(const IdentifierInfo *ID);
6509 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6510 bool IsRecursive);
6511 StringRef lookupStr(const IdentifierInfo *ID);
6512};
6513
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006514/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006515/// FieldEncoding is a helper for this ordering process.
6516class FieldEncoding {
6517 bool HasName;
6518 std::string Enc;
6519public:
6520 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6521 StringRef str() {return Enc.c_str();};
6522 bool operator<(const FieldEncoding &rhs) const {
6523 if (HasName != rhs.HasName) return HasName;
6524 return Enc < rhs.Enc;
6525 }
6526};
6527
Robert Lytton7d1db152013-08-19 09:46:39 +00006528class XCoreABIInfo : public DefaultABIInfo {
6529public:
6530 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006531 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6532 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006533};
6534
Robert Lyttond21e2d72014-03-03 13:45:29 +00006535class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006536 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006537public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006538 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006539 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006540 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6541 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006542};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006543
Robert Lytton2d196952013-10-11 10:29:34 +00006544} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006545
Robert Lytton7d1db152013-08-19 09:46:39 +00006546llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6547 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006548 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006549
Robert Lytton2d196952013-10-11 10:29:34 +00006550 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006551 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6552 CGF.Int8PtrPtrTy);
6553 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006554
Robert Lytton2d196952013-10-11 10:29:34 +00006555 // Handle the argument.
6556 ABIArgInfo AI = classifyArgumentType(Ty);
6557 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6558 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6559 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006560 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006561 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006562 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006563 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006564 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006565 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006566 llvm_unreachable("Unsupported ABI kind for va_arg");
6567 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006568 Val = llvm::UndefValue::get(ArgPtrTy);
6569 ArgSize = 0;
6570 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006571 case ABIArgInfo::Extend:
6572 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006573 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6574 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6575 if (ArgSize < 4)
6576 ArgSize = 4;
6577 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006578 case ABIArgInfo::Indirect:
6579 llvm::Value *ArgAddr;
6580 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6581 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006582 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6583 ArgSize = 4;
6584 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006585 }
Robert Lytton2d196952013-10-11 10:29:34 +00006586
6587 // Increment the VAList.
6588 if (ArgSize) {
6589 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6590 Builder.CreateStore(APN, VAListAddrAsBPP);
6591 }
6592 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006593}
Robert Lytton0e076492013-08-13 09:43:10 +00006594
Robert Lytton844aeeb2014-05-02 09:33:20 +00006595/// During the expansion of a RecordType, an incomplete TypeString is placed
6596/// into the cache as a means to identify and break recursion.
6597/// If there is a Recursive encoding in the cache, it is swapped out and will
6598/// be reinserted by removeIncomplete().
6599/// All other types of encoding should have been used rather than arriving here.
6600void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6601 std::string StubEnc) {
6602 if (!ID)
6603 return;
6604 Entry &E = Map[ID];
6605 assert( (E.Str.empty() || E.State == Recursive) &&
6606 "Incorrectly use of addIncomplete");
6607 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6608 E.Swapped.swap(E.Str); // swap out the Recursive
6609 E.Str.swap(StubEnc);
6610 E.State = Incomplete;
6611 ++IncompleteCount;
6612}
6613
6614/// Once the RecordType has been expanded, the temporary incomplete TypeString
6615/// must be removed from the cache.
6616/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6617/// Returns true if the RecordType was defined recursively.
6618bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6619 if (!ID)
6620 return false;
6621 auto I = Map.find(ID);
6622 assert(I != Map.end() && "Entry not present");
6623 Entry &E = I->second;
6624 assert( (E.State == Incomplete ||
6625 E.State == IncompleteUsed) &&
6626 "Entry must be an incomplete type");
6627 bool IsRecursive = false;
6628 if (E.State == IncompleteUsed) {
6629 // We made use of our Incomplete encoding, thus we are recursive.
6630 IsRecursive = true;
6631 --IncompleteUsedCount;
6632 }
6633 if (E.Swapped.empty())
6634 Map.erase(I);
6635 else {
6636 // Swap the Recursive back.
6637 E.Swapped.swap(E.Str);
6638 E.Swapped.clear();
6639 E.State = Recursive;
6640 }
6641 --IncompleteCount;
6642 return IsRecursive;
6643}
6644
6645/// Add the encoded TypeString to the cache only if it is NonRecursive or
6646/// Recursive (viz: all sub-members were expanded as fully as possible).
6647void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6648 bool IsRecursive) {
6649 if (!ID || IncompleteUsedCount)
6650 return; // No key or it is is an incomplete sub-type so don't add.
6651 Entry &E = Map[ID];
6652 if (IsRecursive && !E.Str.empty()) {
6653 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6654 "This is not the same Recursive entry");
6655 // The parent container was not recursive after all, so we could have used
6656 // this Recursive sub-member entry after all, but we assumed the worse when
6657 // we started viz: IncompleteCount!=0.
6658 return;
6659 }
6660 assert(E.Str.empty() && "Entry already present");
6661 E.Str = Str.str();
6662 E.State = IsRecursive? Recursive : NonRecursive;
6663}
6664
6665/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6666/// are recursively expanding a type (IncompleteCount != 0) and the cached
6667/// encoding is Recursive, return an empty StringRef.
6668StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6669 if (!ID)
6670 return StringRef(); // We have no key.
6671 auto I = Map.find(ID);
6672 if (I == Map.end())
6673 return StringRef(); // We have no encoding.
6674 Entry &E = I->second;
6675 if (E.State == Recursive && IncompleteCount)
6676 return StringRef(); // We don't use Recursive encodings for member types.
6677
6678 if (E.State == Incomplete) {
6679 // The incomplete type is being used to break out of recursion.
6680 E.State = IncompleteUsed;
6681 ++IncompleteUsedCount;
6682 }
6683 return E.Str.c_str();
6684}
6685
6686/// The XCore ABI includes a type information section that communicates symbol
6687/// type information to the linker. The linker uses this information to verify
6688/// safety/correctness of things such as array bound and pointers et al.
6689/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6690/// This type information (TypeString) is emitted into meta data for all global
6691/// symbols: definitions, declarations, functions & variables.
6692///
6693/// The TypeString carries type, qualifier, name, size & value details.
6694/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6695/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6696/// The output is tested by test/CodeGen/xcore-stringtype.c.
6697///
6698static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6699 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6700
6701/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6702void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6703 CodeGen::CodeGenModule &CGM) const {
6704 SmallStringEnc Enc;
6705 if (getTypeString(Enc, D, CGM, TSC)) {
6706 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006707 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6708 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006709 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6710 llvm::NamedMDNode *MD =
6711 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6712 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6713 }
6714}
6715
6716static bool appendType(SmallStringEnc &Enc, QualType QType,
6717 const CodeGen::CodeGenModule &CGM,
6718 TypeStringCache &TSC);
6719
6720/// Helper function for appendRecordType().
6721/// Builds a SmallVector containing the encoded field types in declaration order.
6722static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6723 const RecordDecl *RD,
6724 const CodeGen::CodeGenModule &CGM,
6725 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006726 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006727 SmallStringEnc Enc;
6728 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006729 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006730 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006731 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006732 Enc += "b(";
6733 llvm::raw_svector_ostream OS(Enc);
6734 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006735 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006736 OS.flush();
6737 Enc += ':';
6738 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006739 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006740 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006741 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006742 Enc += ')';
6743 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006744 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006745 }
6746 return true;
6747}
6748
6749/// Appends structure and union types to Enc and adds encoding to cache.
6750/// Recursively calls appendType (via extractFieldType) for each field.
6751/// Union types have their fields ordered according to the ABI.
6752static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6753 const CodeGen::CodeGenModule &CGM,
6754 TypeStringCache &TSC, const IdentifierInfo *ID) {
6755 // Append the cached TypeString if we have one.
6756 StringRef TypeString = TSC.lookupStr(ID);
6757 if (!TypeString.empty()) {
6758 Enc += TypeString;
6759 return true;
6760 }
6761
6762 // Start to emit an incomplete TypeString.
6763 size_t Start = Enc.size();
6764 Enc += (RT->isUnionType()? 'u' : 's');
6765 Enc += '(';
6766 if (ID)
6767 Enc += ID->getName();
6768 Enc += "){";
6769
6770 // We collect all encoded fields and order as necessary.
6771 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006772 const RecordDecl *RD = RT->getDecl()->getDefinition();
6773 if (RD && !RD->field_empty()) {
6774 // An incomplete TypeString stub is placed in the cache for this RecordType
6775 // so that recursive calls to this RecordType will use it whilst building a
6776 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006777 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006778 std::string StubEnc(Enc.substr(Start).str());
6779 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6780 TSC.addIncomplete(ID, std::move(StubEnc));
6781 if (!extractFieldType(FE, RD, CGM, TSC)) {
6782 (void) TSC.removeIncomplete(ID);
6783 return false;
6784 }
6785 IsRecursive = TSC.removeIncomplete(ID);
6786 // The ABI requires unions to be sorted but not structures.
6787 // See FieldEncoding::operator< for sort algorithm.
6788 if (RT->isUnionType())
6789 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006790 // We can now complete the TypeString.
6791 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006792 for (unsigned I = 0; I != E; ++I) {
6793 if (I)
6794 Enc += ',';
6795 Enc += FE[I].str();
6796 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006797 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006798 Enc += '}';
6799 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6800 return true;
6801}
6802
6803/// Appends enum types to Enc and adds the encoding to the cache.
6804static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6805 TypeStringCache &TSC,
6806 const IdentifierInfo *ID) {
6807 // Append the cached TypeString if we have one.
6808 StringRef TypeString = TSC.lookupStr(ID);
6809 if (!TypeString.empty()) {
6810 Enc += TypeString;
6811 return true;
6812 }
6813
6814 size_t Start = Enc.size();
6815 Enc += "e(";
6816 if (ID)
6817 Enc += ID->getName();
6818 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006819
6820 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006821 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006822 SmallVector<FieldEncoding, 16> FE;
6823 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6824 ++I) {
6825 SmallStringEnc EnumEnc;
6826 EnumEnc += "m(";
6827 EnumEnc += I->getName();
6828 EnumEnc += "){";
6829 I->getInitVal().toString(EnumEnc);
6830 EnumEnc += '}';
6831 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6832 }
6833 std::sort(FE.begin(), FE.end());
6834 unsigned E = FE.size();
6835 for (unsigned I = 0; I != E; ++I) {
6836 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006837 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006838 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006839 }
6840 }
6841 Enc += '}';
6842 TSC.addIfComplete(ID, Enc.substr(Start), false);
6843 return true;
6844}
6845
6846/// Appends type's qualifier to Enc.
6847/// This is done prior to appending the type's encoding.
6848static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6849 // Qualifiers are emitted in alphabetical order.
6850 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6851 int Lookup = 0;
6852 if (QT.isConstQualified())
6853 Lookup += 1<<0;
6854 if (QT.isRestrictQualified())
6855 Lookup += 1<<1;
6856 if (QT.isVolatileQualified())
6857 Lookup += 1<<2;
6858 Enc += Table[Lookup];
6859}
6860
6861/// Appends built-in types to Enc.
6862static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6863 const char *EncType;
6864 switch (BT->getKind()) {
6865 case BuiltinType::Void:
6866 EncType = "0";
6867 break;
6868 case BuiltinType::Bool:
6869 EncType = "b";
6870 break;
6871 case BuiltinType::Char_U:
6872 EncType = "uc";
6873 break;
6874 case BuiltinType::UChar:
6875 EncType = "uc";
6876 break;
6877 case BuiltinType::SChar:
6878 EncType = "sc";
6879 break;
6880 case BuiltinType::UShort:
6881 EncType = "us";
6882 break;
6883 case BuiltinType::Short:
6884 EncType = "ss";
6885 break;
6886 case BuiltinType::UInt:
6887 EncType = "ui";
6888 break;
6889 case BuiltinType::Int:
6890 EncType = "si";
6891 break;
6892 case BuiltinType::ULong:
6893 EncType = "ul";
6894 break;
6895 case BuiltinType::Long:
6896 EncType = "sl";
6897 break;
6898 case BuiltinType::ULongLong:
6899 EncType = "ull";
6900 break;
6901 case BuiltinType::LongLong:
6902 EncType = "sll";
6903 break;
6904 case BuiltinType::Float:
6905 EncType = "ft";
6906 break;
6907 case BuiltinType::Double:
6908 EncType = "d";
6909 break;
6910 case BuiltinType::LongDouble:
6911 EncType = "ld";
6912 break;
6913 default:
6914 return false;
6915 }
6916 Enc += EncType;
6917 return true;
6918}
6919
6920/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6921static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6922 const CodeGen::CodeGenModule &CGM,
6923 TypeStringCache &TSC) {
6924 Enc += "p(";
6925 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6926 return false;
6927 Enc += ')';
6928 return true;
6929}
6930
6931/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006932static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6933 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006934 const CodeGen::CodeGenModule &CGM,
6935 TypeStringCache &TSC, StringRef NoSizeEnc) {
6936 if (AT->getSizeModifier() != ArrayType::Normal)
6937 return false;
6938 Enc += "a(";
6939 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6940 CAT->getSize().toStringUnsigned(Enc);
6941 else
6942 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6943 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006944 // The Qualifiers should be attached to the type rather than the array.
6945 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006946 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6947 return false;
6948 Enc += ')';
6949 return true;
6950}
6951
6952/// Appends a function encoding to Enc, calling appendType for the return type
6953/// and the arguments.
6954static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6955 const CodeGen::CodeGenModule &CGM,
6956 TypeStringCache &TSC) {
6957 Enc += "f{";
6958 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6959 return false;
6960 Enc += "}(";
6961 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6962 // N.B. we are only interested in the adjusted param types.
6963 auto I = FPT->param_type_begin();
6964 auto E = FPT->param_type_end();
6965 if (I != E) {
6966 do {
6967 if (!appendType(Enc, *I, CGM, TSC))
6968 return false;
6969 ++I;
6970 if (I != E)
6971 Enc += ',';
6972 } while (I != E);
6973 if (FPT->isVariadic())
6974 Enc += ",va";
6975 } else {
6976 if (FPT->isVariadic())
6977 Enc += "va";
6978 else
6979 Enc += '0';
6980 }
6981 }
6982 Enc += ')';
6983 return true;
6984}
6985
6986/// Handles the type's qualifier before dispatching a call to handle specific
6987/// type encodings.
6988static bool appendType(SmallStringEnc &Enc, QualType QType,
6989 const CodeGen::CodeGenModule &CGM,
6990 TypeStringCache &TSC) {
6991
6992 QualType QT = QType.getCanonicalType();
6993
Robert Lytton6adb20f2014-06-05 09:06:21 +00006994 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6995 // The Qualifiers should be attached to the type rather than the array.
6996 // Thus we don't call appendQualifier() here.
6997 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6998
Robert Lytton844aeeb2014-05-02 09:33:20 +00006999 appendQualifier(Enc, QT);
7000
7001 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7002 return appendBuiltinType(Enc, BT);
7003
Robert Lytton844aeeb2014-05-02 09:33:20 +00007004 if (const PointerType *PT = QT->getAs<PointerType>())
7005 return appendPointerType(Enc, PT, CGM, TSC);
7006
7007 if (const EnumType *ET = QT->getAs<EnumType>())
7008 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7009
7010 if (const RecordType *RT = QT->getAsStructureType())
7011 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7012
7013 if (const RecordType *RT = QT->getAsUnionType())
7014 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7015
7016 if (const FunctionType *FT = QT->getAs<FunctionType>())
7017 return appendFunctionType(Enc, FT, CGM, TSC);
7018
7019 return false;
7020}
7021
7022static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7023 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7024 if (!D)
7025 return false;
7026
7027 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7028 if (FD->getLanguageLinkage() != CLanguageLinkage)
7029 return false;
7030 return appendType(Enc, FD->getType(), CGM, TSC);
7031 }
7032
7033 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7034 if (VD->getLanguageLinkage() != CLanguageLinkage)
7035 return false;
7036 QualType QT = VD->getType().getCanonicalType();
7037 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7038 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007039 // The Qualifiers should be attached to the type rather than the array.
7040 // Thus we don't call appendQualifier() here.
7041 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007042 }
7043 return appendType(Enc, QT, CGM, TSC);
7044 }
7045 return false;
7046}
7047
7048
Robert Lytton0e076492013-08-13 09:43:10 +00007049//===----------------------------------------------------------------------===//
7050// Driver code
7051//===----------------------------------------------------------------------===//
7052
Rafael Espindola9f834732014-09-19 01:54:22 +00007053const llvm::Triple &CodeGenModule::getTriple() const {
7054 return getTarget().getTriple();
7055}
7056
7057bool CodeGenModule::supportsCOMDAT() const {
7058 return !getTriple().isOSBinFormatMachO();
7059}
7060
Chris Lattner2b037972010-07-29 02:01:43 +00007061const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007062 if (TheTargetCodeGenInfo)
7063 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007064
John McCallc8e01702013-04-16 22:48:15 +00007065 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007066 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007067 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007068 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007069
Derek Schuff09338a22012-09-06 17:37:28 +00007070 case llvm::Triple::le32:
7071 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007072 case llvm::Triple::mips:
7073 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007074 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7075
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007076 case llvm::Triple::mips64:
7077 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007078 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7079
Tim Northover25e8a672014-05-24 12:51:25 +00007080 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007081 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007082 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007083 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007084 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007085
Tim Northover573cbee2014-05-24 12:52:07 +00007086 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007087 }
7088
Daniel Dunbard59655c2009-09-12 00:59:49 +00007089 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007090 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007091 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007092 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007093 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007094 if (Triple.getOS() == llvm::Triple::Win32) {
7095 TheTargetCodeGenInfo =
7096 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7097 return *TheTargetCodeGenInfo;
7098 }
7099
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007100 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007101 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007102 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007103 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007104 (CodeGenOpts.FloatABI != "soft" &&
7105 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007106 Kind = ARMABIInfo::AAPCS_VFP;
7107
Derek Schuff71658bd2015-01-29 00:47:04 +00007108 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007109 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007110
John McCallea8d8bb2010-03-11 00:10:12 +00007111 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007112 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007113 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007114 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007115 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007116 if (getTarget().getABI() == "elfv2")
7117 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007118 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007119
Ulrich Weigandb7122372014-07-21 00:48:09 +00007120 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007121 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007122 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007123 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007124 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007125 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007126 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007127 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007128 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007129 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007130
Ulrich Weigandb7122372014-07-21 00:48:09 +00007131 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007132 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007133 }
John McCallea8d8bb2010-03-11 00:10:12 +00007134
Peter Collingbournec947aae2012-05-20 23:28:41 +00007135 case llvm::Triple::nvptx:
7136 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007137 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007138
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007139 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007140 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007141
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007142 case llvm::Triple::systemz: {
7143 bool HasVector = getTarget().getABI() == "vector";
7144 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7145 HasVector));
7146 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007147
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007148 case llvm::Triple::tce:
7149 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7150
Eli Friedman33465822011-07-08 23:31:17 +00007151 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007152 bool IsDarwinVectorABI = Triple.isOSDarwin();
7153 bool IsSmallStructInRegABI =
7154 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007155 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007156
John McCall1fe2a8c2013-06-18 02:46:29 +00007157 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007158 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007159 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007160 IsDarwinVectorABI, IsSmallStructInRegABI,
7161 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007162 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007163 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007164 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007165 new X86_32TargetCodeGenInfo(Types,
7166 IsDarwinVectorABI, IsSmallStructInRegABI,
7167 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007168 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007169 }
Eli Friedman33465822011-07-08 23:31:17 +00007170 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007171
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007172 case llvm::Triple::x86_64: {
Chris Lattner04dc9572010-08-31 16:44:54 +00007173 switch (Triple.getOS()) {
7174 case llvm::Triple::Win32:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00007175 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007176 case llvm::Triple::PS4:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00007177 return *(TheTargetCodeGenInfo = new PS4TargetCodeGenInfo(Types));
Chris Lattner04dc9572010-08-31 16:44:54 +00007178 default:
Ahmed Bougacha1fca2ed2015-05-22 02:25:58 +00007179 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types));
Chris Lattner04dc9572010-08-31 16:44:54 +00007180 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007181 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007182 case llvm::Triple::hexagon:
7183 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007184 case llvm::Triple::r600:
7185 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007186 case llvm::Triple::amdgcn:
7187 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007188 case llvm::Triple::sparcv9:
7189 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007190 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007191 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007192 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007193}