blob: 36f9914108c5920ccf5ca5163f89b3257edbbdd2 [file] [log] [blame]
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikovc4a59eb2009-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 Korobeynikov82d0a412010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Stephen Hines176edba2014-12-01 14:53:08 -080018#include "CGValue.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Lacey8b549992013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel34c1af82011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070023#include "llvm/ADT/StringExtras.h"
Daniel Dunbar2c0843f2009-08-24 08:52:16 +000024#include "llvm/ADT/Triple.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar28df7a52009-12-03 09:13:49 +000027#include "llvm/Support/raw_ostream.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070028#include <algorithm> // std::sort
29
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCallaeeb7012010-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) {
40 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
41 Builder.CreateStore(Value, Cell);
42 }
43}
44
John McCalld608cdb2010-08-22 10:59:02 +000045static bool isAggregateTypeForABI(QualType T) {
John McCall9d232c82013-03-07 21:37:08 +000046 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalld608cdb2010-08-22 10:59:02 +000047 T->isMemberFunctionPointerType();
48}
49
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000050ABIInfo::~ABIInfo() {}
51
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000052static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey23630722013-10-06 01:33:34 +000053 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000054 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
55 if (!RD)
56 return CGCXXABI::RAA_Default;
Mark Lacey23630722013-10-06 01:33:34 +000057 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000058}
59
60static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey23630722013-10-06 01:33:34 +000061 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000062 const RecordType *RT = T->getAs<RecordType>();
63 if (!RT)
64 return CGCXXABI::RAA_Default;
Mark Lacey23630722013-10-06 01:33:34 +000065 return getRecordArgABI(RT, CXXABI);
66}
67
Stephen Hines176edba2014-12-01 14:53:08 -080068/// Pass transparent unions as if they were the type of the first element. Sema
69/// should ensure that all elements of the union have the same "machine type".
70static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
71 if (const RecordType *UT = Ty->getAsUnionType()) {
72 const RecordDecl *UD = UT->getDecl();
73 if (UD->hasAttr<TransparentUnionAttr>()) {
74 assert(!UD->field_empty() && "sema created an empty transparent union");
75 return UD->field_begin()->getType();
76 }
77 }
78 return Ty;
79}
80
Mark Lacey23630722013-10-06 01:33:34 +000081CGCXXABI &ABIInfo::getCXXABI() const {
82 return CGT.getCXXABI();
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000083}
84
Chris Lattnerea044322010-07-29 02:01:43 +000085ASTContext &ABIInfo::getContext() const {
86 return CGT.getContext();
87}
88
89llvm::LLVMContext &ABIInfo::getVMContext() const {
90 return CGT.getLLVMContext();
91}
92
Micah Villmow25a6a842012-10-08 16:25:52 +000093const llvm::DataLayout &ABIInfo::getDataLayout() const {
94 return CGT.getDataLayout();
Chris Lattnerea044322010-07-29 02:01:43 +000095}
96
John McCall64aa4b32013-04-16 22:48:15 +000097const TargetInfo &ABIInfo::getTarget() const {
98 return CGT.getTarget();
99}
Chris Lattnerea044322010-07-29 02:01:43 +0000100
Stephen Hines176edba2014-12-01 14:53:08 -0800101bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
102 return false;
103}
104
105bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
106 uint64_t Members) const {
107 return false;
108}
109
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000110void ABIArgInfo::dump() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000111 raw_ostream &OS = llvm::errs();
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000112 OS << "(ABIArgInfo Kind=";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000113 switch (TheKind) {
114 case Direct:
Chris Lattner800588f2010-07-29 06:26:06 +0000115 OS << "Direct Type=";
Chris Lattner2acc6e32011-07-18 04:24:23 +0000116 if (llvm::Type *Ty = getCoerceToType())
Chris Lattner800588f2010-07-29 06:26:06 +0000117 Ty->print(OS);
118 else
119 OS << "null";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000120 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000121 case Extend:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000122 OS << "Extend";
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000123 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000124 case Ignore:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000125 OS << "Ignore";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000126 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700127 case InAlloca:
128 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
129 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000130 case Indirect:
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000131 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenbergere9b5d772011-07-15 18:23:44 +0000132 << " ByVal=" << getIndirectByVal()
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000133 << " Realign=" << getIndirectRealign();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000134 break;
135 case Expand:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000136 OS << "Expand";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000137 break;
138 }
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000139 OS << ")\n";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000140}
141
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000142TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
143
John McCall49e34be2011-08-30 01:42:09 +0000144// If someone can figure out a general rule for this, that would be great.
145// It's probably just doomed to be platform-dependent, though.
146unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
147 // Verified for:
148 // x86-64 FreeBSD, Linux, Darwin
149 // x86-32 FreeBSD, Linux, Darwin
150 // PowerPC Linux, Darwin
151 // ARM Darwin (*not* EABI)
Tim Northoverc264e162013-01-31 12:13:10 +0000152 // AArch64 Linux
John McCall49e34be2011-08-30 01:42:09 +0000153 return 32;
154}
155
John McCallde5d3c72012-02-17 03:33:10 +0000156bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
157 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-09-21 08:08:30 +0000158 // The following conventions are known to require this to be false:
159 // x86_stdcall
160 // MIPS
161 // For everything else, we just prefer false unless we opt out.
162 return false;
163}
164
Reid Kleckner3190ca92013-05-08 13:44:39 +0000165void
166TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
167 llvm::SmallString<24> &Opt) const {
168 // This assumes the user is passing a library name like "rt" instead of a
169 // filename like "librt.a/so", and that they don't care whether it's static or
170 // dynamic.
171 Opt = "-l";
172 Opt += Lib;
173}
174
Daniel Dunbar98303b92009-09-13 08:03:58 +0000175static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000176
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000177/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000178/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar98303b92009-09-13 08:03:58 +0000179static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
180 bool AllowArrays) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000181 if (FD->isUnnamedBitfield())
182 return true;
183
184 QualType FT = FD->getType();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000185
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000186 // Constant arrays of empty records count as empty, strip them off.
187 // Constant arrays of zero length always count as empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000188 if (AllowArrays)
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000189 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
190 if (AT->getSize() == 0)
191 return true;
Daniel Dunbar98303b92009-09-13 08:03:58 +0000192 FT = AT->getElementType();
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000193 }
Daniel Dunbar98303b92009-09-13 08:03:58 +0000194
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000195 const RecordType *RT = FT->getAs<RecordType>();
196 if (!RT)
197 return false;
198
199 // C++ record fields are never empty, at least in the Itanium ABI.
200 //
201 // FIXME: We should use a predicate for whether this behavior is true in the
202 // current ABI.
203 if (isa<CXXRecordDecl>(RT->getDecl()))
204 return false;
205
Daniel Dunbar98303b92009-09-13 08:03:58 +0000206 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000207}
208
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000209/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000210/// fields. Note that a structure with a flexible array member is not
211/// considered empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000212static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000213 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000214 if (!RT)
215 return 0;
216 const RecordDecl *RD = RT->getDecl();
217 if (RD->hasFlexibleArrayMember())
218 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000219
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000220 // If this is a C++ record, check the bases first.
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000221 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Stephen Hines651f13c2014-04-23 16:59:28 -0700222 for (const auto &I : CXXRD->bases())
223 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000224 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000225
Stephen Hines651f13c2014-04-23 16:59:28 -0700226 for (const auto *I : RD->fields())
227 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000228 return false;
229 return true;
230}
231
232/// isSingleElementStruct - Determine if a structure is a "single
233/// element struct", i.e. it has exactly one non-empty field or
234/// exactly one field which is itself a single element
235/// struct. Structures with flexible array members are never
236/// considered single element structs.
237///
238/// \return The field declaration for the single non-empty field, if
239/// it exists.
240static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
241 const RecordType *RT = T->getAsStructureType();
242 if (!RT)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700243 return nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000244
245 const RecordDecl *RD = RT->getDecl();
246 if (RD->hasFlexibleArrayMember())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700247 return nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000248
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700249 const Type *Found = nullptr;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000250
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000251 // If this is a C++ record, check the bases first.
252 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700253 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000254 // Ignore empty records.
Stephen Hines651f13c2014-04-23 16:59:28 -0700255 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000256 continue;
257
258 // If we already found an element then this isn't a single-element struct.
259 if (Found)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700260 return nullptr;
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000261
262 // If this is non-empty and not a single element struct, the composite
263 // cannot be a single element struct.
Stephen Hines651f13c2014-04-23 16:59:28 -0700264 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000265 if (!Found)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700266 return nullptr;
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000267 }
268 }
269
270 // Check for single element.
Stephen Hines651f13c2014-04-23 16:59:28 -0700271 for (const auto *FD : RD->fields()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000272 QualType FT = FD->getType();
273
274 // Ignore empty fields.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000275 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000276 continue;
277
278 // If we already found an element then this isn't a single-element
279 // struct.
280 if (Found)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700281 return nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000282
283 // Treat single element arrays as the element.
284 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
285 if (AT->getSize().getZExtValue() != 1)
286 break;
287 FT = AT->getElementType();
288 }
289
John McCalld608cdb2010-08-22 10:59:02 +0000290 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000291 Found = FT.getTypePtr();
292 } else {
293 Found = isSingleElementStruct(FT, Context);
294 if (!Found)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700295 return nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000296 }
297 }
298
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000299 // We don't consider a struct a single-element struct if it has
300 // padding beyond the element type.
301 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700302 return nullptr;
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000303
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000304 return Found;
305}
306
307static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmandb748a32012-11-29 23:21:04 +0000308 // Treat complex types as the element type.
309 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
310 Ty = CTy->getElementType();
311
312 // Check for a type which we know has a simple scalar argument-passing
313 // convention without any padding. (We're specifically looking for 32
314 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbara1842d32010-05-14 03:40:53 +0000315 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmandb748a32012-11-29 23:21:04 +0000316 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000317 return false;
318
319 uint64_t Size = Context.getTypeSize(Ty);
320 return Size == 32 || Size == 64;
321}
322
Daniel Dunbar53012f42009-11-09 01:33:53 +0000323/// canExpandIndirectArgument - Test whether an argument type which is to be
324/// passed indirectly (on the stack) would have the equivalent layout if it was
325/// expanded into separate arguments. If so, we prefer to do the latter to avoid
326/// inhibiting optimizations.
327///
328// FIXME: This predicate is missing many cases, currently it just follows
329// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
330// should probably make this smarter, or better yet make the LLVM backend
331// capable of handling it.
332static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
333 // We can only expand structure types.
334 const RecordType *RT = Ty->getAs<RecordType>();
335 if (!RT)
336 return false;
337
338 // We can only expand (C) structures.
339 //
340 // FIXME: This needs to be generalized to handle classes as well.
341 const RecordDecl *RD = RT->getDecl();
342 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
343 return false;
344
Eli Friedman506d4e32011-11-18 01:32:26 +0000345 uint64_t Size = 0;
346
Stephen Hines651f13c2014-04-23 16:59:28 -0700347 for (const auto *FD : RD->fields()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000348 if (!is32Or64BitBasicType(FD->getType(), Context))
349 return false;
350
351 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
352 // how to expand them yet, and the predicate for telling if a bitfield still
353 // counts as "basic" is more complicated than what we were doing previously.
354 if (FD->isBitField())
355 return false;
Eli Friedman506d4e32011-11-18 01:32:26 +0000356
357 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000358 }
359
Eli Friedman506d4e32011-11-18 01:32:26 +0000360 // Make sure there are not any holes in the struct.
361 if (Size != Context.getTypeSize(Ty))
362 return false;
363
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000364 return true;
365}
366
367namespace {
368/// DefaultABIInfo - The default implementation for ABI specific
369/// details. This implementation provides information which results in
370/// self-consistent and sensible LLVM IR generation, but does not
371/// conform to any particular ABI.
372class DefaultABIInfo : public ABIInfo {
Chris Lattnerea044322010-07-29 02:01:43 +0000373public:
374 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000375
Chris Lattnera3c109b2010-07-29 02:16:43 +0000376 ABIArgInfo classifyReturnType(QualType RetTy) const;
377 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000378
Stephen Hines651f13c2014-04-23 16:59:28 -0700379 void computeInfo(CGFunctionInfo &FI) const override {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700380 if (!getCXXABI().classifyReturnType(FI))
381 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -0700382 for (auto &I : FI.arguments())
383 I.info = classifyArgumentType(I.type);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000384 }
385
Stephen Hines651f13c2014-04-23 16:59:28 -0700386 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
387 CodeGenFunction &CGF) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000388};
389
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000390class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
391public:
Chris Lattnerea044322010-07-29 02:01:43 +0000392 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
393 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000394};
395
396llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
397 CodeGenFunction &CGF) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700398 return nullptr;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000399}
400
Chris Lattnera3c109b2010-07-29 02:16:43 +0000401ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700402 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000403 return ABIArgInfo::getIndirect(0);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000404
Chris Lattnera14db752010-03-11 18:19:55 +0000405 // Treat an enum type as its underlying type.
406 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
407 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000408
Chris Lattnera14db752010-03-11 18:19:55 +0000409 return (Ty->isPromotableIntegerType() ?
410 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000411}
412
Bob Wilson0024f942011-01-10 23:54:17 +0000413ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
414 if (RetTy->isVoidType())
415 return ABIArgInfo::getIgnore();
416
417 if (isAggregateTypeForABI(RetTy))
418 return ABIArgInfo::getIndirect(0);
419
420 // Treat an enum type as its underlying type.
421 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
422 RetTy = EnumTy->getDecl()->getIntegerType();
423
424 return (RetTy->isPromotableIntegerType() ?
425 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
426}
427
Derek Schuff9ed63f82012-09-06 17:37:28 +0000428//===----------------------------------------------------------------------===//
429// le32/PNaCl bitcode ABI Implementation
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000430//
431// This is a simplified version of the x86_32 ABI. Arguments and return values
432// are always passed on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000433//===----------------------------------------------------------------------===//
434
435class PNaClABIInfo : public ABIInfo {
436 public:
437 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
438
439 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000440 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff9ed63f82012-09-06 17:37:28 +0000441
Stephen Hines651f13c2014-04-23 16:59:28 -0700442 void computeInfo(CGFunctionInfo &FI) const override;
443 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
444 CodeGenFunction &CGF) const override;
Derek Schuff9ed63f82012-09-06 17:37:28 +0000445};
446
447class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
448 public:
449 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
450 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
451};
452
453void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700454 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff9ed63f82012-09-06 17:37:28 +0000455 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
456
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700457 for (auto &I : FI.arguments())
458 I.info = classifyArgumentType(I.type);
459}
Derek Schuff9ed63f82012-09-06 17:37:28 +0000460
461llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
462 CodeGenFunction &CGF) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700463 return nullptr;
Derek Schuff9ed63f82012-09-06 17:37:28 +0000464}
465
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000466/// \brief Classify argument of given type \p Ty.
467ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff9ed63f82012-09-06 17:37:28 +0000468 if (isAggregateTypeForABI(Ty)) {
Mark Lacey23630722013-10-06 01:33:34 +0000469 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000470 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000471 return ABIArgInfo::getIndirect(0);
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000472 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
473 // Treat an enum type as its underlying type.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000474 Ty = EnumTy->getDecl()->getIntegerType();
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000475 } else if (Ty->isFloatingType()) {
476 // Floating-point types don't go inreg.
477 return ABIArgInfo::getDirect();
Derek Schuff9ed63f82012-09-06 17:37:28 +0000478 }
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000479
480 return (Ty->isPromotableIntegerType() ?
481 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff9ed63f82012-09-06 17:37:28 +0000482}
483
484ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
485 if (RetTy->isVoidType())
486 return ABIArgInfo::getIgnore();
487
Eli Benderskye45dfd12013-04-04 22:49:35 +0000488 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000489 if (isAggregateTypeForABI(RetTy))
490 return ABIArgInfo::getIndirect(0);
491
492 // Treat an enum type as its underlying type.
493 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
494 RetTy = EnumTy->getDecl()->getIntegerType();
495
496 return (RetTy->isPromotableIntegerType() ?
497 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
498}
499
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000500/// IsX86_MMXType - Return true if this is an MMX type.
501bool IsX86_MMXType(llvm::Type *IRType) {
502 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendlingbb465d72010-10-18 03:41:31 +0000503 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
504 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
505 IRType->getScalarSizeInBits() != 64;
506}
507
Jay Foadef6de3d2011-07-11 09:56:20 +0000508static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000509 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000510 llvm::Type* Ty) {
Tim Northover1bea6532013-06-07 00:04:50 +0000511 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
512 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
513 // Invalid MMX constraint
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700514 return nullptr;
Tim Northover1bea6532013-06-07 00:04:50 +0000515 }
516
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000517 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover1bea6532013-06-07 00:04:50 +0000518 }
519
520 // No operation needed
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000521 return Ty;
522}
523
Stephen Hines176edba2014-12-01 14:53:08 -0800524/// Returns true if this type can be passed in SSE registers with the
525/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
526static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
527 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
528 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
529 return true;
530 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
531 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
532 // registers specially.
533 unsigned VecSize = Context.getTypeSize(VT);
534 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
535 return true;
536 }
537 return false;
538}
539
540/// Returns true if this aggregate is small enough to be passed in SSE registers
541/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
542static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
543 return NumMembers <= 4;
544}
545
Chris Lattnerdce5ad02010-06-28 20:05:43 +0000546//===----------------------------------------------------------------------===//
547// X86-32 ABI Implementation
548//===----------------------------------------------------------------------===//
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000549
Stephen Hines651f13c2014-04-23 16:59:28 -0700550/// \brief Similar to llvm::CCState, but for Clang.
551struct CCState {
Stephen Hines176edba2014-12-01 14:53:08 -0800552 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700553
554 unsigned CC;
555 unsigned FreeRegs;
Stephen Hines176edba2014-12-01 14:53:08 -0800556 unsigned FreeSSERegs;
Stephen Hines651f13c2014-04-23 16:59:28 -0700557};
558
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000559/// X86_32ABIInfo - The X86-32 ABI information.
560class X86_32ABIInfo : public ABIInfo {
Rafael Espindolab48280b2012-07-31 02:44:24 +0000561 enum Class {
562 Integer,
563 Float
564 };
565
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000566 static const unsigned MinABIStackAlignInBytes = 4;
567
David Chisnall1e4249c2009-08-17 23:08:21 +0000568 bool IsDarwinVectorABI;
569 bool IsSmallStructInRegABI;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000570 bool IsWin32StructABI;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000571 unsigned DefaultNumRegisterParameters;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000572
573 static bool isRegisterSize(unsigned Size) {
574 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
575 }
576
Stephen Hines176edba2014-12-01 14:53:08 -0800577 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
578 // FIXME: Assumes vectorcall is in use.
579 return isX86VectorTypeForVectorCall(getContext(), Ty);
580 }
581
582 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
583 uint64_t NumMembers) const override {
584 // FIXME: Assumes vectorcall is in use.
585 return isX86VectorCallAggregateSmallEnough(NumMembers);
586 }
587
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700588 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000589
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000590 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
591 /// such that the argument will be passed in memory.
Stephen Hines651f13c2014-04-23 16:59:28 -0700592 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
593
594 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000595
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000596 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbare59d8582010-09-16 20:42:06 +0000597 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000598
Rafael Espindolab48280b2012-07-31 02:44:24 +0000599 Class classify(QualType Ty) const;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700600 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Stephen Hines651f13c2014-04-23 16:59:28 -0700601 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
602 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
603
604 /// \brief Rewrite the function info so that all memory arguments use
605 /// inalloca.
606 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
607
608 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
609 unsigned &StackOffset, ABIArgInfo &Info,
610 QualType Type) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000611
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000612public:
613
Stephen Hines651f13c2014-04-23 16:59:28 -0700614 void computeInfo(CGFunctionInfo &FI) const override;
615 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
616 CodeGenFunction &CGF) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000617
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000618 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindolab48280b2012-07-31 02:44:24 +0000619 unsigned r)
Eli Friedmanc3e0fb42011-07-08 23:31:17 +0000620 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000621 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000622};
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000623
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000624class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
625public:
Eli Friedman55fc7e22012-01-25 22:46:34 +0000626 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000627 bool d, bool p, bool w, unsigned r)
628 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis74f72932010-02-13 15:54:06 +0000629
John McCallb8b52972013-06-18 02:46:29 +0000630 static bool isStructReturnInRegABI(
631 const llvm::Triple &Triple, const CodeGenOptions &Opts);
632
Charles Davis74f72932010-02-13 15:54:06 +0000633 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -0700634 CodeGen::CodeGenModule &CGM) const override;
John McCall6374c332010-03-06 00:35:14 +0000635
Stephen Hines651f13c2014-04-23 16:59:28 -0700636 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall6374c332010-03-06 00:35:14 +0000637 // Darwin uses different dwarf register numbers for EH.
John McCall64aa4b32013-04-16 22:48:15 +0000638 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCall6374c332010-03-06 00:35:14 +0000639 return 4;
640 }
641
642 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -0700643 llvm::Value *Address) const override;
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000644
Jay Foadef6de3d2011-07-11 09:56:20 +0000645 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000646 StringRef Constraint,
Stephen Hines651f13c2014-04-23 16:59:28 -0700647 llvm::Type* Ty) const override {
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000648 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
649 }
650
Stephen Hines176edba2014-12-01 14:53:08 -0800651 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
652 std::string &Constraints,
653 std::vector<llvm::Type *> &ResultRegTypes,
654 std::vector<llvm::Type *> &ResultTruncRegTypes,
655 std::vector<LValue> &ResultRegDests,
656 std::string &AsmString,
657 unsigned NumOutputs) const override;
658
Stephen Hines651f13c2014-04-23 16:59:28 -0700659 llvm::Constant *
660 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb914e872013-10-20 21:29:19 +0000661 unsigned Sig = (0xeb << 0) | // jmp rel8
662 (0x06 << 8) | // .+0x08
663 ('F' << 16) |
664 ('T' << 24);
665 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
666 }
667
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700668 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
669 return true;
670 }
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000671};
672
673}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000674
Stephen Hines176edba2014-12-01 14:53:08 -0800675/// Rewrite input constraint references after adding some output constraints.
676/// In the case where there is one output and one input and we add one output,
677/// we need to replace all operand references greater than or equal to 1:
678/// mov $0, $1
679/// mov eax, $1
680/// The result will be:
681/// mov $0, $2
682/// mov eax, $2
683static void rewriteInputConstraintReferences(unsigned FirstIn,
684 unsigned NumNewOuts,
685 std::string &AsmString) {
686 std::string Buf;
687 llvm::raw_string_ostream OS(Buf);
688 size_t Pos = 0;
689 while (Pos < AsmString.size()) {
690 size_t DollarStart = AsmString.find('$', Pos);
691 if (DollarStart == std::string::npos)
692 DollarStart = AsmString.size();
693 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
694 if (DollarEnd == std::string::npos)
695 DollarEnd = AsmString.size();
696 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
697 Pos = DollarEnd;
698 size_t NumDollars = DollarEnd - DollarStart;
699 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
700 // We have an operand reference.
701 size_t DigitStart = Pos;
702 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
703 if (DigitEnd == std::string::npos)
704 DigitEnd = AsmString.size();
705 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
706 unsigned OperandIndex;
707 if (!OperandStr.getAsInteger(10, OperandIndex)) {
708 if (OperandIndex >= FirstIn)
709 OperandIndex += NumNewOuts;
710 OS << OperandIndex;
711 } else {
712 OS << OperandStr;
713 }
714 Pos = DigitEnd;
715 }
716 }
717 AsmString = std::move(OS.str());
718}
719
720/// Add output constraints for EAX:EDX because they are return registers.
721void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
722 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
723 std::vector<llvm::Type *> &ResultRegTypes,
724 std::vector<llvm::Type *> &ResultTruncRegTypes,
725 std::vector<LValue> &ResultRegDests, std::string &AsmString,
726 unsigned NumOutputs) const {
727 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
728
729 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
730 // larger.
731 if (!Constraints.empty())
732 Constraints += ',';
733 if (RetWidth <= 32) {
734 Constraints += "={eax}";
735 ResultRegTypes.push_back(CGF.Int32Ty);
736 } else {
737 // Use the 'A' constraint for EAX:EDX.
738 Constraints += "=A";
739 ResultRegTypes.push_back(CGF.Int64Ty);
740 }
741
742 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
743 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
744 ResultTruncRegTypes.push_back(CoerceTy);
745
746 // Coerce the integer by bitcasting the return slot pointer.
747 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
748 CoerceTy->getPointerTo()));
749 ResultRegDests.push_back(ReturnSlot);
750
751 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
752}
753
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000754/// shouldReturnTypeInRegister - Determine if the given type should be
755/// passed in a register (for the Darwin ABI).
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700756bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
757 ASTContext &Context) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000758 uint64_t Size = Context.getTypeSize(Ty);
759
760 // Type must be register sized.
761 if (!isRegisterSize(Size))
762 return false;
763
764 if (Ty->isVectorType()) {
765 // 64- and 128- bit vectors inside structures are not returned in
766 // registers.
767 if (Size == 64 || Size == 128)
768 return false;
769
770 return true;
771 }
772
Daniel Dunbar77115232010-05-15 00:00:30 +0000773 // If this is a builtin, pointer, enum, complex type, member pointer, or
774 // member function pointer it is ok.
Daniel Dunbara1842d32010-05-14 03:40:53 +0000775 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbar55e59e12009-09-24 05:12:36 +0000776 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar77115232010-05-15 00:00:30 +0000777 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000778 return true;
779
780 // Arrays are treated like records.
781 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700782 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000783
784 // Otherwise, it must be a record type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000785 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000786 if (!RT) return false;
787
Anders Carlssona8874232010-01-27 03:25:19 +0000788 // FIXME: Traverse bases here too.
789
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000790 // Structure types are passed in register if all fields would be
791 // passed in a register.
Stephen Hines651f13c2014-04-23 16:59:28 -0700792 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000793 // Empty fields are ignored.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000794 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000795 continue;
796
797 // Check fields recursively.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700798 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000799 return false;
800 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000801 return true;
802}
803
Stephen Hines651f13c2014-04-23 16:59:28 -0700804ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
805 // If the return value is indirect, then the hidden argument is consuming one
806 // integer register.
807 if (State.FreeRegs) {
808 --State.FreeRegs;
809 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
810 }
811 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
812}
813
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700814ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000815 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000816 return ABIArgInfo::getIgnore();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000817
Stephen Hines176edba2014-12-01 14:53:08 -0800818 const Type *Base = nullptr;
819 uint64_t NumElts = 0;
820 if (State.CC == llvm::CallingConv::X86_VectorCall &&
821 isHomogeneousAggregate(RetTy, Base, NumElts)) {
822 // The LLVM struct type for such an aggregate should lower properly.
823 return ABIArgInfo::getDirect();
824 }
825
Chris Lattnera3c109b2010-07-29 02:16:43 +0000826 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000827 // On Darwin, some vectors are returned in registers.
David Chisnall1e4249c2009-08-17 23:08:21 +0000828 if (IsDarwinVectorABI) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000829 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000830
831 // 128-bit vectors are a special case; they are returned in
832 // registers and we need to make sure to pick a type the LLVM
833 // backend will like.
834 if (Size == 128)
Chris Lattner800588f2010-07-29 06:26:06 +0000835 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattnera3c109b2010-07-29 02:16:43 +0000836 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000837
838 // Always return in register if it fits in a general purpose
839 // register, or if it is 64 bits and has a single element.
840 if ((Size == 8 || Size == 16 || Size == 32) ||
841 (Size == 64 && VT->getNumElements() == 1))
Chris Lattner800588f2010-07-29 06:26:06 +0000842 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +0000843 Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000844
Stephen Hines651f13c2014-04-23 16:59:28 -0700845 return getIndirectReturnResult(State);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000846 }
847
848 return ABIArgInfo::getDirect();
Chris Lattnera3c109b2010-07-29 02:16:43 +0000849 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000850
John McCalld608cdb2010-08-22 10:59:02 +0000851 if (isAggregateTypeForABI(RetTy)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000852 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson40092972009-10-20 22:07:59 +0000853 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000854 if (RT->getDecl()->hasFlexibleArrayMember())
Stephen Hines651f13c2014-04-23 16:59:28 -0700855 return getIndirectReturnResult(State);
Anders Carlsson40092972009-10-20 22:07:59 +0000856 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000857
David Chisnall1e4249c2009-08-17 23:08:21 +0000858 // If specified, structs and unions are always indirect.
859 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Stephen Hines651f13c2014-04-23 16:59:28 -0700860 return getIndirectReturnResult(State);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000861
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000862 // Small structures which are register sized are generally returned
863 // in a register.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700864 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000865 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000866
867 // As a special-case, if the struct is a "single-element" struct, and
868 // the field is of type "float" or "double", return it in a
Eli Friedman55fc7e22012-01-25 22:46:34 +0000869 // floating-point register. (MSVC does not apply this special case.)
870 // We apply a similar transformation for pointer types to improve the
871 // quality of the generated IR.
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000872 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000873 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedman55fc7e22012-01-25 22:46:34 +0000874 || SeltTy->hasPointerRepresentation())
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000875 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
876
877 // FIXME: We should be able to narrow this integer in cases with dead
878 // padding.
Chris Lattner800588f2010-07-29 06:26:06 +0000879 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000880 }
881
Stephen Hines651f13c2014-04-23 16:59:28 -0700882 return getIndirectReturnResult(State);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000883 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000884
Chris Lattnera3c109b2010-07-29 02:16:43 +0000885 // Treat an enum type as its underlying type.
886 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
887 RetTy = EnumTy->getDecl()->getIntegerType();
888
889 return (RetTy->isPromotableIntegerType() ?
890 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000891}
892
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000893static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
894 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
895}
896
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000897static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
898 const RecordType *RT = Ty->getAs<RecordType>();
899 if (!RT)
900 return 0;
901 const RecordDecl *RD = RT->getDecl();
902
903 // If this is a C++ record, check the bases first.
904 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Stephen Hines651f13c2014-04-23 16:59:28 -0700905 for (const auto &I : CXXRD->bases())
906 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000907 return false;
908
Stephen Hines651f13c2014-04-23 16:59:28 -0700909 for (const auto *i : RD->fields()) {
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000910 QualType FT = i->getType();
911
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000912 if (isSSEVectorType(Context, FT))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000913 return true;
914
915 if (isRecordWithSSEVectorType(Context, FT))
916 return true;
917 }
918
919 return false;
920}
921
Daniel Dunbare59d8582010-09-16 20:42:06 +0000922unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
923 unsigned Align) const {
924 // Otherwise, if the alignment is less than or equal to the minimum ABI
925 // alignment, just use the default; the backend will handle this.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000926 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbare59d8582010-09-16 20:42:06 +0000927 return 0; // Use default alignment.
928
929 // On non-Darwin, the stack type alignment is always 4.
930 if (!IsDarwinVectorABI) {
931 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000932 return MinABIStackAlignInBytes;
Daniel Dunbare59d8582010-09-16 20:42:06 +0000933 }
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000934
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000935 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000936 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
937 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000938 return 16;
939
940 return MinABIStackAlignInBytes;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000941}
942
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000943ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Stephen Hines651f13c2014-04-23 16:59:28 -0700944 CCState &State) const {
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000945 if (!ByVal) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700946 if (State.FreeRegs) {
947 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000948 return ABIArgInfo::getIndirectInReg(0, false);
949 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000950 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000951 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000952
Daniel Dunbare59d8582010-09-16 20:42:06 +0000953 // Compute the byval alignment.
954 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
955 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
956 if (StackAlign == 0)
Stephen Hines651f13c2014-04-23 16:59:28 -0700957 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbare59d8582010-09-16 20:42:06 +0000958
959 // If the stack alignment is less than the type alignment, realign the
960 // argument.
Stephen Hines651f13c2014-04-23 16:59:28 -0700961 bool Realign = TypeAlign > StackAlign;
962 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000963}
964
Rafael Espindolab48280b2012-07-31 02:44:24 +0000965X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
966 const Type *T = isSingleElementStruct(Ty, getContext());
967 if (!T)
968 T = Ty.getTypePtr();
969
970 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
971 BuiltinType::Kind K = BT->getKind();
972 if (K == BuiltinType::Float || K == BuiltinType::Double)
973 return Float;
974 }
975 return Integer;
976}
977
Stephen Hines651f13c2014-04-23 16:59:28 -0700978bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
979 bool &NeedsPadding) const {
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000980 NeedsPadding = false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000981 Class C = classify(Ty);
982 if (C == Float)
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000983 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000984
Rafael Espindolab6932692012-10-24 01:58:58 +0000985 unsigned Size = getContext().getTypeSize(Ty);
986 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindola5f14fcb2012-10-23 02:04:01 +0000987
988 if (SizeInRegs == 0)
989 return false;
990
Stephen Hines651f13c2014-04-23 16:59:28 -0700991 if (SizeInRegs > State.FreeRegs) {
992 State.FreeRegs = 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000993 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000994 }
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000995
Stephen Hines651f13c2014-04-23 16:59:28 -0700996 State.FreeRegs -= SizeInRegs;
Rafael Espindolab6932692012-10-24 01:58:58 +0000997
Stephen Hines176edba2014-12-01 14:53:08 -0800998 if (State.CC == llvm::CallingConv::X86_FastCall ||
999 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindolab6932692012-10-24 01:58:58 +00001000 if (Size > 32)
1001 return false;
1002
1003 if (Ty->isIntegralOrEnumerationType())
1004 return true;
1005
1006 if (Ty->isPointerType())
1007 return true;
1008
1009 if (Ty->isReferenceType())
1010 return true;
1011
Stephen Hines651f13c2014-04-23 16:59:28 -07001012 if (State.FreeRegs)
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001013 NeedsPadding = true;
1014
Rafael Espindolab6932692012-10-24 01:58:58 +00001015 return false;
1016 }
1017
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001018 return true;
Rafael Espindolab48280b2012-07-31 02:44:24 +00001019}
1020
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001021ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07001022 CCState &State) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001023 // FIXME: Set alignment on indirect arguments.
Daniel Dunbardc6d5742010-04-21 19:10:51 +00001024
Stephen Hines176edba2014-12-01 14:53:08 -08001025 Ty = useFirstFieldIfTransparentUnion(Ty);
1026
1027 // Check with the C++ ABI first.
1028 const RecordType *RT = Ty->getAs<RecordType>();
1029 if (RT) {
1030 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1031 if (RAA == CGCXXABI::RAA_Indirect) {
1032 return getIndirectResult(Ty, false, State);
1033 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1034 // The field index doesn't matter, we'll fix it up later.
1035 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1036 }
1037 }
1038
1039 // vectorcall adds the concept of a homogenous vector aggregate, similar
1040 // to other targets.
1041 const Type *Base = nullptr;
1042 uint64_t NumElts = 0;
1043 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1044 isHomogeneousAggregate(Ty, Base, NumElts)) {
1045 if (State.FreeSSERegs >= NumElts) {
1046 State.FreeSSERegs -= NumElts;
1047 if (Ty->isBuiltinType() || Ty->isVectorType())
1048 return ABIArgInfo::getDirect();
1049 return ABIArgInfo::getExpand();
1050 }
1051 return getIndirectResult(Ty, /*ByVal=*/false, State);
1052 }
1053
1054 if (isAggregateTypeForABI(Ty)) {
1055 if (RT) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001056 // Structs are always byval on win32, regardless of what they contain.
1057 if (IsWin32StructABI)
1058 return getIndirectResult(Ty, true, State);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001059
1060 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001061 if (RT->getDecl()->hasFlexibleArrayMember())
Stephen Hines651f13c2014-04-23 16:59:28 -07001062 return getIndirectResult(Ty, true, State);
Anders Carlssona8874232010-01-27 03:25:19 +00001063 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001064
Eli Friedman5a4d3522011-11-18 00:28:11 +00001065 // Ignore empty structs/unions.
Eli Friedman5a1ac892011-11-18 04:01:36 +00001066 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001067 return ABIArgInfo::getIgnore();
1068
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001069 llvm::LLVMContext &LLVMContext = getVMContext();
1070 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1071 bool NeedsPadding;
Stephen Hines651f13c2014-04-23 16:59:28 -07001072 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001073 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperb9bad792013-07-08 04:47:18 +00001074 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001075 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1076 return ABIArgInfo::getDirectInReg(Result);
1077 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001078 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001079
Daniel Dunbar53012f42009-11-09 01:33:53 +00001080 // Expand small (<= 128-bit) record types when we know that the stack layout
1081 // of those arguments will match the struct. This is important because the
1082 // LLVM backend isn't smart enough to remove byval, which inhibits many
1083 // optimizations.
Chris Lattnera3c109b2010-07-29 02:16:43 +00001084 if (getContext().getTypeSize(Ty) <= 4*32 &&
1085 canExpandIndirectArgument(Ty, getContext()))
Stephen Hines651f13c2014-04-23 16:59:28 -07001086 return ABIArgInfo::getExpandWithPadding(
Stephen Hines176edba2014-12-01 14:53:08 -08001087 State.CC == llvm::CallingConv::X86_FastCall ||
1088 State.CC == llvm::CallingConv::X86_VectorCall,
1089 PaddingType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001090
Stephen Hines651f13c2014-04-23 16:59:28 -07001091 return getIndirectResult(Ty, true, State);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001092 }
1093
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001094 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner7b733502010-08-26 20:08:43 +00001095 // On Darwin, some vectors are passed in memory, we handle this by passing
1096 // it as an i8/i16/i32/i64.
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001097 if (IsDarwinVectorABI) {
1098 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001099 if ((Size == 8 || Size == 16 || Size == 32) ||
1100 (Size == 64 && VT->getNumElements() == 1))
1101 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1102 Size));
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001103 }
Bill Wendlingbb465d72010-10-18 03:41:31 +00001104
Chad Rosier1f1df1f2013-03-25 21:00:27 +00001105 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1106 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001107
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001108 return ABIArgInfo::getDirect();
1109 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001110
1111
Chris Lattnera3c109b2010-07-29 02:16:43 +00001112 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1113 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001114
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001115 bool NeedsPadding;
Stephen Hines651f13c2014-04-23 16:59:28 -07001116 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001117
1118 if (Ty->isPromotableIntegerType()) {
1119 if (InReg)
1120 return ABIArgInfo::getExtendInReg();
1121 return ABIArgInfo::getExtend();
1122 }
1123 if (InReg)
1124 return ABIArgInfo::getDirectInReg();
1125 return ABIArgInfo::getDirect();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001126}
1127
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +00001128void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07001129 CCState State(FI.getCallingConvention());
1130 if (State.CC == llvm::CallingConv::X86_FastCall)
1131 State.FreeRegs = 2;
Stephen Hines176edba2014-12-01 14:53:08 -08001132 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1133 State.FreeRegs = 2;
1134 State.FreeSSERegs = 6;
1135 } else if (FI.getHasRegParm())
Stephen Hines651f13c2014-04-23 16:59:28 -07001136 State.FreeRegs = FI.getRegParm();
Rafael Espindolab6932692012-10-24 01:58:58 +00001137 else
Stephen Hines651f13c2014-04-23 16:59:28 -07001138 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindolab48280b2012-07-31 02:44:24 +00001139
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001140 if (!getCXXABI().classifyReturnType(FI)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001141 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001142 } else if (FI.getReturnInfo().isIndirect()) {
1143 // The C++ ABI is not aware of register usage, so we have to check if the
1144 // return value was sret and put it in a register ourselves if appropriate.
1145 if (State.FreeRegs) {
1146 --State.FreeRegs; // The sret parameter consumes a register.
1147 FI.getReturnInfo().setInReg(true);
1148 }
1149 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001150
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001151 // The chain argument effectively gives us another free register.
1152 if (FI.isChainCall())
1153 ++State.FreeRegs;
1154
Stephen Hines651f13c2014-04-23 16:59:28 -07001155 bool UsedInAlloca = false;
1156 for (auto &I : FI.arguments()) {
1157 I.info = classifyArgumentType(I.type, State);
1158 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001159 }
1160
Stephen Hines651f13c2014-04-23 16:59:28 -07001161 // If we needed to use inalloca for any argument, do a second pass and rewrite
1162 // all the memory arguments to use inalloca.
1163 if (UsedInAlloca)
1164 rewriteWithInAlloca(FI);
1165}
1166
1167void
1168X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1169 unsigned &StackOffset,
1170 ABIArgInfo &Info, QualType Type) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001171 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1172 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1173 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1174 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1175
Stephen Hines651f13c2014-04-23 16:59:28 -07001176 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1177 // byte aligned.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001178 if (StackOffset % 4U) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001179 unsigned OldOffset = StackOffset;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001180 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Stephen Hines651f13c2014-04-23 16:59:28 -07001181 unsigned NumBytes = StackOffset - OldOffset;
1182 assert(NumBytes);
1183 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1184 Ty = llvm::ArrayType::get(Ty, NumBytes);
1185 FrameFields.push_back(Ty);
1186 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001187}
1188
Stephen Hines176edba2014-12-01 14:53:08 -08001189static bool isArgInAlloca(const ABIArgInfo &Info) {
1190 // Leave ignored and inreg arguments alone.
1191 switch (Info.getKind()) {
1192 case ABIArgInfo::InAlloca:
1193 return true;
1194 case ABIArgInfo::Indirect:
1195 assert(Info.getIndirectByVal());
1196 return true;
1197 case ABIArgInfo::Ignore:
1198 return false;
1199 case ABIArgInfo::Direct:
1200 case ABIArgInfo::Extend:
1201 case ABIArgInfo::Expand:
1202 if (Info.getInReg())
1203 return false;
1204 return true;
1205 }
1206 llvm_unreachable("invalid enum");
1207}
1208
Stephen Hines651f13c2014-04-23 16:59:28 -07001209void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1210 assert(IsWin32StructABI && "inalloca only supported on win32");
1211
1212 // Build a packed struct type for all of the arguments in memory.
1213 SmallVector<llvm::Type *, 6> FrameFields;
1214
1215 unsigned StackOffset = 0;
Stephen Hines176edba2014-12-01 14:53:08 -08001216 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1217
1218 // Put 'this' into the struct before 'sret', if necessary.
1219 bool IsThisCall =
1220 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1221 ABIArgInfo &Ret = FI.getReturnInfo();
1222 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1223 isArgInAlloca(I->info)) {
1224 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1225 ++I;
1226 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001227
1228 // Put the sret parameter into the inalloca struct if it's in memory.
Stephen Hines651f13c2014-04-23 16:59:28 -07001229 if (Ret.isIndirect() && !Ret.getInReg()) {
1230 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1231 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1232 // On Windows, the hidden sret parameter is always returned in eax.
1233 Ret.setInAllocaSRet(IsWin32StructABI);
1234 }
1235
1236 // Skip the 'this' parameter in ecx.
Stephen Hines176edba2014-12-01 14:53:08 -08001237 if (IsThisCall)
Stephen Hines651f13c2014-04-23 16:59:28 -07001238 ++I;
1239
1240 // Put arguments passed in memory into the struct.
1241 for (; I != E; ++I) {
Stephen Hines176edba2014-12-01 14:53:08 -08001242 if (isArgInAlloca(I->info))
1243 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Stephen Hines651f13c2014-04-23 16:59:28 -07001244 }
1245
1246 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1247 /*isPacked=*/true));
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +00001248}
1249
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001250llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1251 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001252 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001253
1254 CGBuilderTy &Builder = CGF.Builder;
1255 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1256 "ap");
1257 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman7b1fb812011-11-18 02:12:09 +00001258
1259 // Compute if the address needs to be aligned
1260 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1261 Align = getTypeStackAlignInBytes(Ty, Align);
1262 Align = std::max(Align, 4U);
1263 if (Align > 4) {
1264 // addr = (addr + align - 1) & -align;
1265 llvm::Value *Offset =
1266 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1267 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1268 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1269 CGF.Int32Ty);
1270 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1271 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1272 Addr->getType(),
1273 "ap.cur.aligned");
1274 }
1275
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001276 llvm::Type *PTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001277 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001278 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1279
1280 uint64_t Offset =
Eli Friedman7b1fb812011-11-18 02:12:09 +00001281 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001282 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00001283 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001284 "ap.next");
1285 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1286
1287 return AddrTyped;
1288}
1289
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001290bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1291 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1292 assert(Triple.getArch() == llvm::Triple::x86);
1293
1294 switch (Opts.getStructReturnConvention()) {
1295 case CodeGenOptions::SRCK_Default:
1296 break;
1297 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1298 return false;
1299 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1300 return true;
1301 }
1302
1303 if (Triple.isOSDarwin())
1304 return true;
1305
1306 switch (Triple.getOS()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001307 case llvm::Triple::DragonFly:
1308 case llvm::Triple::FreeBSD:
1309 case llvm::Triple::OpenBSD:
1310 case llvm::Triple::Bitrig:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001311 case llvm::Triple::Win32:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001312 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001313 default:
1314 return false;
1315 }
1316}
1317
Charles Davis74f72932010-02-13 15:54:06 +00001318void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1319 llvm::GlobalValue *GV,
1320 CodeGen::CodeGenModule &CGM) const {
1321 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1322 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1323 // Get the LLVM function.
1324 llvm::Function *Fn = cast<llvm::Function>(GV);
1325
1326 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendling0d583392012-10-15 20:36:26 +00001327 llvm::AttrBuilder B;
Bill Wendlinge91e9ec2012-10-14 03:28:14 +00001328 B.addStackAlignmentAttr(16);
Bill Wendling909b6de2013-01-23 00:21:06 +00001329 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1330 llvm::AttributeSet::get(CGM.getLLVMContext(),
1331 llvm::AttributeSet::FunctionIndex,
1332 B));
Charles Davis74f72932010-02-13 15:54:06 +00001333 }
1334 }
1335}
1336
John McCall6374c332010-03-06 00:35:14 +00001337bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1338 CodeGen::CodeGenFunction &CGF,
1339 llvm::Value *Address) const {
1340 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCall6374c332010-03-06 00:35:14 +00001341
Chris Lattner8b418682012-02-07 00:39:47 +00001342 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001343
John McCall6374c332010-03-06 00:35:14 +00001344 // 0-7 are the eight integer registers; the order is different
1345 // on Darwin (for EH), but the range is the same.
1346 // 8 is %eip.
John McCallaeeb7012010-05-27 06:19:26 +00001347 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCall6374c332010-03-06 00:35:14 +00001348
John McCall64aa4b32013-04-16 22:48:15 +00001349 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCall6374c332010-03-06 00:35:14 +00001350 // 12-16 are st(0..4). Not sure why we stop at 4.
1351 // These have size 16, which is sizeof(long double) on
1352 // platforms with 8-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001353 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCallaeeb7012010-05-27 06:19:26 +00001354 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001355
John McCall6374c332010-03-06 00:35:14 +00001356 } else {
1357 // 9 is %eflags, which doesn't get a size on Darwin for some
1358 // reason.
1359 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1360
1361 // 11-16 are st(0..5). Not sure why we stop at 5.
1362 // These have size 12, which is sizeof(long double) on
1363 // platforms with 4-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001364 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCallaeeb7012010-05-27 06:19:26 +00001365 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1366 }
John McCall6374c332010-03-06 00:35:14 +00001367
1368 return false;
1369}
1370
Chris Lattnerdce5ad02010-06-28 20:05:43 +00001371//===----------------------------------------------------------------------===//
1372// X86-64 ABI Implementation
1373//===----------------------------------------------------------------------===//
1374
1375
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001376namespace {
1377/// X86_64ABIInfo - The X86_64 ABI information.
1378class X86_64ABIInfo : public ABIInfo {
1379 enum Class {
1380 Integer = 0,
1381 SSE,
1382 SSEUp,
1383 X87,
1384 X87Up,
1385 ComplexX87,
1386 NoClass,
1387 Memory
1388 };
1389
1390 /// merge - Implement the X86_64 ABI merging algorithm.
1391 ///
1392 /// Merge an accumulating classification \arg Accum with a field
1393 /// classification \arg Field.
1394 ///
1395 /// \param Accum - The accumulating classification. This should
1396 /// always be either NoClass or the result of a previous merge
1397 /// call. In addition, this should never be Memory (the caller
1398 /// should just return Memory for the aggregate).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001399 static Class merge(Class Accum, Class Field);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001400
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001401 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1402 ///
1403 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1404 /// final MEMORY or SSE classes when necessary.
1405 ///
1406 /// \param AggregateSize - The size of the current aggregate in
1407 /// the classification process.
1408 ///
1409 /// \param Lo - The classification for the parts of the type
1410 /// residing in the low word of the containing object.
1411 ///
1412 /// \param Hi - The classification for the parts of the type
1413 /// residing in the higher words of the containing object.
1414 ///
1415 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1416
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001417 /// classify - Determine the x86_64 register classes in which the
1418 /// given type T should be passed.
1419 ///
1420 /// \param Lo - The classification for the parts of the type
1421 /// residing in the low word of the containing object.
1422 ///
1423 /// \param Hi - The classification for the parts of the type
1424 /// residing in the high word of the containing object.
1425 ///
1426 /// \param OffsetBase - The bit offset of this type in the
1427 /// containing object. Some parameters are classified different
1428 /// depending on whether they straddle an eightbyte boundary.
1429 ///
Eli Friedman7a1b5862013-06-12 00:13:45 +00001430 /// \param isNamedArg - Whether the argument in question is a "named"
1431 /// argument, as used in AMD64-ABI 3.5.7.
1432 ///
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001433 /// If a word is unused its result will be NoClass; if a type should
1434 /// be passed in Memory then at least the classification of \arg Lo
1435 /// will be Memory.
1436 ///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001437 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001438 ///
1439 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1440 /// also be ComplexX87.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001441 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1442 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001443
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001444 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001445 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1446 unsigned IROffset, QualType SourceTy,
1447 unsigned SourceOffset) const;
1448 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1449 unsigned IROffset, QualType SourceTy,
1450 unsigned SourceOffset) const;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001451
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001452 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001453 /// such that the argument will be returned in memory.
Chris Lattner9c254f02010-06-29 06:01:59 +00001454 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001455
1456 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001457 /// such that the argument will be passed in memory.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001458 ///
1459 /// \param freeIntRegs - The number of free integer registers remaining
1460 /// available.
1461 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001462
Chris Lattnera3c109b2010-07-29 02:16:43 +00001463 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001464
Bill Wendlingbb465d72010-10-18 03:41:31 +00001465 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbaredfac032012-03-10 01:03:58 +00001466 unsigned freeIntRegs,
Bill Wendlingbb465d72010-10-18 03:41:31 +00001467 unsigned &neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001468 unsigned &neededSSE,
1469 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001470
Eli Friedmanee1ad992011-12-02 00:11:43 +00001471 bool IsIllegalVectorType(QualType Ty) const;
1472
John McCall67a57732011-04-21 01:20:55 +00001473 /// The 0.98 ABI revision clarified a lot of ambiguities,
1474 /// unfortunately in ways that were not always consistent with
1475 /// certain previous compilers. In particular, platforms which
1476 /// required strict binary compatibility with older versions of GCC
1477 /// may need to exempt themselves.
1478 bool honorsRevision0_98() const {
John McCall64aa4b32013-04-16 22:48:15 +00001479 return !getTarget().getTriple().isOSDarwin();
John McCall67a57732011-04-21 01:20:55 +00001480 }
1481
Eli Friedmanee1ad992011-12-02 00:11:43 +00001482 bool HasAVX;
Derek Schuffbabaf312012-10-11 15:52:22 +00001483 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1484 // 64-bit hardware.
1485 bool Has64BitPointers;
Eli Friedmanee1ad992011-12-02 00:11:43 +00001486
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001487public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001488 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffbabaf312012-10-11 15:52:22 +00001489 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff90da80c2012-10-11 18:21:13 +00001490 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001491 }
Chris Lattner9c254f02010-06-29 06:01:59 +00001492
John McCallde5d3c72012-02-17 03:33:10 +00001493 bool isPassedUsingAVXType(QualType type) const {
1494 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00001495 // The freeIntRegs argument doesn't matter here.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001496 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1497 /*isNamedArg*/true);
John McCallde5d3c72012-02-17 03:33:10 +00001498 if (info.isDirect()) {
1499 llvm::Type *ty = info.getCoerceToType();
1500 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1501 return (vectorTy->getBitWidth() > 128);
1502 }
1503 return false;
1504 }
1505
Stephen Hines651f13c2014-04-23 16:59:28 -07001506 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001507
Stephen Hines651f13c2014-04-23 16:59:28 -07001508 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1509 CodeGenFunction &CGF) const override;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001510
1511 bool has64BitPointers() const {
1512 return Has64BitPointers;
1513 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001514};
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001515
Chris Lattnerf13721d2010-08-31 16:44:54 +00001516/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001517class WinX86_64ABIInfo : public ABIInfo {
1518
Stephen Hines176edba2014-12-01 14:53:08 -08001519 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1520 bool IsReturnType) const;
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001521
Chris Lattnerf13721d2010-08-31 16:44:54 +00001522public:
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001523 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1524
Stephen Hines651f13c2014-04-23 16:59:28 -07001525 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001526
Stephen Hines651f13c2014-04-23 16:59:28 -07001527 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1528 CodeGenFunction &CGF) const override;
Stephen Hines176edba2014-12-01 14:53:08 -08001529
1530 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1531 // FIXME: Assumes vectorcall is in use.
1532 return isX86VectorTypeForVectorCall(getContext(), Ty);
1533 }
1534
1535 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1536 uint64_t NumMembers) const override {
1537 // FIXME: Assumes vectorcall is in use.
1538 return isX86VectorCallAggregateSmallEnough(NumMembers);
1539 }
Chris Lattnerf13721d2010-08-31 16:44:54 +00001540};
1541
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001542class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Stephen Hines176edba2014-12-01 14:53:08 -08001543 bool HasAVX;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001544public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001545 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Stephen Hines176edba2014-12-01 14:53:08 -08001546 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCall6374c332010-03-06 00:35:14 +00001547
John McCallde5d3c72012-02-17 03:33:10 +00001548 const X86_64ABIInfo &getABIInfo() const {
1549 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1550 }
1551
Stephen Hines651f13c2014-04-23 16:59:28 -07001552 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall6374c332010-03-06 00:35:14 +00001553 return 7;
1554 }
1555
1556 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07001557 llvm::Value *Address) const override {
Chris Lattner8b418682012-02-07 00:39:47 +00001558 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001559
John McCallaeeb7012010-05-27 06:19:26 +00001560 // 0-15 are the 16 integer registers.
1561 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001562 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCall6374c332010-03-06 00:35:14 +00001563 return false;
1564 }
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001565
Jay Foadef6de3d2011-07-11 09:56:20 +00001566 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001567 StringRef Constraint,
Stephen Hines651f13c2014-04-23 16:59:28 -07001568 llvm::Type* Ty) const override {
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001569 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1570 }
1571
John McCallde5d3c72012-02-17 03:33:10 +00001572 bool isNoProtoCallVariadic(const CallArgList &args,
Stephen Hines651f13c2014-04-23 16:59:28 -07001573 const FunctionNoProtoType *fnType) const override {
John McCall01f151e2011-09-21 08:08:30 +00001574 // The default CC on x86-64 sets %al to the number of SSA
1575 // registers used, and GCC sets this when calling an unprototyped
Eli Friedman3ed79032011-12-01 04:53:19 +00001576 // function, so we override the default behavior. However, don't do
Eli Friedman68805fe2011-12-06 03:08:26 +00001577 // that when AVX types are involved: the ABI explicitly states it is
1578 // undefined, and it doesn't work in practice because of how the ABI
1579 // defines varargs anyway.
Reid Kleckneref072032013-08-27 23:08:25 +00001580 if (fnType->getCallConv() == CC_C) {
Eli Friedman3ed79032011-12-01 04:53:19 +00001581 bool HasAVXType = false;
John McCallde5d3c72012-02-17 03:33:10 +00001582 for (CallArgList::const_iterator
1583 it = args.begin(), ie = args.end(); it != ie; ++it) {
1584 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1585 HasAVXType = true;
1586 break;
Eli Friedman3ed79032011-12-01 04:53:19 +00001587 }
1588 }
John McCallde5d3c72012-02-17 03:33:10 +00001589
Eli Friedman3ed79032011-12-01 04:53:19 +00001590 if (!HasAVXType)
1591 return true;
1592 }
John McCall01f151e2011-09-21 08:08:30 +00001593
John McCallde5d3c72012-02-17 03:33:10 +00001594 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCall01f151e2011-09-21 08:08:30 +00001595 }
1596
Stephen Hines651f13c2014-04-23 16:59:28 -07001597 llvm::Constant *
1598 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001599 unsigned Sig;
1600 if (getABIInfo().has64BitPointers())
1601 Sig = (0xeb << 0) | // jmp rel8
1602 (0x0a << 8) | // .+0x0c
1603 ('F' << 16) |
1604 ('T' << 24);
1605 else
1606 Sig = (0xeb << 0) | // jmp rel8
1607 (0x06 << 8) | // .+0x08
1608 ('F' << 16) |
1609 ('T' << 24);
Peter Collingbourneb914e872013-10-20 21:29:19 +00001610 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1611 }
1612
Stephen Hines176edba2014-12-01 14:53:08 -08001613 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1614 return HasAVX ? 32 : 16;
1615 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001616
1617 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
1618 return true;
1619 }
1620};
1621
1622class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1623public:
1624 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1625 : X86_64TargetCodeGenInfo(CGT, HasAVX) {}
1626
1627 void getDependentLibraryOption(llvm::StringRef Lib,
1628 llvm::SmallString<24> &Opt) const {
1629 Opt = "\01";
1630 Opt += Lib;
1631 }
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001632};
1633
Aaron Ballman89735b92013-05-24 15:06:56 +00001634static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001635 // If the argument does not end in .lib, automatically add the suffix.
1636 // If the argument contains a space, enclose it in quotes.
1637 // This matches the behavior of MSVC.
1638 bool Quote = (Lib.find(" ") != StringRef::npos);
1639 std::string ArgStr = Quote ? "\"" : "";
1640 ArgStr += Lib;
Rui Ueyama723cead2013-10-31 19:12:53 +00001641 if (!Lib.endswith_lower(".lib"))
Aaron Ballman89735b92013-05-24 15:06:56 +00001642 ArgStr += ".lib";
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001643 ArgStr += Quote ? "\"" : "";
Aaron Ballman89735b92013-05-24 15:06:56 +00001644 return ArgStr;
1645}
1646
Reid Kleckner3190ca92013-05-08 13:44:39 +00001647class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1648public:
John McCallb8b52972013-06-18 02:46:29 +00001649 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1650 bool d, bool p, bool w, unsigned RegParms)
1651 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Kleckner3190ca92013-05-08 13:44:39 +00001652
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001653 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1654 CodeGen::CodeGenModule &CGM) const override;
1655
Reid Kleckner3190ca92013-05-08 13:44:39 +00001656 void getDependentLibraryOption(llvm::StringRef Lib,
Stephen Hines651f13c2014-04-23 16:59:28 -07001657 llvm::SmallString<24> &Opt) const override {
Reid Kleckner3190ca92013-05-08 13:44:39 +00001658 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001659 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001660 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001661
1662 void getDetectMismatchOption(llvm::StringRef Name,
1663 llvm::StringRef Value,
Stephen Hines651f13c2014-04-23 16:59:28 -07001664 llvm::SmallString<32> &Opt) const override {
Eli Friedman572ac322013-06-07 22:42:22 +00001665 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001666 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001667};
1668
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001669static void addStackProbeSizeTargetAttribute(const Decl *D,
1670 llvm::GlobalValue *GV,
1671 CodeGen::CodeGenModule &CGM) {
1672 if (isa<FunctionDecl>(D)) {
1673 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1674 llvm::Function *Fn = cast<llvm::Function>(GV);
1675
1676 Fn->addFnAttr("stack-probe-size", llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
1677 }
1678 }
1679}
1680
1681void WinX86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1682 llvm::GlobalValue *GV,
1683 CodeGen::CodeGenModule &CGM) const {
1684 X86_32TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1685
1686 addStackProbeSizeTargetAttribute(D, GV, CGM);
1687}
1688
Chris Lattnerf13721d2010-08-31 16:44:54 +00001689class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Stephen Hines176edba2014-12-01 14:53:08 -08001690 bool HasAVX;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001691public:
Stephen Hines176edba2014-12-01 14:53:08 -08001692 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1693 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattnerf13721d2010-08-31 16:44:54 +00001694
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001695 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1696 CodeGen::CodeGenModule &CGM) const override;
1697
Stephen Hines651f13c2014-04-23 16:59:28 -07001698 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattnerf13721d2010-08-31 16:44:54 +00001699 return 7;
1700 }
1701
1702 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07001703 llvm::Value *Address) const override {
Chris Lattner8b418682012-02-07 00:39:47 +00001704 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001705
Chris Lattnerf13721d2010-08-31 16:44:54 +00001706 // 0-15 are the 16 integer registers.
1707 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001708 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattnerf13721d2010-08-31 16:44:54 +00001709 return false;
1710 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001711
1712 void getDependentLibraryOption(llvm::StringRef Lib,
Stephen Hines651f13c2014-04-23 16:59:28 -07001713 llvm::SmallString<24> &Opt) const override {
Reid Kleckner3190ca92013-05-08 13:44:39 +00001714 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001715 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001716 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001717
1718 void getDetectMismatchOption(llvm::StringRef Name,
1719 llvm::StringRef Value,
Stephen Hines651f13c2014-04-23 16:59:28 -07001720 llvm::SmallString<32> &Opt) const override {
Eli Friedman572ac322013-06-07 22:42:22 +00001721 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001722 }
Stephen Hines176edba2014-12-01 14:53:08 -08001723
1724 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1725 return HasAVX ? 32 : 16;
1726 }
Chris Lattnerf13721d2010-08-31 16:44:54 +00001727};
1728
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001729void WinX86_64TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1730 llvm::GlobalValue *GV,
1731 CodeGen::CodeGenModule &CGM) const {
1732 TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1733
1734 addStackProbeSizeTargetAttribute(D, GV, CGM);
1735}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001736}
1737
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001738void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1739 Class &Hi) const {
1740 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1741 //
1742 // (a) If one of the classes is Memory, the whole argument is passed in
1743 // memory.
1744 //
1745 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1746 // memory.
1747 //
1748 // (c) If the size of the aggregate exceeds two eightbytes and the first
1749 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1750 // argument is passed in memory. NOTE: This is necessary to keep the
1751 // ABI working for processors that don't support the __m256 type.
1752 //
1753 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1754 //
1755 // Some of these are enforced by the merging logic. Others can arise
1756 // only with unions; for example:
1757 // union { _Complex double; unsigned; }
1758 //
1759 // Note that clauses (b) and (c) were added in 0.98.
1760 //
1761 if (Hi == Memory)
1762 Lo = Memory;
1763 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1764 Lo = Memory;
1765 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1766 Lo = Memory;
1767 if (Hi == SSEUp && Lo != SSE)
1768 Hi = SSE;
1769}
1770
Chris Lattner1090a9b2010-06-28 21:43:59 +00001771X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001772 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1773 // classified recursively so that always two fields are
1774 // considered. The resulting class is calculated according to
1775 // the classes of the fields in the eightbyte:
1776 //
1777 // (a) If both classes are equal, this is the resulting class.
1778 //
1779 // (b) If one of the classes is NO_CLASS, the resulting class is
1780 // the other class.
1781 //
1782 // (c) If one of the classes is MEMORY, the result is the MEMORY
1783 // class.
1784 //
1785 // (d) If one of the classes is INTEGER, the result is the
1786 // INTEGER.
1787 //
1788 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1789 // MEMORY is used as class.
1790 //
1791 // (f) Otherwise class SSE is used.
1792
1793 // Accum should never be memory (we should have returned) or
1794 // ComplexX87 (because this cannot be passed in a structure).
1795 assert((Accum != Memory && Accum != ComplexX87) &&
1796 "Invalid accumulated classification during merge.");
1797 if (Accum == Field || Field == NoClass)
1798 return Accum;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001799 if (Field == Memory)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001800 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001801 if (Accum == NoClass)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001802 return Field;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001803 if (Accum == Integer || Field == Integer)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001804 return Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001805 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1806 Accum == X87 || Accum == X87Up)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001807 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001808 return SSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001809}
1810
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001811void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001812 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001813 // FIXME: This code can be simplified by introducing a simple value class for
1814 // Class pairs with appropriate constructor methods for the various
1815 // situations.
1816
1817 // FIXME: Some of the split computations are wrong; unaligned vectors
1818 // shouldn't be passed in registers for example, so there is no chance they
1819 // can straddle an eightbyte. Verify & simplify.
1820
1821 Lo = Hi = NoClass;
1822
1823 Class &Current = OffsetBase < 64 ? Lo : Hi;
1824 Current = Memory;
1825
John McCall183700f2009-09-21 23:43:11 +00001826 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001827 BuiltinType::Kind k = BT->getKind();
1828
1829 if (k == BuiltinType::Void) {
1830 Current = NoClass;
1831 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1832 Lo = Integer;
1833 Hi = Integer;
1834 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1835 Current = Integer;
Derek Schuff7da46f92012-10-11 16:55:58 +00001836 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1837 (k == BuiltinType::LongDouble &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001838 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001839 Current = SSE;
1840 } else if (k == BuiltinType::LongDouble) {
1841 Lo = X87;
1842 Hi = X87Up;
1843 }
1844 // FIXME: _Decimal32 and _Decimal64 are SSE.
1845 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001846 return;
1847 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001848
Chris Lattner1090a9b2010-06-28 21:43:59 +00001849 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001850 // Classify the underlying integer type.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001851 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattner1090a9b2010-06-28 21:43:59 +00001852 return;
1853 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001854
Chris Lattner1090a9b2010-06-28 21:43:59 +00001855 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001856 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001857 return;
1858 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001859
Chris Lattner1090a9b2010-06-28 21:43:59 +00001860 if (Ty->isMemberPointerType()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001861 if (Ty->isMemberFunctionPointerType()) {
1862 if (Has64BitPointers) {
1863 // If Has64BitPointers, this is an {i64, i64}, so classify both
1864 // Lo and Hi now.
1865 Lo = Hi = Integer;
1866 } else {
1867 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1868 // straddles an eightbyte boundary, Hi should be classified as well.
1869 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1870 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1871 if (EB_FuncPtr != EB_ThisAdj) {
1872 Lo = Hi = Integer;
1873 } else {
1874 Current = Integer;
1875 }
1876 }
1877 } else {
Daniel Dunbar67d438d2010-05-15 00:00:37 +00001878 Current = Integer;
Stephen Hines176edba2014-12-01 14:53:08 -08001879 }
Chris Lattner1090a9b2010-06-28 21:43:59 +00001880 return;
1881 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001882
Chris Lattner1090a9b2010-06-28 21:43:59 +00001883 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001884 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001885 if (Size == 32) {
1886 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1887 // float> as integer.
1888 Current = Integer;
1889
1890 // If this type crosses an eightbyte boundary, it should be
1891 // split.
1892 uint64_t EB_Real = (OffsetBase) / 64;
1893 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1894 if (EB_Real != EB_Imag)
1895 Hi = Lo;
1896 } else if (Size == 64) {
1897 // gcc passes <1 x double> in memory. :(
1898 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1899 return;
1900
1901 // gcc passes <1 x long long> as INTEGER.
Chris Lattner473f8e72010-08-26 18:03:20 +00001902 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner0fefa412010-08-26 18:13:50 +00001903 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1904 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1905 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001906 Current = Integer;
1907 else
1908 Current = SSE;
1909
1910 // If this type crosses an eightbyte boundary, it should be
1911 // split.
1912 if (OffsetBase && OffsetBase != 64)
1913 Hi = Lo;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001914 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001915 // Arguments of 256-bits are split into four eightbyte chunks. The
1916 // least significant one belongs to class SSE and all the others to class
1917 // SSEUP. The original Lo and Hi design considers that types can't be
1918 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1919 // This design isn't correct for 256-bits, but since there're no cases
1920 // where the upper parts would need to be inspected, avoid adding
1921 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001922 //
1923 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1924 // registers if they are "named", i.e. not part of the "..." of a
1925 // variadic function.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001926 Lo = SSE;
1927 Hi = SSEUp;
1928 }
Chris Lattner1090a9b2010-06-28 21:43:59 +00001929 return;
1930 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001931
Chris Lattner1090a9b2010-06-28 21:43:59 +00001932 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001933 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001934
Chris Lattnerea044322010-07-29 02:01:43 +00001935 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001936 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001937 if (Size <= 64)
1938 Current = Integer;
1939 else if (Size <= 128)
1940 Lo = Hi = Integer;
Chris Lattnerea044322010-07-29 02:01:43 +00001941 } else if (ET == getContext().FloatTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001942 Current = SSE;
Derek Schuff7da46f92012-10-11 16:55:58 +00001943 else if (ET == getContext().DoubleTy ||
1944 (ET == getContext().LongDoubleTy &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001945 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001946 Lo = Hi = SSE;
Chris Lattnerea044322010-07-29 02:01:43 +00001947 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001948 Current = ComplexX87;
1949
1950 // If this complex type crosses an eightbyte boundary then it
1951 // should be split.
1952 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattnerea044322010-07-29 02:01:43 +00001953 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001954 if (Hi == NoClass && EB_Real != EB_Imag)
1955 Hi = Lo;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001956
Chris Lattner1090a9b2010-06-28 21:43:59 +00001957 return;
1958 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001959
Chris Lattnerea044322010-07-29 02:01:43 +00001960 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001961 // Arrays are treated like structures.
1962
Chris Lattnerea044322010-07-29 02:01:43 +00001963 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001964
1965 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001966 // than four eightbytes, ..., it has class MEMORY.
1967 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001968 return;
1969
1970 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1971 // fields, it has class MEMORY.
1972 //
1973 // Only need to check alignment of array base.
Chris Lattnerea044322010-07-29 02:01:43 +00001974 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001975 return;
1976
1977 // Otherwise implement simplified merge. We could be smarter about
1978 // this, but it isn't worth it and would be harder to verify.
1979 Current = NoClass;
Chris Lattnerea044322010-07-29 02:01:43 +00001980 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001981 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes089d8922011-07-12 01:27:38 +00001982
1983 // The only case a 256-bit wide vector could be used is when the array
1984 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1985 // to work for sizes wider than 128, early check and fallback to memory.
1986 if (Size > 128 && EltSize != 256)
1987 return;
1988
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001989 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1990 Class FieldLo, FieldHi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001991 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001992 Lo = merge(Lo, FieldLo);
1993 Hi = merge(Hi, FieldHi);
1994 if (Lo == Memory || Hi == Memory)
1995 break;
1996 }
1997
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001998 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001999 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattner1090a9b2010-06-28 21:43:59 +00002000 return;
2001 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002002
Chris Lattner1090a9b2010-06-28 21:43:59 +00002003 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00002004 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002005
2006 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002007 // than four eightbytes, ..., it has class MEMORY.
2008 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002009 return;
2010
Anders Carlsson0a8f8472009-09-16 15:53:40 +00002011 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2012 // copy constructor or a non-trivial destructor, it is passed by invisible
2013 // reference.
Mark Lacey23630722013-10-06 01:33:34 +00002014 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson0a8f8472009-09-16 15:53:40 +00002015 return;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00002016
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002017 const RecordDecl *RD = RT->getDecl();
2018
2019 // Assume variable sized types are passed in memory.
2020 if (RD->hasFlexibleArrayMember())
2021 return;
2022
Chris Lattnerea044322010-07-29 02:01:43 +00002023 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002024
2025 // Reset Lo class, this will be recomputed.
2026 Current = NoClass;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00002027
2028 // If this is a C++ record, classify the bases first.
2029 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002030 for (const auto &I : CXXRD->bases()) {
2031 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbarce9f4232009-11-22 23:01:23 +00002032 "Unexpected base class!");
2033 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -07002034 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbarce9f4232009-11-22 23:01:23 +00002035
2036 // Classify this field.
2037 //
2038 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2039 // single eightbyte, each is classified separately. Each eightbyte gets
2040 // initialized to class NO_CLASS.
2041 Class FieldLo, FieldHi;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00002042 uint64_t Offset =
2043 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Stephen Hines651f13c2014-04-23 16:59:28 -07002044 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbarce9f4232009-11-22 23:01:23 +00002045 Lo = merge(Lo, FieldLo);
2046 Hi = merge(Hi, FieldHi);
2047 if (Lo == Memory || Hi == Memory)
2048 break;
2049 }
2050 }
2051
2052 // Classify the fields one at a time, merging the results.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002053 unsigned idx = 0;
Bruno Cardoso Lopes548e4782011-07-12 22:30:58 +00002054 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002055 i != e; ++i, ++idx) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002056 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2057 bool BitField = i->isBitField();
2058
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00002059 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2060 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002061 //
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00002062 // The only case a 256-bit wide vector could be used is when the struct
2063 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2064 // to work for sizes wider than 128, early check and fallback to memory.
2065 //
2066 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2067 Lo = Memory;
2068 return;
2069 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002070 // Note, skip this test for bit-fields, see below.
Chris Lattnerea044322010-07-29 02:01:43 +00002071 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002072 Lo = Memory;
2073 return;
2074 }
2075
2076 // Classify this field.
2077 //
2078 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2079 // exceeds a single eightbyte, each is classified
2080 // separately. Each eightbyte gets initialized to class
2081 // NO_CLASS.
2082 Class FieldLo, FieldHi;
2083
2084 // Bit-fields require special handling, they do not force the
2085 // structure to be passed in memory even if unaligned, and
2086 // therefore they can straddle an eightbyte.
2087 if (BitField) {
2088 // Ignore padding bit-fields.
2089 if (i->isUnnamedBitfield())
2090 continue;
2091
2092 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002093 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002094
2095 uint64_t EB_Lo = Offset / 64;
2096 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru9a6002a2013-10-06 09:54:18 +00002097
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002098 if (EB_Lo) {
2099 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2100 FieldLo = NoClass;
2101 FieldHi = Integer;
2102 } else {
2103 FieldLo = Integer;
2104 FieldHi = EB_Hi ? Integer : NoClass;
2105 }
2106 } else
Eli Friedman7a1b5862013-06-12 00:13:45 +00002107 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002108 Lo = merge(Lo, FieldLo);
2109 Hi = merge(Hi, FieldHi);
2110 if (Lo == Memory || Hi == Memory)
2111 break;
2112 }
2113
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002114 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002115 }
2116}
2117
Chris Lattner9c254f02010-06-29 06:01:59 +00002118ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00002119 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2120 // place naturally.
John McCalld608cdb2010-08-22 10:59:02 +00002121 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00002122 // Treat an enum type as its underlying type.
2123 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2124 Ty = EnumTy->getDecl()->getIntegerType();
2125
2126 return (Ty->isPromotableIntegerType() ?
2127 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2128 }
2129
2130 return ABIArgInfo::getIndirect(0);
2131}
2132
Eli Friedmanee1ad992011-12-02 00:11:43 +00002133bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2134 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2135 uint64_t Size = getContext().getTypeSize(VecTy);
2136 unsigned LargestVector = HasAVX ? 256 : 128;
2137 if (Size <= 64 || Size > LargestVector)
2138 return true;
2139 }
2140
2141 return false;
2142}
2143
Daniel Dunbaredfac032012-03-10 01:03:58 +00002144ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2145 unsigned freeIntRegs) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002146 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2147 // place naturally.
Daniel Dunbaredfac032012-03-10 01:03:58 +00002148 //
2149 // This assumption is optimistic, as there could be free registers available
2150 // when we need to pass this argument in memory, and LLVM could try to pass
2151 // the argument in the free register. This does not seem to happen currently,
2152 // but this code would be much safer if we could mark the argument with
2153 // 'onstack'. See PR12193.
Eli Friedmanee1ad992011-12-02 00:11:43 +00002154 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00002155 // Treat an enum type as its underlying type.
2156 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2157 Ty = EnumTy->getDecl()->getIntegerType();
2158
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00002159 return (Ty->isPromotableIntegerType() ?
2160 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00002161 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002162
Mark Lacey23630722013-10-06 01:33:34 +00002163 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002164 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00002165
Chris Lattner855d2272011-05-22 23:21:23 +00002166 // Compute the byval alignment. We specify the alignment of the byval in all
2167 // cases so that the mid-level optimizer knows the alignment of the byval.
2168 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbaredfac032012-03-10 01:03:58 +00002169
2170 // Attempt to avoid passing indirect results using byval when possible. This
2171 // is important for good codegen.
2172 //
2173 // We do this by coercing the value into a scalar type which the backend can
2174 // handle naturally (i.e., without using byval).
2175 //
2176 // For simplicity, we currently only do this when we have exhausted all of the
2177 // free integer registers. Doing this when there are free integer registers
2178 // would require more care, as we would have to ensure that the coerced value
2179 // did not claim the unused register. That would require either reording the
2180 // arguments to the function (so that any subsequent inreg values came first),
2181 // or only doing this optimization when there were no following arguments that
2182 // might be inreg.
2183 //
2184 // We currently expect it to be rare (particularly in well written code) for
2185 // arguments to be passed on the stack when there are still free integer
2186 // registers available (this would typically imply large structs being passed
2187 // by value), so this seems like a fair tradeoff for now.
2188 //
2189 // We can revisit this if the backend grows support for 'onstack' parameter
2190 // attributes. See PR12193.
2191 if (freeIntRegs == 0) {
2192 uint64_t Size = getContext().getTypeSize(Ty);
2193
2194 // If this type fits in an eightbyte, coerce it into the matching integral
2195 // type, which will end up on the stack (with alignment 8).
2196 if (Align == 8 && Size <= 64)
2197 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2198 Size));
2199 }
2200
Chris Lattner855d2272011-05-22 23:21:23 +00002201 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002202}
2203
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002204/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2205/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002206llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002207 // Wrapper structs/arrays that only contain vectors are passed just like
2208 // vectors; strip them off if present.
2209 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2210 Ty = QualType(InnerTy, 0);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002211
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002212 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002213
Bruno Cardoso Lopes528a8c72011-07-08 22:57:35 +00002214 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002215 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
2216 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002217 unsigned BitWidth = VT->getBitWidth();
Tanya Lattnerce275672011-11-28 23:18:11 +00002218 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner0f408f52010-07-29 04:56:46 +00002219 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
2220 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
2221 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
2222 EltTy->isIntegerTy(128)))
2223 return VT;
2224 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002225
Chris Lattner0f408f52010-07-29 04:56:46 +00002226 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
2227}
2228
Chris Lattnere2962be2010-07-29 07:30:00 +00002229/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2230/// is known to either be off the end of the specified type or being in
2231/// alignment padding. The user type specified is known to be at most 128 bits
2232/// in size, and have passed through X86_64ABIInfo::classify with a successful
2233/// classification that put one of the two halves in the INTEGER class.
2234///
2235/// It is conservatively correct to return false.
2236static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2237 unsigned EndBit, ASTContext &Context) {
2238 // If the bytes being queried are off the end of the type, there is no user
2239 // data hiding here. This handles analysis of builtins, vectors and other
2240 // types that don't contain interesting padding.
2241 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2242 if (TySize <= StartBit)
2243 return true;
2244
Chris Lattner021c3a32010-07-29 07:43:55 +00002245 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2246 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2247 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2248
2249 // Check each element to see if the element overlaps with the queried range.
2250 for (unsigned i = 0; i != NumElts; ++i) {
2251 // If the element is after the span we care about, then we're done..
2252 unsigned EltOffset = i*EltSize;
2253 if (EltOffset >= EndBit) break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002254
Chris Lattner021c3a32010-07-29 07:43:55 +00002255 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2256 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2257 EndBit-EltOffset, Context))
2258 return false;
2259 }
2260 // If it overlaps no elements, then it is safe to process as padding.
2261 return true;
2262 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002263
Chris Lattnere2962be2010-07-29 07:30:00 +00002264 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2265 const RecordDecl *RD = RT->getDecl();
2266 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002267
Chris Lattnere2962be2010-07-29 07:30:00 +00002268 // If this is a C++ record, check the bases first.
2269 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002270 for (const auto &I : CXXRD->bases()) {
2271 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnere2962be2010-07-29 07:30:00 +00002272 "Unexpected base class!");
2273 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -07002274 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002275
Chris Lattnere2962be2010-07-29 07:30:00 +00002276 // If the base is after the span we care about, ignore it.
Benjamin Kramerd4f51982012-07-04 18:45:14 +00002277 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnere2962be2010-07-29 07:30:00 +00002278 if (BaseOffset >= EndBit) continue;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002279
Chris Lattnere2962be2010-07-29 07:30:00 +00002280 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Stephen Hines651f13c2014-04-23 16:59:28 -07002281 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnere2962be2010-07-29 07:30:00 +00002282 EndBit-BaseOffset, Context))
2283 return false;
2284 }
2285 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002286
Chris Lattnere2962be2010-07-29 07:30:00 +00002287 // Verify that no field has data that overlaps the region of interest. Yes
2288 // this could be sped up a lot by being smarter about queried fields,
2289 // however we're only looking at structs up to 16 bytes, so we don't care
2290 // much.
2291 unsigned idx = 0;
2292 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2293 i != e; ++i, ++idx) {
2294 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002295
Chris Lattnere2962be2010-07-29 07:30:00 +00002296 // If we found a field after the region we care about, then we're done.
2297 if (FieldOffset >= EndBit) break;
2298
2299 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2300 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2301 Context))
2302 return false;
2303 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002304
Chris Lattnere2962be2010-07-29 07:30:00 +00002305 // If nothing in this record overlapped the area of interest, then we're
2306 // clean.
2307 return true;
2308 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002309
Chris Lattnere2962be2010-07-29 07:30:00 +00002310 return false;
2311}
2312
Chris Lattner0b362002010-07-29 18:39:32 +00002313/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2314/// float member at the specified offset. For example, {int,{float}} has a
2315/// float at offset 4. It is conservatively correct for this routine to return
2316/// false.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002317static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmow25a6a842012-10-08 16:25:52 +00002318 const llvm::DataLayout &TD) {
Chris Lattner0b362002010-07-29 18:39:32 +00002319 // Base case if we find a float.
2320 if (IROffset == 0 && IRType->isFloatTy())
2321 return true;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002322
Chris Lattner0b362002010-07-29 18:39:32 +00002323 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002324 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner0b362002010-07-29 18:39:32 +00002325 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2326 unsigned Elt = SL->getElementContainingOffset(IROffset);
2327 IROffset -= SL->getElementOffset(Elt);
2328 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2329 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002330
Chris Lattner0b362002010-07-29 18:39:32 +00002331 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002332 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2333 llvm::Type *EltTy = ATy->getElementType();
Chris Lattner0b362002010-07-29 18:39:32 +00002334 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2335 IROffset -= IROffset/EltSize*EltSize;
2336 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2337 }
2338
2339 return false;
2340}
2341
Chris Lattnerf47c9442010-07-29 18:13:09 +00002342
2343/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2344/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002345llvm::Type *X86_64ABIInfo::
2346GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattnerf47c9442010-07-29 18:13:09 +00002347 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnercba8d312010-07-29 18:19:50 +00002348 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattnerf47c9442010-07-29 18:13:09 +00002349 // pass as float if the last 4 bytes is just padding. This happens for
2350 // structs that contain 3 floats.
2351 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2352 SourceOffset*8+64, getContext()))
2353 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002354
Chris Lattner0b362002010-07-29 18:39:32 +00002355 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2356 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2357 // case.
Micah Villmow25a6a842012-10-08 16:25:52 +00002358 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2359 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner22fd4ba2010-08-25 23:39:14 +00002360 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002361
Chris Lattnerf47c9442010-07-29 18:13:09 +00002362 return llvm::Type::getDoubleTy(getVMContext());
2363}
2364
2365
Chris Lattner0d2656d2010-07-29 17:40:35 +00002366/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2367/// an 8-byte GPR. This means that we either have a scalar or we are talking
2368/// about the high or low part of an up-to-16-byte struct. This routine picks
2369/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattner49382de2010-07-28 22:44:07 +00002370/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2371/// etc).
2372///
2373/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2374/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2375/// the 8-byte value references. PrefType may be null.
2376///
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002377/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattner49382de2010-07-28 22:44:07 +00002378/// an offset into this that we're processing (which is always either 0 or 8).
2379///
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002380llvm::Type *X86_64ABIInfo::
2381GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner0d2656d2010-07-29 17:40:35 +00002382 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnere2962be2010-07-29 07:30:00 +00002383 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2384 // returning an 8-byte unit starting with it. See if we can safely use it.
2385 if (IROffset == 0) {
2386 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffbabaf312012-10-11 15:52:22 +00002387 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2388 IRType->isIntegerTy(64))
Chris Lattnere2962be2010-07-29 07:30:00 +00002389 return IRType;
Chris Lattner49382de2010-07-28 22:44:07 +00002390
Chris Lattnere2962be2010-07-29 07:30:00 +00002391 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2392 // goodness in the source type is just tail padding. This is allowed to
2393 // kick in for struct {double,int} on the int, but not on
2394 // struct{double,int,int} because we wouldn't return the second int. We
2395 // have to do this analysis on the source type because we can't depend on
2396 // unions being lowered a specific way etc.
2397 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffbabaf312012-10-11 15:52:22 +00002398 IRType->isIntegerTy(32) ||
2399 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2400 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2401 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002402
Chris Lattnere2962be2010-07-29 07:30:00 +00002403 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2404 SourceOffset*8+64, getContext()))
2405 return IRType;
2406 }
2407 }
Chris Lattner49382de2010-07-28 22:44:07 +00002408
Chris Lattner2acc6e32011-07-18 04:24:23 +00002409 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner49382de2010-07-28 22:44:07 +00002410 // If this is a struct, recurse into the field at the specified offset.
Micah Villmow25a6a842012-10-08 16:25:52 +00002411 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattner49382de2010-07-28 22:44:07 +00002412 if (IROffset < SL->getSizeInBytes()) {
2413 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2414 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002415
Chris Lattner0d2656d2010-07-29 17:40:35 +00002416 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2417 SourceTy, SourceOffset);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002418 }
Chris Lattner49382de2010-07-28 22:44:07 +00002419 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002420
Chris Lattner2acc6e32011-07-18 04:24:23 +00002421 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002422 llvm::Type *EltTy = ATy->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00002423 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner021c3a32010-07-29 07:43:55 +00002424 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner0d2656d2010-07-29 17:40:35 +00002425 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2426 SourceOffset);
Chris Lattner021c3a32010-07-29 07:43:55 +00002427 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002428
Chris Lattner49382de2010-07-28 22:44:07 +00002429 // Okay, we don't have any better idea of what to pass, so we pass this in an
2430 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002431 unsigned TySizeInBytes =
2432 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattner49382de2010-07-28 22:44:07 +00002433
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002434 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002435
Chris Lattner49382de2010-07-28 22:44:07 +00002436 // It is always safe to classify this as an integer type up to i64 that
2437 // isn't larger than the structure.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002438 return llvm::IntegerType::get(getVMContext(),
2439 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner9c254f02010-06-29 06:01:59 +00002440}
2441
Chris Lattner66e7b682010-09-01 00:50:20 +00002442
2443/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2444/// be used as elements of a two register pair to pass or return, return a
2445/// first class aggregate to represent them. For example, if the low part of
2446/// a by-value argument should be passed as i32* and the high part as float,
2447/// return {i32*, float}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002448static llvm::Type *
Jay Foadef6de3d2011-07-11 09:56:20 +00002449GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmow25a6a842012-10-08 16:25:52 +00002450 const llvm::DataLayout &TD) {
Chris Lattner66e7b682010-09-01 00:50:20 +00002451 // In order to correctly satisfy the ABI, we need to the high part to start
2452 // at offset 8. If the high and low parts we inferred are both 4-byte types
2453 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2454 // the second element at offset 8. Check for this:
2455 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2456 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Stephen Hines176edba2014-12-01 14:53:08 -08002457 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattner66e7b682010-09-01 00:50:20 +00002458 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002459
Chris Lattner66e7b682010-09-01 00:50:20 +00002460 // To handle this, we have to increase the size of the low part so that the
2461 // second element will start at an 8 byte offset. We can't increase the size
2462 // of the second element because it might make us access off the end of the
2463 // struct.
2464 if (HiStart != 8) {
2465 // There are only two sorts of types the ABI generation code can produce for
2466 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2467 // Promote these to a larger type.
2468 if (Lo->isFloatTy())
2469 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2470 else {
2471 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2472 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2473 }
2474 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002475
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002476 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002477
2478
Chris Lattner66e7b682010-09-01 00:50:20 +00002479 // Verify that the second element is at an 8-byte offset.
2480 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2481 "Invalid x86-64 argument pair!");
2482 return Result;
2483}
2484
Chris Lattner519f68c2010-07-28 23:06:14 +00002485ABIArgInfo X86_64ABIInfo::
Chris Lattnera3c109b2010-07-29 02:16:43 +00002486classifyReturnType(QualType RetTy) const {
Chris Lattner519f68c2010-07-28 23:06:14 +00002487 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2488 // classification algorithm.
2489 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002490 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner519f68c2010-07-28 23:06:14 +00002491
2492 // Check some invariants.
2493 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002494 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2495
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002496 llvm::Type *ResType = nullptr;
Chris Lattner519f68c2010-07-28 23:06:14 +00002497 switch (Lo) {
2498 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002499 if (Hi == NoClass)
2500 return ABIArgInfo::getIgnore();
2501 // If the low part is just padding, it takes no register, leave ResType
2502 // null.
2503 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2504 "Unknown missing lo part");
2505 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002506
2507 case SSEUp:
2508 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002509 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002510
2511 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2512 // hidden argument.
2513 case Memory:
2514 return getIndirectReturnResult(RetTy);
2515
2516 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2517 // available register of the sequence %rax, %rdx is used.
2518 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002519 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002520
Chris Lattnereb518b42010-07-29 21:42:50 +00002521 // If we have a sign or zero extended integer, make sure to return Extend
2522 // so that the parameter gets the right LLVM IR attributes.
2523 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2524 // Treat an enum type as its underlying type.
2525 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2526 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002527
Chris Lattnereb518b42010-07-29 21:42:50 +00002528 if (RetTy->isIntegralOrEnumerationType() &&
2529 RetTy->isPromotableIntegerType())
2530 return ABIArgInfo::getExtend();
2531 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002532 break;
2533
2534 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2535 // available SSE register of the sequence %xmm0, %xmm1 is used.
2536 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002537 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattner0b30c672010-07-28 23:12:33 +00002538 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002539
2540 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2541 // returned on the X87 stack in %st0 as 80-bit x87 number.
2542 case X87:
Chris Lattnerea044322010-07-29 02:01:43 +00002543 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattner0b30c672010-07-28 23:12:33 +00002544 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002545
2546 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2547 // part of the value is returned in %st0 and the imaginary part in
2548 // %st1.
2549 case ComplexX87:
2550 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner7650d952011-06-18 22:49:11 +00002551 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattnerea044322010-07-29 02:01:43 +00002552 llvm::Type::getX86_FP80Ty(getVMContext()),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002553 nullptr);
Chris Lattner519f68c2010-07-28 23:06:14 +00002554 break;
2555 }
2556
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002557 llvm::Type *HighPart = nullptr;
Chris Lattner519f68c2010-07-28 23:06:14 +00002558 switch (Hi) {
2559 // Memory was handled previously and X87 should
2560 // never occur as a hi class.
2561 case Memory:
2562 case X87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002563 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002564
2565 case ComplexX87: // Previously handled.
Chris Lattner0b30c672010-07-28 23:12:33 +00002566 case NoClass:
2567 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002568
Chris Lattner3db4dde2010-09-01 00:20:33 +00002569 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002570 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002571 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2572 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002573 break;
Chris Lattner3db4dde2010-09-01 00:20:33 +00002574 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002575 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002576 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2577 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002578 break;
2579
2580 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002581 // is passed in the next available eightbyte chunk if the last used
2582 // vector register.
Chris Lattner519f68c2010-07-28 23:06:14 +00002583 //
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002584 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner519f68c2010-07-28 23:06:14 +00002585 case SSEUp:
2586 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002587 ResType = GetByteVectorType(RetTy);
Chris Lattner519f68c2010-07-28 23:06:14 +00002588 break;
2589
2590 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2591 // returned together with the previous X87 value in %st0.
2592 case X87Up:
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002593 // If X87Up is preceded by X87, we don't need to do
Chris Lattner519f68c2010-07-28 23:06:14 +00002594 // anything. However, in some cases with unions it may not be
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002595 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner519f68c2010-07-28 23:06:14 +00002596 // extra bits in an SSE reg.
Chris Lattner603519d2010-07-29 17:49:08 +00002597 if (Lo != X87) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002598 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002599 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2600 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner603519d2010-07-29 17:49:08 +00002601 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002602 break;
2603 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002604
Chris Lattner3db4dde2010-09-01 00:20:33 +00002605 // If a high part was specified, merge it together with the low part. It is
Chris Lattner645406a2010-09-01 00:24:35 +00002606 // known to pass in the high eightbyte of the result. We do this by forming a
2607 // first class struct aggregate with the high and low part: {low, high}
Chris Lattner66e7b682010-09-01 00:50:20 +00002608 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002609 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner519f68c2010-07-28 23:06:14 +00002610
Chris Lattnereb518b42010-07-29 21:42:50 +00002611 return ABIArgInfo::getDirect(ResType);
Chris Lattner519f68c2010-07-28 23:06:14 +00002612}
2613
Daniel Dunbaredfac032012-03-10 01:03:58 +00002614ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman7a1b5862013-06-12 00:13:45 +00002615 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2616 bool isNamedArg)
Daniel Dunbaredfac032012-03-10 01:03:58 +00002617 const
2618{
Stephen Hines176edba2014-12-01 14:53:08 -08002619 Ty = useFirstFieldIfTransparentUnion(Ty);
2620
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002621 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002622 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002623
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002624 // Check some invariants.
2625 // FIXME: Enforce these by construction.
2626 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002627 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2628
2629 neededInt = 0;
2630 neededSSE = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002631 llvm::Type *ResType = nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002632 switch (Lo) {
2633 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002634 if (Hi == NoClass)
2635 return ABIArgInfo::getIgnore();
2636 // If the low part is just padding, it takes no register, leave ResType
2637 // null.
2638 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2639 "Unknown missing lo part");
2640 break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002641
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002642 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2643 // on the stack.
2644 case Memory:
2645
2646 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2647 // COMPLEX_X87, it is passed in memory.
2648 case X87:
2649 case ComplexX87:
Mark Lacey23630722013-10-06 01:33:34 +00002650 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedmanded137f2011-06-29 07:04:55 +00002651 ++neededInt;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002652 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002653
2654 case SSEUp:
2655 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002656 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002657
2658 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2659 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2660 // and %r9 is used.
2661 case Integer:
Chris Lattner9c254f02010-06-29 06:01:59 +00002662 ++neededInt;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002663
Chris Lattner49382de2010-07-28 22:44:07 +00002664 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002665 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattnereb518b42010-07-29 21:42:50 +00002666
2667 // If we have a sign or zero extended integer, make sure to return Extend
2668 // so that the parameter gets the right LLVM IR attributes.
2669 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2670 // Treat an enum type as its underlying type.
2671 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2672 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002673
Chris Lattnereb518b42010-07-29 21:42:50 +00002674 if (Ty->isIntegralOrEnumerationType() &&
2675 Ty->isPromotableIntegerType())
2676 return ABIArgInfo::getExtend();
2677 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002678
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002679 break;
2680
2681 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2682 // available SSE register is used, the registers are taken in the
2683 // order from %xmm0 to %xmm7.
Bill Wendlingbb465d72010-10-18 03:41:31 +00002684 case SSE: {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002685 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman14508ff2011-07-02 00:57:27 +00002686 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling99aaae82010-10-18 23:51:38 +00002687 ++neededSSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002688 break;
2689 }
Bill Wendlingbb465d72010-10-18 03:41:31 +00002690 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002691
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002692 llvm::Type *HighPart = nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002693 switch (Hi) {
2694 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002695 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002696 // which is passed in memory.
2697 case Memory:
2698 case X87:
2699 case ComplexX87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002700 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002701
2702 case NoClass: break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002703
Chris Lattner645406a2010-09-01 00:24:35 +00002704 case Integer:
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002705 ++neededInt;
Chris Lattner49382de2010-07-28 22:44:07 +00002706 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002707 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002708
Chris Lattner645406a2010-09-01 00:24:35 +00002709 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2710 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002711 break;
2712
2713 // X87Up generally doesn't occur here (long double is passed in
2714 // memory), except in situations involving unions.
2715 case X87Up:
Chris Lattner645406a2010-09-01 00:24:35 +00002716 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002717 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002718
Chris Lattner645406a2010-09-01 00:24:35 +00002719 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2720 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner117e3f42010-07-30 04:02:24 +00002721
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002722 ++neededSSE;
2723 break;
2724
2725 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2726 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002727 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002728 case SSEUp:
Chris Lattnerab5722e2010-07-28 23:47:21 +00002729 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002730 ResType = GetByteVectorType(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002731 break;
2732 }
2733
Chris Lattner645406a2010-09-01 00:24:35 +00002734 // If a high part was specified, merge it together with the low part. It is
2735 // known to pass in the high eightbyte of the result. We do this by forming a
2736 // first class struct aggregate with the high and low part: {low, high}
2737 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002738 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002739
Chris Lattnereb518b42010-07-29 21:42:50 +00002740 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002741}
2742
Chris Lattneree5dcd02010-07-29 02:31:05 +00002743void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002744
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002745 if (!getCXXABI().classifyReturnType(FI))
2746 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002747
2748 // Keep track of the number of assigned registers.
Bill Wendling99aaae82010-10-18 23:51:38 +00002749 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002750
2751 // If the return value is indirect, then the hidden argument is consuming one
2752 // integer register.
2753 if (FI.getReturnInfo().isIndirect())
2754 --freeIntRegs;
2755
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002756 // The chain argument effectively gives us another free register.
2757 if (FI.isChainCall())
2758 ++freeIntRegs;
2759
Stephen Hines176edba2014-12-01 14:53:08 -08002760 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002761 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2762 // get assigned (in left-to-right order) for passing as follows...
Stephen Hines176edba2014-12-01 14:53:08 -08002763 unsigned ArgNo = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002764 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Stephen Hines176edba2014-12-01 14:53:08 -08002765 it != ie; ++it, ++ArgNo) {
2766 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002767
Bill Wendling99aaae82010-10-18 23:51:38 +00002768 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002769 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Stephen Hines176edba2014-12-01 14:53:08 -08002770 neededSSE, IsNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002771
2772 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2773 // eightbyte of an argument, the whole argument is passed on the
2774 // stack. If registers have already been assigned for some
2775 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling99aaae82010-10-18 23:51:38 +00002776 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002777 freeIntRegs -= neededInt;
2778 freeSSERegs -= neededSSE;
2779 } else {
Daniel Dunbaredfac032012-03-10 01:03:58 +00002780 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002781 }
2782 }
2783}
2784
2785static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2786 QualType Ty,
2787 CodeGenFunction &CGF) {
2788 llvm::Value *overflow_arg_area_p =
2789 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2790 llvm::Value *overflow_arg_area =
2791 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2792
2793 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2794 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedman8d2fe422011-11-18 02:44:19 +00002795 // It isn't stated explicitly in the standard, but in practice we use
2796 // alignment greater than 16 where necessary.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002797 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2798 if (Align > 8) {
Eli Friedman8d2fe422011-11-18 02:44:19 +00002799 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson0032b272009-08-13 21:57:51 +00002800 llvm::Value *Offset =
Eli Friedman8d2fe422011-11-18 02:44:19 +00002801 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002802 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2803 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner77b89b82010-06-27 07:15:29 +00002804 CGF.Int64Ty);
Eli Friedman8d2fe422011-11-18 02:44:19 +00002805 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002806 overflow_arg_area =
2807 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2808 overflow_arg_area->getType(),
2809 "overflow_arg_area.align");
2810 }
2811
2812 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002813 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002814 llvm::Value *Res =
2815 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002816 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002817
2818 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2819 // l->overflow_arg_area + sizeof(type).
2820 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2821 // an 8 byte boundary.
2822
2823 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson0032b272009-08-13 21:57:51 +00002824 llvm::Value *Offset =
Chris Lattner77b89b82010-06-27 07:15:29 +00002825 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002826 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2827 "overflow_arg_area.next");
2828 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2829
2830 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2831 return Res;
2832}
2833
2834llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2835 CodeGenFunction &CGF) const {
2836 // Assume that va_list type is correct; should be pointer to LLVM type:
2837 // struct {
2838 // i32 gp_offset;
2839 // i32 fp_offset;
2840 // i8* overflow_arg_area;
2841 // i8* reg_save_area;
2842 // };
Bill Wendling99aaae82010-10-18 23:51:38 +00002843 unsigned neededInt, neededSSE;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002844
Chris Lattnera14db752010-03-11 18:19:55 +00002845 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002846 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2847 /*isNamedArg*/false);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002848
2849 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2850 // in the registers. If not go to step 7.
2851 if (!neededInt && !neededSSE)
2852 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2853
2854 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2855 // general purpose registers needed to pass type and num_fp to hold
2856 // the number of floating point registers needed.
2857
2858 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2859 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2860 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2861 //
2862 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2863 // register save space).
2864
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002865 llvm::Value *InRegs = nullptr;
2866 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2867 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002868 if (neededInt) {
2869 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2870 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattner1090a9b2010-06-28 21:43:59 +00002871 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2872 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002873 }
2874
2875 if (neededSSE) {
2876 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2877 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2878 llvm::Value *FitsInFP =
Chris Lattner1090a9b2010-06-28 21:43:59 +00002879 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2880 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002881 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2882 }
2883
2884 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2885 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2886 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2887 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2888
2889 // Emit code to load the value if it was passed in registers.
2890
2891 CGF.EmitBlock(InRegBlock);
2892
2893 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2894 // an offset of l->gp_offset and/or l->fp_offset. This may require
2895 // copying to a temporary location in case the parameter is passed
2896 // in different register classes or requires an alignment greater
2897 // than 8 for general purpose registers and 16 for XMM registers.
2898 //
2899 // FIXME: This really results in shameful code when we end up needing to
2900 // collect arguments from different places; often what should result in a
2901 // simple assembling of a structure from scattered addresses has many more
2902 // loads than necessary. Can we clean this up?
Chris Lattner2acc6e32011-07-18 04:24:23 +00002903 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002904 llvm::Value *RegAddr =
2905 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2906 "reg_save_area");
2907 if (neededInt && neededSSE) {
2908 // FIXME: Cleanup.
Chris Lattner800588f2010-07-29 06:26:06 +00002909 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002910 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmaneeb00622013-06-07 23:20:55 +00002911 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2912 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002913 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002914 llvm::Type *TyLo = ST->getElementType(0);
2915 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattnera8b7a7d2010-08-26 06:28:35 +00002916 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002917 "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002918 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2919 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002920 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2921 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002922 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2923 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002924 llvm::Value *V =
2925 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2926 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2927 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2928 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2929
Owen Andersona1cf15f2009-07-14 23:10:40 +00002930 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002931 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002932 } else if (neededInt) {
2933 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2934 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002935 llvm::PointerType::getUnqual(LTy));
Eli Friedmaneeb00622013-06-07 23:20:55 +00002936
2937 // Copy to a temporary if necessary to ensure the appropriate alignment.
2938 std::pair<CharUnits, CharUnits> SizeAlign =
2939 CGF.getContext().getTypeInfoInChars(Ty);
2940 uint64_t TySize = SizeAlign.first.getQuantity();
2941 unsigned TyAlign = SizeAlign.second.getQuantity();
2942 if (TyAlign > 8) {
Eli Friedmaneeb00622013-06-07 23:20:55 +00002943 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2944 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2945 RegAddr = Tmp;
2946 }
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002947 } else if (neededSSE == 1) {
2948 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2949 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2950 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002951 } else {
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002952 assert(neededSSE == 2 && "Invalid number of needed registers!");
2953 // SSE registers are spaced 16 bytes apart in the register save
2954 // area, we need to collect the two eightbytes together.
2955 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattner1090a9b2010-06-28 21:43:59 +00002956 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattner8b418682012-02-07 00:39:47 +00002957 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002958 llvm::Type *DblPtrTy =
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002959 llvm::PointerType::getUnqual(DoubleTy);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002960 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmaneeb00622013-06-07 23:20:55 +00002961 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2962 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002963 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2964 DblPtrTy));
2965 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2966 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2967 DblPtrTy));
2968 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2969 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2970 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002971 }
2972
2973 // AMD64-ABI 3.5.7p5: Step 5. Set:
2974 // l->gp_offset = l->gp_offset + num_gp * 8
2975 // l->fp_offset = l->fp_offset + num_fp * 16.
2976 if (neededInt) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002977 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002978 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2979 gp_offset_p);
2980 }
2981 if (neededSSE) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002982 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002983 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2984 fp_offset_p);
2985 }
2986 CGF.EmitBranch(ContBlock);
2987
2988 // Emit code to load the value if it was passed in memory.
2989
2990 CGF.EmitBlock(InMemBlock);
2991 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2992
2993 // Return the appropriate result.
2994
2995 CGF.EmitBlock(ContBlock);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002996 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002997 "vaarg.addr");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002998 ResAddr->addIncoming(RegAddr, InRegBlock);
2999 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003000 return ResAddr;
3001}
3002
Stephen Hines176edba2014-12-01 14:53:08 -08003003ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3004 bool IsReturnType) const {
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003005
3006 if (Ty->isVoidType())
3007 return ABIArgInfo::getIgnore();
3008
3009 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3010 Ty = EnumTy->getDecl()->getIntegerType();
3011
Stephen Hines176edba2014-12-01 14:53:08 -08003012 TypeInfo Info = getContext().getTypeInfo(Ty);
3013 uint64_t Width = Info.Width;
3014 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003015
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003016 const RecordType *RT = Ty->getAs<RecordType>();
3017 if (RT) {
3018 if (!IsReturnType) {
Mark Lacey23630722013-10-06 01:33:34 +00003019 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003020 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3021 }
3022
3023 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003024 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3025
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00003026 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Stephen Hines176edba2014-12-01 14:53:08 -08003027 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00003028 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Stephen Hines176edba2014-12-01 14:53:08 -08003029 Width));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003030 }
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00003031
Stephen Hines176edba2014-12-01 14:53:08 -08003032 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3033 // other targets.
3034 const Type *Base = nullptr;
3035 uint64_t NumElts = 0;
3036 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3037 if (FreeSSERegs >= NumElts) {
3038 FreeSSERegs -= NumElts;
3039 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3040 return ABIArgInfo::getDirect();
3041 return ABIArgInfo::getExpand();
3042 }
3043 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3044 }
3045
3046
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003047 if (Ty->isMemberPointerType()) {
3048 // If the member pointer is represented by an LLVM int or ptr, pass it
3049 // directly.
3050 llvm::Type *LLTy = CGT.ConvertType(Ty);
3051 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3052 return ABIArgInfo::getDirect();
3053 }
3054
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003055 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00003056 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3057 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Stephen Hines176edba2014-12-01 14:53:08 -08003058 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003059 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003060
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003061 // Otherwise, coerce it to a small integer.
Stephen Hines176edba2014-12-01 14:53:08 -08003062 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003063 }
3064
Stephen Hines176edba2014-12-01 14:53:08 -08003065 // Bool type is always extended to the ABI, other builtin types are not
3066 // extended.
3067 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3068 if (BT && BT->getKind() == BuiltinType::Bool)
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003069 return ABIArgInfo::getExtend();
3070
3071 return ABIArgInfo::getDirect();
3072}
3073
3074void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines176edba2014-12-01 14:53:08 -08003075 bool IsVectorCall =
3076 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003077
Stephen Hines176edba2014-12-01 14:53:08 -08003078 // We can use up to 4 SSE return registers with vectorcall.
3079 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3080 if (!getCXXABI().classifyReturnType(FI))
3081 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3082
3083 // We can use up to 6 SSE register parameters with vectorcall.
3084 FreeSSERegs = IsVectorCall ? 6 : 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07003085 for (auto &I : FI.arguments())
Stephen Hines176edba2014-12-01 14:53:08 -08003086 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003087}
3088
Chris Lattnerf13721d2010-08-31 16:44:54 +00003089llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3090 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003091 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003092
Chris Lattnerf13721d2010-08-31 16:44:54 +00003093 CGBuilderTy &Builder = CGF.Builder;
3094 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3095 "ap");
3096 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3097 llvm::Type *PTy =
3098 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3099 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3100
3101 uint64_t Offset =
3102 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3103 llvm::Value *NextAddr =
3104 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3105 "ap.next");
3106 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3107
3108 return AddrTyped;
3109}
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003110
John McCallec853ba2010-03-11 00:10:12 +00003111// PowerPC-32
John McCallec853ba2010-03-11 00:10:12 +00003112namespace {
Stephen Hines176edba2014-12-01 14:53:08 -08003113/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3114class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallec853ba2010-03-11 00:10:12 +00003115public:
Stephen Hines176edba2014-12-01 14:53:08 -08003116 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3117
3118 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3119 CodeGenFunction &CGF) const override;
3120};
3121
3122class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3123public:
3124 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00003125
Stephen Hines651f13c2014-04-23 16:59:28 -07003126 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallec853ba2010-03-11 00:10:12 +00003127 // This is recovered from gcc output.
3128 return 1; // r1 is the dedicated stack pointer
3129 }
3130
3131 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07003132 llvm::Value *Address) const override;
Stephen Hines176edba2014-12-01 14:53:08 -08003133
3134 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3135 return 16; // Natural alignment for Altivec vectors.
3136 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003137
3138 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
3139 return true;
3140 }
John McCallec853ba2010-03-11 00:10:12 +00003141};
3142
3143}
3144
Stephen Hines176edba2014-12-01 14:53:08 -08003145llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3146 QualType Ty,
3147 CodeGenFunction &CGF) const {
3148 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3149 // TODO: Implement this. For now ignore.
3150 (void)CTy;
3151 return nullptr;
3152 }
3153
3154 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3155 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3156 llvm::Type *CharPtr = CGF.Int8PtrTy;
3157 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3158
3159 CGBuilderTy &Builder = CGF.Builder;
3160 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3161 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3162 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3163 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3164 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3165 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3166 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3167 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3168 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3169 // Align GPR when TY is i64.
3170 if (isI64) {
3171 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3172 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3173 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3174 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3175 }
3176 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3177 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3178 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3179 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3180 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3181
3182 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3183 Builder.getInt8(8), "cond");
3184
3185 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3186 Builder.getInt8(isInt ? 4 : 8));
3187
3188 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3189
3190 if (Ty->isFloatingType())
3191 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3192
3193 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3194 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3195 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3196
3197 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3198
3199 CGF.EmitBlock(UsingRegs);
3200
3201 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3202 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3203 // Increase the GPR/FPR indexes.
3204 if (isInt) {
3205 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3206 Builder.CreateStore(GPR, GPRPtr);
3207 } else {
3208 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3209 Builder.CreateStore(FPR, FPRPtr);
3210 }
3211 CGF.EmitBranch(Cont);
3212
3213 CGF.EmitBlock(UsingOverflow);
3214
3215 // Increase the overflow area.
3216 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3217 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3218 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3219 CGF.EmitBranch(Cont);
3220
3221 CGF.EmitBlock(Cont);
3222
3223 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3224 Result->addIncoming(Result1, UsingRegs);
3225 Result->addIncoming(Result2, UsingOverflow);
3226
3227 if (Ty->isAggregateType()) {
3228 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3229 return Builder.CreateLoad(AGGPtr, false, "aggr");
3230 }
3231
3232 return Result;
3233}
3234
John McCallec853ba2010-03-11 00:10:12 +00003235bool
3236PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3237 llvm::Value *Address) const {
3238 // This is calculated from the LLVM and GCC tables and verified
3239 // against gcc output. AFAIK all ABIs use the same encoding.
3240
3241 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallec853ba2010-03-11 00:10:12 +00003242
Chris Lattner8b418682012-02-07 00:39:47 +00003243 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallec853ba2010-03-11 00:10:12 +00003244 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3245 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3246 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3247
3248 // 0-31: r0-31, the 4-byte general-purpose registers
John McCallaeeb7012010-05-27 06:19:26 +00003249 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallec853ba2010-03-11 00:10:12 +00003250
3251 // 32-63: fp0-31, the 8-byte floating-point registers
John McCallaeeb7012010-05-27 06:19:26 +00003252 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallec853ba2010-03-11 00:10:12 +00003253
3254 // 64-76 are various 4-byte special-purpose registers:
3255 // 64: mq
3256 // 65: lr
3257 // 66: ctr
3258 // 67: ap
3259 // 68-75 cr0-7
3260 // 76: xer
John McCallaeeb7012010-05-27 06:19:26 +00003261 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallec853ba2010-03-11 00:10:12 +00003262
3263 // 77-108: v0-31, the 16-byte vector registers
John McCallaeeb7012010-05-27 06:19:26 +00003264 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallec853ba2010-03-11 00:10:12 +00003265
3266 // 109: vrsave
3267 // 110: vscr
3268 // 111: spe_acc
3269 // 112: spefscr
3270 // 113: sfp
John McCallaeeb7012010-05-27 06:19:26 +00003271 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallec853ba2010-03-11 00:10:12 +00003272
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00003273 return false;
John McCallec853ba2010-03-11 00:10:12 +00003274}
3275
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003276// PowerPC-64
3277
3278namespace {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003279/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3280class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Stephen Hines176edba2014-12-01 14:53:08 -08003281public:
3282 enum ABIKind {
3283 ELFv1 = 0,
3284 ELFv2
3285 };
3286
3287private:
3288 static const unsigned GPRBits = 64;
3289 ABIKind Kind;
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003290
3291public:
Stephen Hines176edba2014-12-01 14:53:08 -08003292 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3293 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003294
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003295 bool isPromotableTypeForABI(QualType Ty) const;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003296 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003297
3298 ABIArgInfo classifyReturnType(QualType RetTy) const;
3299 ABIArgInfo classifyArgumentType(QualType Ty) const;
3300
Stephen Hines176edba2014-12-01 14:53:08 -08003301 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3302 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3303 uint64_t Members) const override;
3304
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003305 // TODO: We can add more logic to computeInfo to improve performance.
3306 // Example: For aggregate arguments that fit in a register, we could
3307 // use getDirectInReg (as is done below for structs containing a single
3308 // floating-point value) to avoid pushing them to memory on function
3309 // entry. This would require changing the logic in PPCISelLowering
3310 // when lowering the parameters in the caller and args in the callee.
Stephen Hines651f13c2014-04-23 16:59:28 -07003311 void computeInfo(CGFunctionInfo &FI) const override {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003312 if (!getCXXABI().classifyReturnType(FI))
3313 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07003314 for (auto &I : FI.arguments()) {
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003315 // We rely on the default argument classification for the most part.
3316 // One exception: An aggregate containing a single floating-point
Bill Schmidtb1993102013-07-23 22:15:57 +00003317 // or vector item must be passed in a register if one is available.
Stephen Hines651f13c2014-04-23 16:59:28 -07003318 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003319 if (T) {
3320 const BuiltinType *BT = T->getAs<BuiltinType>();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003321 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3322 (BT && BT->isFloatingPoint())) {
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003323 QualType QT(T, 0);
Stephen Hines651f13c2014-04-23 16:59:28 -07003324 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003325 continue;
3326 }
3327 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003328 I.info = classifyArgumentType(I.type);
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003329 }
3330 }
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003331
Stephen Hines651f13c2014-04-23 16:59:28 -07003332 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3333 CodeGenFunction &CGF) const override;
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003334};
3335
3336class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3337public:
Stephen Hines176edba2014-12-01 14:53:08 -08003338 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3339 PPC64_SVR4_ABIInfo::ABIKind Kind)
3340 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003341
Stephen Hines651f13c2014-04-23 16:59:28 -07003342 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003343 // This is recovered from gcc output.
3344 return 1; // r1 is the dedicated stack pointer
3345 }
3346
3347 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07003348 llvm::Value *Address) const override;
Stephen Hines176edba2014-12-01 14:53:08 -08003349
3350 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3351 return 16; // Natural alignment for Altivec and VSX vectors.
3352 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003353
3354 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
3355 return true;
3356 }
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003357};
3358
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003359class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3360public:
3361 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3362
Stephen Hines651f13c2014-04-23 16:59:28 -07003363 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003364 // This is recovered from gcc output.
3365 return 1; // r1 is the dedicated stack pointer
3366 }
3367
3368 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07003369 llvm::Value *Address) const override;
Stephen Hines176edba2014-12-01 14:53:08 -08003370
3371 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3372 return 16; // Natural alignment for Altivec vectors.
3373 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003374
3375 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
3376 return true;
3377 }
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003378};
3379
3380}
3381
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003382// Return true if the ABI requires Ty to be passed sign- or zero-
3383// extended to 64 bits.
3384bool
3385PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3386 // Treat an enum type as its underlying type.
3387 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3388 Ty = EnumTy->getDecl()->getIntegerType();
3389
3390 // Promotable integer types are required to be promoted by the ABI.
3391 if (Ty->isPromotableIntegerType())
3392 return true;
3393
3394 // In addition to the usual promotable integer types, we also need to
3395 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3396 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3397 switch (BT->getKind()) {
3398 case BuiltinType::Int:
3399 case BuiltinType::UInt:
3400 return true;
3401 default:
3402 break;
3403 }
3404
3405 return false;
3406}
3407
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003408/// isAlignedParamType - Determine whether a type requires 16-byte
3409/// alignment in the parameter area.
3410bool
3411PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3412 // Complex types are passed just like their elements.
3413 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3414 Ty = CTy->getElementType();
3415
3416 // Only vector types of size 16 bytes need alignment (larger types are
3417 // passed via reference, smaller types are not aligned).
3418 if (Ty->isVectorType())
3419 return getContext().getTypeSize(Ty) == 128;
3420
3421 // For single-element float/vector structs, we consider the whole type
3422 // to have the same alignment requirements as its single element.
3423 const Type *AlignAsType = nullptr;
3424 const Type *EltType = isSingleElementStruct(Ty, getContext());
3425 if (EltType) {
3426 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3427 if ((EltType->isVectorType() &&
3428 getContext().getTypeSize(EltType) == 128) ||
3429 (BT && BT->isFloatingPoint()))
3430 AlignAsType = EltType;
3431 }
3432
Stephen Hines176edba2014-12-01 14:53:08 -08003433 // Likewise for ELFv2 homogeneous aggregates.
3434 const Type *Base = nullptr;
3435 uint64_t Members = 0;
3436 if (!AlignAsType && Kind == ELFv2 &&
3437 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3438 AlignAsType = Base;
3439
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003440 // With special case aggregates, only vector base types need alignment.
3441 if (AlignAsType)
3442 return AlignAsType->isVectorType();
3443
3444 // Otherwise, we only need alignment for any aggregate type that
3445 // has an alignment requirement of >= 16 bytes.
3446 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3447 return true;
3448
3449 return false;
3450}
3451
Stephen Hines176edba2014-12-01 14:53:08 -08003452/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3453/// aggregate. Base is set to the base element type, and Members is set
3454/// to the number of base elements.
3455bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3456 uint64_t &Members) const {
3457 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3458 uint64_t NElements = AT->getSize().getZExtValue();
3459 if (NElements == 0)
3460 return false;
3461 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3462 return false;
3463 Members *= NElements;
3464 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3465 const RecordDecl *RD = RT->getDecl();
3466 if (RD->hasFlexibleArrayMember())
3467 return false;
3468
3469 Members = 0;
3470
3471 // If this is a C++ record, check the bases first.
3472 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3473 for (const auto &I : CXXRD->bases()) {
3474 // Ignore empty records.
3475 if (isEmptyRecord(getContext(), I.getType(), true))
3476 continue;
3477
3478 uint64_t FldMembers;
3479 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3480 return false;
3481
3482 Members += FldMembers;
3483 }
3484 }
3485
3486 for (const auto *FD : RD->fields()) {
3487 // Ignore (non-zero arrays of) empty records.
3488 QualType FT = FD->getType();
3489 while (const ConstantArrayType *AT =
3490 getContext().getAsConstantArrayType(FT)) {
3491 if (AT->getSize().getZExtValue() == 0)
3492 return false;
3493 FT = AT->getElementType();
3494 }
3495 if (isEmptyRecord(getContext(), FT, true))
3496 continue;
3497
3498 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3499 if (getContext().getLangOpts().CPlusPlus &&
3500 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3501 continue;
3502
3503 uint64_t FldMembers;
3504 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3505 return false;
3506
3507 Members = (RD->isUnion() ?
3508 std::max(Members, FldMembers) : Members + FldMembers);
3509 }
3510
3511 if (!Base)
3512 return false;
3513
3514 // Ensure there is no padding.
3515 if (getContext().getTypeSize(Base) * Members !=
3516 getContext().getTypeSize(Ty))
3517 return false;
3518 } else {
3519 Members = 1;
3520 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3521 Members = 2;
3522 Ty = CT->getElementType();
3523 }
3524
3525 // Most ABIs only support float, double, and some vector type widths.
3526 if (!isHomogeneousAggregateBaseType(Ty))
3527 return false;
3528
3529 // The base type must be the same for all members. Types that
3530 // agree in both total size and mode (float vs. vector) are
3531 // treated as being equivalent here.
3532 const Type *TyPtr = Ty.getTypePtr();
3533 if (!Base)
3534 Base = TyPtr;
3535
3536 if (Base->isVectorType() != TyPtr->isVectorType() ||
3537 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3538 return false;
3539 }
3540 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3541}
3542
3543bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3544 // Homogeneous aggregates for ELFv2 must have base types of float,
3545 // double, long double, or 128-bit vectors.
3546 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3547 if (BT->getKind() == BuiltinType::Float ||
3548 BT->getKind() == BuiltinType::Double ||
3549 BT->getKind() == BuiltinType::LongDouble)
3550 return true;
3551 }
3552 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3553 if (getContext().getTypeSize(VT) == 128)
3554 return true;
3555 }
3556 return false;
3557}
3558
3559bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3560 const Type *Base, uint64_t Members) const {
3561 // Vector types require one register, floating point types require one
3562 // or two registers depending on their size.
3563 uint32_t NumRegs =
3564 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
3565
3566 // Homogeneous Aggregates may occupy at most 8 registers.
3567 return Members * NumRegs <= 8;
3568}
3569
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003570ABIArgInfo
3571PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Stephen Hines176edba2014-12-01 14:53:08 -08003572 Ty = useFirstFieldIfTransparentUnion(Ty);
3573
Bill Schmidtc9715fc2012-11-27 02:46:43 +00003574 if (Ty->isAnyComplexType())
3575 return ABIArgInfo::getDirect();
3576
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003577 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3578 // or via reference (larger than 16 bytes).
3579 if (Ty->isVectorType()) {
3580 uint64_t Size = getContext().getTypeSize(Ty);
3581 if (Size > 128)
3582 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3583 else if (Size < 128) {
3584 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3585 return ABIArgInfo::getDirect(CoerceTy);
3586 }
3587 }
3588
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003589 if (isAggregateTypeForABI(Ty)) {
Mark Lacey23630722013-10-06 01:33:34 +00003590 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003591 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003592
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003593 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3594 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Stephen Hines176edba2014-12-01 14:53:08 -08003595
3596 // ELFv2 homogeneous aggregates are passed as array types.
3597 const Type *Base = nullptr;
3598 uint64_t Members = 0;
3599 if (Kind == ELFv2 &&
3600 isHomogeneousAggregate(Ty, Base, Members)) {
3601 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3602 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3603 return ABIArgInfo::getDirect(CoerceTy);
3604 }
3605
3606 // If an aggregate may end up fully in registers, we do not
3607 // use the ByVal method, but pass the aggregate as array.
3608 // This is usually beneficial since we avoid forcing the
3609 // back-end to store the argument to memory.
3610 uint64_t Bits = getContext().getTypeSize(Ty);
3611 if (Bits > 0 && Bits <= 8 * GPRBits) {
3612 llvm::Type *CoerceTy;
3613
3614 // Types up to 8 bytes are passed as integer type (which will be
3615 // properly aligned in the argument save area doubleword).
3616 if (Bits <= GPRBits)
3617 CoerceTy = llvm::IntegerType::get(getVMContext(),
3618 llvm::RoundUpToAlignment(Bits, 8));
3619 // Larger types are passed as arrays, with the base type selected
3620 // according to the required alignment in the save area.
3621 else {
3622 uint64_t RegBits = ABIAlign * 8;
3623 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3624 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3625 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3626 }
3627
3628 return ABIArgInfo::getDirect(CoerceTy);
3629 }
3630
3631 // All other aggregates are passed ByVal.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003632 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3633 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003634 }
3635
3636 return (isPromotableTypeForABI(Ty) ?
3637 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3638}
3639
3640ABIArgInfo
3641PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3642 if (RetTy->isVoidType())
3643 return ABIArgInfo::getIgnore();
3644
Bill Schmidt9e6111a2012-12-17 04:20:17 +00003645 if (RetTy->isAnyComplexType())
3646 return ABIArgInfo::getDirect();
3647
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003648 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3649 // or via reference (larger than 16 bytes).
3650 if (RetTy->isVectorType()) {
3651 uint64_t Size = getContext().getTypeSize(RetTy);
3652 if (Size > 128)
3653 return ABIArgInfo::getIndirect(0);
3654 else if (Size < 128) {
3655 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3656 return ABIArgInfo::getDirect(CoerceTy);
3657 }
3658 }
3659
Stephen Hines176edba2014-12-01 14:53:08 -08003660 if (isAggregateTypeForABI(RetTy)) {
3661 // ELFv2 homogeneous aggregates are returned as array types.
3662 const Type *Base = nullptr;
3663 uint64_t Members = 0;
3664 if (Kind == ELFv2 &&
3665 isHomogeneousAggregate(RetTy, Base, Members)) {
3666 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3667 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3668 return ABIArgInfo::getDirect(CoerceTy);
3669 }
3670
3671 // ELFv2 small aggregates are returned in up to two registers.
3672 uint64_t Bits = getContext().getTypeSize(RetTy);
3673 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3674 if (Bits == 0)
3675 return ABIArgInfo::getIgnore();
3676
3677 llvm::Type *CoerceTy;
3678 if (Bits > GPRBits) {
3679 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003680 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Stephen Hines176edba2014-12-01 14:53:08 -08003681 } else
3682 CoerceTy = llvm::IntegerType::get(getVMContext(),
3683 llvm::RoundUpToAlignment(Bits, 8));
3684 return ABIArgInfo::getDirect(CoerceTy);
3685 }
3686
3687 // All other aggregates are returned indirectly.
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003688 return ABIArgInfo::getIndirect(0);
Stephen Hines176edba2014-12-01 14:53:08 -08003689 }
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003690
3691 return (isPromotableTypeForABI(RetTy) ?
3692 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3693}
3694
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003695// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3696llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3697 QualType Ty,
3698 CodeGenFunction &CGF) const {
3699 llvm::Type *BP = CGF.Int8PtrTy;
3700 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3701
3702 CGBuilderTy &Builder = CGF.Builder;
3703 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3704 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3705
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003706 // Handle types that require 16-byte alignment in the parameter save area.
3707 if (isAlignedParamType(Ty)) {
3708 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3709 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3710 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3711 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3712 }
3713
Bill Schmidt19f8e852013-01-14 17:45:36 +00003714 // Update the va_list pointer. The pointer should be bumped by the
3715 // size of the object. We can trust getTypeSize() except for a complex
3716 // type whose base type is smaller than a doubleword. For these, the
3717 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003718 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt19f8e852013-01-14 17:45:36 +00003719 QualType BaseTy;
3720 unsigned CplxBaseSize = 0;
3721
3722 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3723 BaseTy = CTy->getElementType();
3724 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3725 if (CplxBaseSize < 8)
3726 SizeInBytes = 16;
3727 }
3728
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003729 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3730 llvm::Value *NextAddr =
3731 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3732 "ap.next");
3733 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3734
Bill Schmidt19f8e852013-01-14 17:45:36 +00003735 // If we have a complex type and the base type is smaller than 8 bytes,
3736 // the ABI calls for the real and imaginary parts to be right-adjusted
3737 // in separate doublewords. However, Clang expects us to produce a
3738 // pointer to a structure with the two parts packed tightly. So generate
3739 // loads of the real and imaginary parts relative to the va_list pointer,
3740 // and store them to a temporary structure.
3741 if (CplxBaseSize && CplxBaseSize < 8) {
3742 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3743 llvm::Value *ImagAddr = RealAddr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003744 if (CGF.CGM.getDataLayout().isBigEndian()) {
3745 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3746 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3747 } else {
3748 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3749 }
Bill Schmidt19f8e852013-01-14 17:45:36 +00003750 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3751 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3752 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3753 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3754 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3755 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3756 "vacplx");
3757 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3758 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3759 Builder.CreateStore(Real, RealPtr, false);
3760 Builder.CreateStore(Imag, ImagPtr, false);
3761 return Ptr;
3762 }
3763
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003764 // If the argument is smaller than 8 bytes, it is right-adjusted in
3765 // its doubleword slot. Adjust the pointer to pick it up from the
3766 // correct offset.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003767 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003768 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3769 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3770 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3771 }
3772
3773 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3774 return Builder.CreateBitCast(Addr, PTy);
3775}
3776
3777static bool
3778PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3779 llvm::Value *Address) {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003780 // This is calculated from the LLVM and GCC tables and verified
3781 // against gcc output. AFAIK all ABIs use the same encoding.
3782
3783 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3784
3785 llvm::IntegerType *i8 = CGF.Int8Ty;
3786 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3787 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3788 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3789
3790 // 0-31: r0-31, the 8-byte general-purpose registers
3791 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3792
3793 // 32-63: fp0-31, the 8-byte floating-point registers
3794 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3795
3796 // 64-76 are various 4-byte special-purpose registers:
3797 // 64: mq
3798 // 65: lr
3799 // 66: ctr
3800 // 67: ap
3801 // 68-75 cr0-7
3802 // 76: xer
3803 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3804
3805 // 77-108: v0-31, the 16-byte vector registers
3806 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3807
3808 // 109: vrsave
3809 // 110: vscr
3810 // 111: spe_acc
3811 // 112: spefscr
3812 // 113: sfp
3813 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3814
3815 return false;
3816}
John McCallec853ba2010-03-11 00:10:12 +00003817
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003818bool
3819PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3820 CodeGen::CodeGenFunction &CGF,
3821 llvm::Value *Address) const {
3822
3823 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3824}
3825
3826bool
3827PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3828 llvm::Value *Address) const {
3829
3830 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3831}
3832
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003833//===----------------------------------------------------------------------===//
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003834// AArch64 ABI Implementation
Stephen Hines651f13c2014-04-23 16:59:28 -07003835//===----------------------------------------------------------------------===//
3836
3837namespace {
3838
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003839class AArch64ABIInfo : public ABIInfo {
Stephen Hines651f13c2014-04-23 16:59:28 -07003840public:
3841 enum ABIKind {
3842 AAPCS = 0,
3843 DarwinPCS
3844 };
3845
3846private:
3847 ABIKind Kind;
3848
3849public:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003850 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07003851
3852private:
3853 ABIKind getABIKind() const { return Kind; }
3854 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3855
3856 ABIArgInfo classifyReturnType(QualType RetTy) const;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003857 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Stephen Hines176edba2014-12-01 14:53:08 -08003858 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3859 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3860 uint64_t Members) const override;
3861
Stephen Hines651f13c2014-04-23 16:59:28 -07003862 bool isIllegalVectorType(QualType Ty) const;
3863
Stephen Hines176edba2014-12-01 14:53:08 -08003864 void computeInfo(CGFunctionInfo &FI) const override {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003865 if (!getCXXABI().classifyReturnType(FI))
3866 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003867
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003868 for (auto &it : FI.arguments())
3869 it.info = classifyArgumentType(it.type);
Stephen Hines651f13c2014-04-23 16:59:28 -07003870 }
3871
3872 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3873 CodeGenFunction &CGF) const;
3874
3875 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3876 CodeGenFunction &CGF) const;
3877
3878 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Stephen Hines176edba2014-12-01 14:53:08 -08003879 CodeGenFunction &CGF) const override {
Stephen Hines651f13c2014-04-23 16:59:28 -07003880 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3881 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3882 }
3883};
3884
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003885class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Stephen Hines651f13c2014-04-23 16:59:28 -07003886public:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003887 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3888 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07003889
3890 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3891 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3892 }
3893
3894 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3895
3896 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3897};
3898}
3899
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003900ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Stephen Hines176edba2014-12-01 14:53:08 -08003901 Ty = useFirstFieldIfTransparentUnion(Ty);
3902
Stephen Hines651f13c2014-04-23 16:59:28 -07003903 // Handle illegal vector types here.
3904 if (isIllegalVectorType(Ty)) {
3905 uint64_t Size = getContext().getTypeSize(Ty);
Tim Murray9212d4f2014-08-15 16:00:15 -07003906 // Android promotes <2 x i8> to i16, not i32
3907 if (Size <= 16) {
3908 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
Tim Murray9212d4f2014-08-15 16:00:15 -07003909 return ABIArgInfo::getDirect(ResType);
3910 }
3911 if (Size == 32) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003912 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Stephen Hines651f13c2014-04-23 16:59:28 -07003913 return ABIArgInfo::getDirect(ResType);
3914 }
3915 if (Size == 64) {
3916 llvm::Type *ResType =
3917 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Stephen Hines651f13c2014-04-23 16:59:28 -07003918 return ABIArgInfo::getDirect(ResType);
3919 }
3920 if (Size == 128) {
3921 llvm::Type *ResType =
3922 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Stephen Hines651f13c2014-04-23 16:59:28 -07003923 return ABIArgInfo::getDirect(ResType);
3924 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003925 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3926 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003927
3928 if (!isAggregateTypeForABI(Ty)) {
3929 // Treat an enum type as its underlying type.
3930 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3931 Ty = EnumTy->getDecl()->getIntegerType();
3932
Stephen Hines651f13c2014-04-23 16:59:28 -07003933 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3934 ? ABIArgInfo::getExtend()
3935 : ABIArgInfo::getDirect());
3936 }
3937
3938 // Structures with either a non-trivial destructor or a non-trivial
3939 // copy constructor are always indirect.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003940 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003941 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003942 CGCXXABI::RAA_DirectInMemory);
Stephen Hines651f13c2014-04-23 16:59:28 -07003943 }
3944
3945 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3946 // elsewhere for GNU compatibility.
3947 if (isEmptyRecord(getContext(), Ty, true)) {
3948 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3949 return ABIArgInfo::getIgnore();
3950
Stephen Hines651f13c2014-04-23 16:59:28 -07003951 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3952 }
3953
3954 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003955 const Type *Base = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07003956 uint64_t Members = 0;
Stephen Hines176edba2014-12-01 14:53:08 -08003957 if (isHomogeneousAggregate(Ty, Base, Members)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003958 return ABIArgInfo::getDirect(
3959 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Stephen Hines651f13c2014-04-23 16:59:28 -07003960 }
3961
3962 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3963 uint64_t Size = getContext().getTypeSize(Ty);
3964 if (Size <= 128) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003965 unsigned Alignment = getContext().getTypeAlign(Ty);
Stephen Hines651f13c2014-04-23 16:59:28 -07003966 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003967
Stephen Hines651f13c2014-04-23 16:59:28 -07003968 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3969 // For aggregates with 16-byte alignment, we use i128.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003970 if (Alignment < 128 && Size == 128) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003971 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3972 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3973 }
3974 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3975 }
3976
Stephen Hines651f13c2014-04-23 16:59:28 -07003977 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3978}
3979
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003980ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07003981 if (RetTy->isVoidType())
3982 return ABIArgInfo::getIgnore();
3983
3984 // Large vector types should be returned via memory.
3985 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3986 return ABIArgInfo::getIndirect(0);
3987
3988 if (!isAggregateTypeForABI(RetTy)) {
3989 // Treat an enum type as its underlying type.
3990 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3991 RetTy = EnumTy->getDecl()->getIntegerType();
3992
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003993 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3994 ? ABIArgInfo::getExtend()
3995 : ABIArgInfo::getDirect());
Stephen Hines651f13c2014-04-23 16:59:28 -07003996 }
3997
Stephen Hines651f13c2014-04-23 16:59:28 -07003998 if (isEmptyRecord(getContext(), RetTy, true))
3999 return ABIArgInfo::getIgnore();
4000
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004001 const Type *Base = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08004002 uint64_t Members = 0;
4003 if (isHomogeneousAggregate(RetTy, Base, Members))
Stephen Hines651f13c2014-04-23 16:59:28 -07004004 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4005 return ABIArgInfo::getDirect();
4006
4007 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4008 uint64_t Size = getContext().getTypeSize(RetTy);
4009 if (Size <= 128) {
4010 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
4011 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4012 }
4013
4014 return ABIArgInfo::getIndirect(0);
4015}
4016
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004017/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4018bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07004019 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4020 // Check whether VT is legal.
4021 unsigned NumElements = VT->getNumElements();
4022 uint64_t Size = getContext().getTypeSize(VT);
4023 // NumElements should be power of 2 between 1 and 16.
4024 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4025 return true;
4026 return Size != 64 && (Size != 128 || NumElements == 1);
4027 }
4028 return false;
4029}
4030
Stephen Hines176edba2014-12-01 14:53:08 -08004031bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4032 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4033 // point type or a short-vector type. This is the same as the 32-bit ABI,
4034 // but with the difference that any floating-point type is allowed,
4035 // including __fp16.
4036 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4037 if (BT->isFloatingPoint())
4038 return true;
4039 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4040 unsigned VecSize = getContext().getTypeSize(VT);
4041 if (VecSize == 64 || VecSize == 128)
4042 return true;
4043 }
4044 return false;
4045}
4046
4047bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4048 uint64_t Members) const {
4049 return Members <= 4;
4050}
4051
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004052llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4053 QualType Ty,
4054 CodeGenFunction &CGF) const {
4055 ABIArgInfo AI = classifyArgumentType(Ty);
Stephen Hines176edba2014-12-01 14:53:08 -08004056 bool IsIndirect = AI.isIndirect();
4057
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004058 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4059 if (IsIndirect)
4060 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4061 else if (AI.getCoerceToType())
4062 BaseTy = AI.getCoerceToType();
4063
4064 unsigned NumRegs = 1;
4065 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4066 BaseTy = ArrTy->getElementType();
4067 NumRegs = ArrTy->getNumElements();
4068 }
4069 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4070
Stephen Hines651f13c2014-04-23 16:59:28 -07004071 // The AArch64 va_list type and handling is specified in the Procedure Call
4072 // Standard, section B.4:
4073 //
4074 // struct {
4075 // void *__stack;
4076 // void *__gr_top;
4077 // void *__vr_top;
4078 // int __gr_offs;
4079 // int __vr_offs;
4080 // };
4081
4082 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4083 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4084 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4085 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4086 auto &Ctx = CGF.getContext();
4087
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004088 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004089 int reg_top_index;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004090 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4091 if (!IsFPR) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004092 // 3 is the field number of __gr_offs
4093 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4094 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4095 reg_top_index = 1; // field number for __gr_top
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004096 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Stephen Hines651f13c2014-04-23 16:59:28 -07004097 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07004098 // 4 is the field number of __vr_offs.
4099 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4100 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4101 reg_top_index = 2; // field number for __vr_top
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004102 RegSize = 16 * NumRegs;
Stephen Hines651f13c2014-04-23 16:59:28 -07004103 }
4104
4105 //=======================================
4106 // Find out where argument was passed
4107 //=======================================
4108
4109 // If reg_offs >= 0 we're already using the stack for this type of
4110 // argument. We don't want to keep updating reg_offs (in case it overflows,
4111 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4112 // whatever they get).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004113 llvm::Value *UsingStack = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004114 UsingStack = CGF.Builder.CreateICmpSGE(
4115 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4116
4117 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4118
4119 // Otherwise, at least some kind of argument could go in these registers, the
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004120 // question is whether this particular type is too big.
Stephen Hines651f13c2014-04-23 16:59:28 -07004121 CGF.EmitBlock(MaybeRegBlock);
4122
4123 // Integer arguments may need to correct register alignment (for example a
4124 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4125 // align __gr_offs to calculate the potential address.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004126 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004127 int Align = Ctx.getTypeAlign(Ty) / 8;
4128
4129 reg_offs = CGF.Builder.CreateAdd(
4130 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4131 "align_regoffs");
4132 reg_offs = CGF.Builder.CreateAnd(
4133 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4134 "aligned_regoffs");
4135 }
4136
4137 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004138 llvm::Value *NewOffset = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004139 NewOffset = CGF.Builder.CreateAdd(
4140 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4141 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4142
4143 // Now we're in a position to decide whether this argument really was in
4144 // registers or not.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004145 llvm::Value *InRegs = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004146 InRegs = CGF.Builder.CreateICmpSLE(
4147 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4148
4149 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4150
4151 //=======================================
4152 // Argument was in registers
4153 //=======================================
4154
4155 // Now we emit the code for if the argument was originally passed in
4156 // registers. First start the appropriate block:
4157 CGF.EmitBlock(InRegBlock);
4158
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004159 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004160 reg_top_p =
4161 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4162 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4163 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004164 llvm::Value *RegAddr = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004165 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4166
4167 if (IsIndirect) {
4168 // If it's been passed indirectly (actually a struct), whatever we find from
4169 // stored registers or on the stack will actually be a struct **.
4170 MemTy = llvm::PointerType::getUnqual(MemTy);
4171 }
4172
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004173 const Type *Base = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08004174 uint64_t NumMembers = 0;
4175 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004176 if (IsHFA && NumMembers > 1) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004177 // Homogeneous aggregates passed in registers will have their elements split
4178 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4179 // qN+1, ...). We reload and store into a temporary local variable
4180 // contiguously.
4181 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4182 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4183 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4184 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4185 int Offset = 0;
4186
4187 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4188 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4189 for (unsigned i = 0; i < NumMembers; ++i) {
4190 llvm::Value *BaseOffset =
4191 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4192 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4193 LoadAddr = CGF.Builder.CreateBitCast(
4194 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
4195 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4196
4197 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4198 CGF.Builder.CreateStore(Elem, StoreAddr);
4199 }
4200
4201 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4202 } else {
4203 // Otherwise the object is contiguous in memory
4204 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004205 if (CGF.CGM.getDataLayout().isBigEndian() &&
4206 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07004207 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4208 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4209 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4210
4211 BaseAddr = CGF.Builder.CreateAdd(
4212 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4213
4214 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4215 }
4216
4217 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4218 }
4219
4220 CGF.EmitBranch(ContBlock);
4221
4222 //=======================================
4223 // Argument was on the stack
4224 //=======================================
4225 CGF.EmitBlock(OnStackBlock);
4226
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004227 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004228 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4229 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4230
4231 // Again, stack arguments may need realigmnent. In this case both integer and
4232 // floating-point ones might be affected.
4233 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4234 int Align = Ctx.getTypeAlign(Ty) / 8;
4235
4236 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4237
4238 OnStackAddr = CGF.Builder.CreateAdd(
4239 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4240 "align_stack");
4241 OnStackAddr = CGF.Builder.CreateAnd(
4242 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4243 "align_stack");
4244
4245 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4246 }
4247
4248 uint64_t StackSize;
4249 if (IsIndirect)
4250 StackSize = 8;
4251 else
4252 StackSize = Ctx.getTypeSize(Ty) / 8;
4253
4254 // All stack slots are 8 bytes
4255 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4256
4257 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4258 llvm::Value *NewStack =
4259 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4260
4261 // Write the new value of __stack for the next call to va_arg
4262 CGF.Builder.CreateStore(NewStack, stack_p);
4263
4264 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4265 Ctx.getTypeSize(Ty) < 64) {
4266 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4267 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4268
4269 OnStackAddr = CGF.Builder.CreateAdd(
4270 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4271
4272 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4273 }
4274
4275 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4276
4277 CGF.EmitBranch(ContBlock);
4278
4279 //=======================================
4280 // Tidy up
4281 //=======================================
4282 CGF.EmitBlock(ContBlock);
4283
4284 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4285 ResAddr->addIncoming(RegAddr, InRegBlock);
4286 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4287
4288 if (IsIndirect)
4289 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4290
4291 return ResAddr;
4292}
4293
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004294llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07004295 CodeGenFunction &CGF) const {
4296 // We do not support va_arg for aggregates or illegal vector types.
4297 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4298 // other cases.
4299 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004300 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004301
4302 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4303 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4304
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004305 const Type *Base = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08004306 uint64_t Members = 0;
4307 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Stephen Hines651f13c2014-04-23 16:59:28 -07004308
4309 bool isIndirect = false;
4310 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4311 // be passed indirectly.
4312 if (Size > 16 && !isHA) {
4313 isIndirect = true;
4314 Size = 8;
4315 Align = 8;
4316 }
4317
4318 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4319 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4320
4321 CGBuilderTy &Builder = CGF.Builder;
4322 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4323 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4324
4325 if (isEmptyRecord(getContext(), Ty, true)) {
4326 // These are ignored for parameter passing purposes.
4327 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4328 return Builder.CreateBitCast(Addr, PTy);
4329 }
4330
4331 const uint64_t MinABIAlign = 8;
4332 if (Align > MinABIAlign) {
4333 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4334 Addr = Builder.CreateGEP(Addr, Offset);
4335 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4336 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4337 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4338 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4339 }
4340
4341 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4342 llvm::Value *NextAddr = Builder.CreateGEP(
4343 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4344 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4345
4346 if (isIndirect)
4347 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4348 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4349 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4350
4351 return AddrTyped;
4352}
4353
4354//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00004355// ARM ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004356//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00004357
4358namespace {
4359
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004360class ARMABIInfo : public ABIInfo {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004361public:
4362 enum ABIKind {
4363 APCS = 0,
4364 AAPCS = 1,
4365 AAPCS_VFP
4366 };
4367
4368private:
4369 ABIKind Kind;
4370
4371public:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004372 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
4373 setCCs();
John McCallbd7370a2013-02-28 19:01:20 +00004374 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004375
John McCall49e34be2011-08-30 01:42:09 +00004376 bool isEABI() const {
Stephen Hines651f13c2014-04-23 16:59:28 -07004377 switch (getTarget().getTriple().getEnvironment()) {
4378 case llvm::Triple::Android:
4379 case llvm::Triple::EABI:
4380 case llvm::Triple::EABIHF:
4381 case llvm::Triple::GNUEABI:
4382 case llvm::Triple::GNUEABIHF:
4383 return true;
4384 default:
4385 return false;
4386 }
4387 }
4388
4389 bool isEABIHF() const {
4390 switch (getTarget().getTriple().getEnvironment()) {
4391 case llvm::Triple::EABIHF:
4392 case llvm::Triple::GNUEABIHF:
4393 return true;
4394 default:
4395 return false;
4396 }
John McCall49e34be2011-08-30 01:42:09 +00004397 }
4398
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004399 ABIKind getABIKind() const { return Kind; }
4400
Tim Northover64eac852013-10-01 14:34:25 +00004401private:
Stephen Hines651f13c2014-04-23 16:59:28 -07004402 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004403 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Ren97f81572012-10-16 19:18:39 +00004404 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004405
Stephen Hines176edba2014-12-01 14:53:08 -08004406 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4407 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4408 uint64_t Members) const override;
4409
Stephen Hines651f13c2014-04-23 16:59:28 -07004410 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004411
Stephen Hines651f13c2014-04-23 16:59:28 -07004412 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4413 CodeGenFunction &CGF) const override;
John McCallbd7370a2013-02-28 19:01:20 +00004414
4415 llvm::CallingConv::ID getLLVMDefaultCC() const;
4416 llvm::CallingConv::ID getABIDefaultCC() const;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004417 void setCCs();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004418};
4419
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004420class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4421public:
Chris Lattnerea044322010-07-29 02:01:43 +00004422 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4423 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCall6374c332010-03-06 00:35:14 +00004424
John McCall49e34be2011-08-30 01:42:09 +00004425 const ARMABIInfo &getABIInfo() const {
4426 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4427 }
4428
Stephen Hines651f13c2014-04-23 16:59:28 -07004429 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCall6374c332010-03-06 00:35:14 +00004430 return 13;
4431 }
Roman Divacky09345d12011-05-18 19:36:54 +00004432
Stephen Hines651f13c2014-04-23 16:59:28 -07004433 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCallf85e1932011-06-15 23:02:42 +00004434 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4435 }
4436
Roman Divacky09345d12011-05-18 19:36:54 +00004437 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07004438 llvm::Value *Address) const override {
Chris Lattner8b418682012-02-07 00:39:47 +00004439 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divacky09345d12011-05-18 19:36:54 +00004440
4441 // 0-15 are the 16 integer registers.
Chris Lattner8b418682012-02-07 00:39:47 +00004442 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divacky09345d12011-05-18 19:36:54 +00004443 return false;
4444 }
John McCall49e34be2011-08-30 01:42:09 +00004445
Stephen Hines651f13c2014-04-23 16:59:28 -07004446 unsigned getSizeOfUnwindException() const override {
John McCall49e34be2011-08-30 01:42:09 +00004447 if (getABIInfo().isEABI()) return 88;
4448 return TargetCodeGenInfo::getSizeOfUnwindException();
4449 }
Tim Northover64eac852013-10-01 14:34:25 +00004450
4451 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -07004452 CodeGen::CodeGenModule &CGM) const override {
Tim Northover64eac852013-10-01 14:34:25 +00004453 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4454 if (!FD)
4455 return;
4456
4457 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4458 if (!Attr)
4459 return;
4460
4461 const char *Kind;
4462 switch (Attr->getInterrupt()) {
4463 case ARMInterruptAttr::Generic: Kind = ""; break;
4464 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4465 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4466 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4467 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4468 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4469 }
4470
4471 llvm::Function *Fn = cast<llvm::Function>(GV);
4472
4473 Fn->addFnAttr("interrupt", Kind);
4474
4475 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4476 return;
4477
4478 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4479 // however this is not necessarily true on taking any interrupt. Instruct
4480 // the backend to perform a realignment as part of the function prologue.
4481 llvm::AttrBuilder B;
4482 B.addStackAlignmentAttr(8);
4483 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4484 llvm::AttributeSet::get(CGM.getLLVMContext(),
4485 llvm::AttributeSet::FunctionIndex,
4486 B));
4487 }
4488
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004489 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
4490 return false;
4491 // FIXME: backend implementation too restricted, even on Darwin.
4492 // return CGF.getTarget().getTriple().isOSDarwin();
4493 }
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004494};
4495
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004496class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4497 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4498 CodeGen::CodeGenModule &CGM) const;
4499
4500public:
4501 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4502 : ARMTargetCodeGenInfo(CGT, K) {}
4503
4504 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4505 CodeGen::CodeGenModule &CGM) const override;
4506};
4507
4508void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4509 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4510 if (!isa<FunctionDecl>(D))
4511 return;
4512 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4513 return;
4514
4515 llvm::Function *F = cast<llvm::Function>(GV);
4516 F->addFnAttr("stack-probe-size",
4517 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4518}
4519
4520void WindowsARMTargetCodeGenInfo::SetTargetAttributes(
4521 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4522 ARMTargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
4523 addStackProbeSizeTargetAttribute(D, GV, CGM);
4524}
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00004525}
4526
Chris Lattneree5dcd02010-07-29 02:31:05 +00004527void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004528 if (!getCXXABI().classifyReturnType(FI))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004529 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Stephen Hines651f13c2014-04-23 16:59:28 -07004530
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004531 for (auto &I : FI.arguments())
4532 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004533
Anton Korobeynikov414d8962011-04-14 20:06:49 +00004534 // Always honor user-specified calling convention.
4535 if (FI.getCallingConvention() != llvm::CallingConv::C)
4536 return;
4537
John McCallbd7370a2013-02-28 19:01:20 +00004538 llvm::CallingConv::ID cc = getRuntimeCC();
4539 if (cc != llvm::CallingConv::C)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004540 FI.setEffectiveCallingConvention(cc);
John McCallbd7370a2013-02-28 19:01:20 +00004541}
Rafael Espindola25117ab2010-06-16 16:13:39 +00004542
John McCallbd7370a2013-02-28 19:01:20 +00004543/// Return the default calling convention that LLVM will use.
4544llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4545 // The default calling convention that LLVM will infer.
Stephen Hines651f13c2014-04-23 16:59:28 -07004546 if (isEABIHF())
John McCallbd7370a2013-02-28 19:01:20 +00004547 return llvm::CallingConv::ARM_AAPCS_VFP;
4548 else if (isEABI())
4549 return llvm::CallingConv::ARM_AAPCS;
4550 else
4551 return llvm::CallingConv::ARM_APCS;
4552}
4553
4554/// Return the calling convention that our ABI would like us to use
4555/// as the C calling convention.
4556llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004557 switch (getABIKind()) {
John McCallbd7370a2013-02-28 19:01:20 +00004558 case APCS: return llvm::CallingConv::ARM_APCS;
4559 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4560 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004561 }
John McCallbd7370a2013-02-28 19:01:20 +00004562 llvm_unreachable("bad ABI kind");
4563}
4564
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004565void ARMABIInfo::setCCs() {
John McCallbd7370a2013-02-28 19:01:20 +00004566 assert(getRuntimeCC() == llvm::CallingConv::C);
4567
4568 // Don't muddy up the IR with a ton of explicit annotations if
4569 // they'd just match what LLVM will infer from the triple.
4570 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4571 if (abiCC != getLLVMDefaultCC())
4572 RuntimeCC = abiCC;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004573
4574 BuiltinCC = (getABIKind() == APCS ?
4575 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004576}
4577
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004578ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4579 bool isVariadic) const {
Manman Renb3fa55f2012-10-30 23:21:41 +00004580 // 6.1.2.1 The following argument types are VFP CPRCs:
4581 // A single-precision floating-point type (including promoted
4582 // half-precision types); A double-precision floating-point type;
4583 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4584 // with a Base Type of a single- or double-precision floating-point type,
4585 // 64-bit containerized vectors or 128-bit containerized vectors with one
4586 // to four Elements.
Stephen Hines176edba2014-12-01 14:53:08 -08004587 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
4588
4589 Ty = useFirstFieldIfTransparentUnion(Ty);
Manman Renb3fa55f2012-10-30 23:21:41 +00004590
Manman Ren97f81572012-10-16 19:18:39 +00004591 // Handle illegal vector types here.
4592 if (isIllegalVectorType(Ty)) {
4593 uint64_t Size = getContext().getTypeSize(Ty);
4594 if (Size <= 32) {
4595 llvm::Type *ResType =
4596 llvm::Type::getInt32Ty(getVMContext());
4597 return ABIArgInfo::getDirect(ResType);
4598 }
4599 if (Size == 64) {
4600 llvm::Type *ResType = llvm::VectorType::get(
4601 llvm::Type::getInt32Ty(getVMContext()), 2);
4602 return ABIArgInfo::getDirect(ResType);
4603 }
4604 if (Size == 128) {
4605 llvm::Type *ResType = llvm::VectorType::get(
4606 llvm::Type::getInt32Ty(getVMContext()), 4);
4607 return ABIArgInfo::getDirect(ResType);
4608 }
4609 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4610 }
4611
John McCalld608cdb2010-08-22 10:59:02 +00004612 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004613 // Treat an enum type as its underlying type.
Stephen Hines651f13c2014-04-23 16:59:28 -07004614 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004615 Ty = EnumTy->getDecl()->getIntegerType();
Stephen Hines651f13c2014-04-23 16:59:28 -07004616 }
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004617
Stephen Hines176edba2014-12-01 14:53:08 -08004618 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4619 : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004620 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00004621
Stephen Hines651f13c2014-04-23 16:59:28 -07004622 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northoverf5c3a252013-06-21 22:49:34 +00004623 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Stephen Hines651f13c2014-04-23 16:59:28 -07004624 }
Tim Northoverf5c3a252013-06-21 22:49:34 +00004625
Daniel Dunbar42025572009-09-14 21:54:03 +00004626 // Ignore empty records.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004627 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar42025572009-09-14 21:54:03 +00004628 return ABIArgInfo::getIgnore();
4629
Stephen Hines176edba2014-12-01 14:53:08 -08004630 if (IsEffectivelyAAPCS_VFP) {
Manman Renb3fa55f2012-10-30 23:21:41 +00004631 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4632 // into VFP registers.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004633 const Type *Base = nullptr;
Manman Renb3fa55f2012-10-30 23:21:41 +00004634 uint64_t Members = 0;
Stephen Hines176edba2014-12-01 14:53:08 -08004635 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004636 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Renb3fa55f2012-10-30 23:21:41 +00004637 // Base can be a floating-point or a vector.
Stephen Hines176edba2014-12-01 14:53:08 -08004638 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004639 }
Bob Wilson194f06a2011-08-03 05:58:22 +00004640 }
4641
Manman Ren634b3d22012-08-13 21:23:55 +00004642 // Support byval for ARM.
Manman Rencb489dd2012-11-06 19:05:29 +00004643 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4644 // most 8-byte. We realign the indirect argument if type alignment is bigger
4645 // than ABI alignment.
Manman Renfd1ba912012-11-05 22:42:46 +00004646 uint64_t ABIAlign = 4;
4647 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4648 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4649 getABIKind() == ARMABIInfo::AAPCS)
4650 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren885ad692012-11-06 04:58:01 +00004651 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004652 // Update Allocated GPRs. Since this is only used when the size of the
4653 // argument is greater than 64 bytes, this will always use up any available
4654 // registers (of which there are 4). We also don't care about getting the
4655 // alignment right, because general-purpose registers cannot be back-filled.
Stephen Hines651f13c2014-04-23 16:59:28 -07004656 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Rencb489dd2012-11-06 19:05:29 +00004657 /*Realign=*/TyAlign > ABIAlign);
Eli Friedman79f30982012-08-09 00:31:40 +00004658 }
4659
Daniel Dunbar8aa87c72010-09-23 01:54:28 +00004660 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2acc6e32011-07-18 04:24:23 +00004661 llvm::Type* ElemTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004662 unsigned SizeRegs;
Eli Friedman79f30982012-08-09 00:31:40 +00004663 // FIXME: Try to match the types of the arguments more accurately where
4664 // we can.
4665 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson53fc1a62011-08-01 23:39:04 +00004666 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4667 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren78eb76e2012-06-25 22:04:00 +00004668 } else {
Manman Ren78eb76e2012-06-25 22:04:00 +00004669 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4670 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastings67d097e2011-04-27 17:24:02 +00004671 }
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00004672
Stephen Hines176edba2014-12-01 14:53:08 -08004673 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004674}
4675
Chris Lattnera3c109b2010-07-29 02:16:43 +00004676static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar98303b92009-09-13 08:03:58 +00004677 llvm::LLVMContext &VMContext) {
4678 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4679 // is called integer-like if its size is less than or equal to one word, and
4680 // the offset of each of its addressable sub-fields is zero.
4681
4682 uint64_t Size = Context.getTypeSize(Ty);
4683
4684 // Check that the type fits in a word.
4685 if (Size > 32)
4686 return false;
4687
4688 // FIXME: Handle vector types!
4689 if (Ty->isVectorType())
4690 return false;
4691
Daniel Dunbarb0d58192009-09-14 02:20:34 +00004692 // Float types are never treated as "integer like".
4693 if (Ty->isRealFloatingType())
4694 return false;
4695
Daniel Dunbar98303b92009-09-13 08:03:58 +00004696 // If this is a builtin or pointer type then it is ok.
John McCall183700f2009-09-21 23:43:11 +00004697 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar98303b92009-09-13 08:03:58 +00004698 return true;
4699
Daniel Dunbar45815812010-02-01 23:31:26 +00004700 // Small complex integer types are "integer like".
4701 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4702 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar98303b92009-09-13 08:03:58 +00004703
4704 // Single element and zero sized arrays should be allowed, by the definition
4705 // above, but they are not.
4706
4707 // Otherwise, it must be a record type.
4708 const RecordType *RT = Ty->getAs<RecordType>();
4709 if (!RT) return false;
4710
4711 // Ignore records with flexible arrays.
4712 const RecordDecl *RD = RT->getDecl();
4713 if (RD->hasFlexibleArrayMember())
4714 return false;
4715
4716 // Check that all sub-fields are at offset 0, and are themselves "integer
4717 // like".
4718 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4719
4720 bool HadField = false;
4721 unsigned idx = 0;
4722 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4723 i != e; ++i, ++idx) {
David Blaikie581deb32012-06-06 20:45:41 +00004724 const FieldDecl *FD = *i;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004725
Daniel Dunbar679855a2010-01-29 03:22:29 +00004726 // Bit-fields are not addressable, we only need to verify they are "integer
4727 // like". We still have to disallow a subsequent non-bitfield, for example:
4728 // struct { int : 0; int x }
4729 // is non-integer like according to gcc.
4730 if (FD->isBitField()) {
4731 if (!RD->isUnion())
4732 HadField = true;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004733
Daniel Dunbar679855a2010-01-29 03:22:29 +00004734 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4735 return false;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004736
Daniel Dunbar679855a2010-01-29 03:22:29 +00004737 continue;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004738 }
4739
Daniel Dunbar679855a2010-01-29 03:22:29 +00004740 // Check if this field is at offset 0.
4741 if (Layout.getFieldOffset(idx) != 0)
4742 return false;
4743
Daniel Dunbar98303b92009-09-13 08:03:58 +00004744 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4745 return false;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00004746
Daniel Dunbar679855a2010-01-29 03:22:29 +00004747 // Only allow at most one field in a structure. This doesn't match the
4748 // wording above, but follows gcc in situations with a field following an
4749 // empty structure.
Daniel Dunbar98303b92009-09-13 08:03:58 +00004750 if (!RD->isUnion()) {
4751 if (HadField)
4752 return false;
4753
4754 HadField = true;
4755 }
4756 }
4757
4758 return true;
4759}
4760
Stephen Hines651f13c2014-04-23 16:59:28 -07004761ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4762 bool isVariadic) const {
Stephen Hines176edba2014-12-01 14:53:08 -08004763 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
4764
Daniel Dunbar98303b92009-09-13 08:03:58 +00004765 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004766 return ABIArgInfo::getIgnore();
Daniel Dunbar98303b92009-09-13 08:03:58 +00004767
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00004768 // Large vector types should be returned via memory.
Stephen Hines651f13c2014-04-23 16:59:28 -07004769 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00004770 return ABIArgInfo::getIndirect(0);
Stephen Hines651f13c2014-04-23 16:59:28 -07004771 }
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00004772
John McCalld608cdb2010-08-22 10:59:02 +00004773 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004774 // Treat an enum type as its underlying type.
4775 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4776 RetTy = EnumTy->getDecl()->getIntegerType();
4777
Stephen Hines176edba2014-12-01 14:53:08 -08004778 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4779 : ABIArgInfo::getDirect();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004780 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00004781
4782 // Are we following APCS?
4783 if (getABIKind() == APCS) {
Chris Lattnera3c109b2010-07-29 02:16:43 +00004784 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar98303b92009-09-13 08:03:58 +00004785 return ABIArgInfo::getIgnore();
4786
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00004787 // Complex types are all returned as packed integers.
4788 //
4789 // FIXME: Consider using 2 x vector types if the back end handles them
4790 // correctly.
4791 if (RetTy->isAnyComplexType())
Stephen Hines176edba2014-12-01 14:53:08 -08004792 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4793 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00004794
Daniel Dunbar98303b92009-09-13 08:03:58 +00004795 // Integer like structures are returned in r0.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004796 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar98303b92009-09-13 08:03:58 +00004797 // Return in the smallest viable integer type.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004798 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar98303b92009-09-13 08:03:58 +00004799 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00004800 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00004801 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00004802 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4803 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00004804 }
4805
4806 // Otherwise return in memory.
4807 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004808 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00004809
4810 // Otherwise this is an AAPCS variant.
4811
Chris Lattnera3c109b2010-07-29 02:16:43 +00004812 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar16a08082009-09-14 00:56:55 +00004813 return ABIArgInfo::getIgnore();
4814
Bob Wilson3b694fa2011-11-02 04:51:36 +00004815 // Check for homogeneous aggregates with AAPCS-VFP.
Stephen Hines176edba2014-12-01 14:53:08 -08004816 if (IsEffectivelyAAPCS_VFP) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004817 const Type *Base = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08004818 uint64_t Members;
4819 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004820 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson3b694fa2011-11-02 04:51:36 +00004821 // Homogeneous Aggregates are returned directly.
Stephen Hines176edba2014-12-01 14:53:08 -08004822 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004823 }
Bob Wilson3b694fa2011-11-02 04:51:36 +00004824 }
4825
Daniel Dunbar98303b92009-09-13 08:03:58 +00004826 // Aggregates <= 4 bytes are returned in r0; other aggregates
4827 // are returned indirectly.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004828 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar16a08082009-09-14 00:56:55 +00004829 if (Size <= 32) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004830 if (getDataLayout().isBigEndian())
4831 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
4832 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
4833
Daniel Dunbar16a08082009-09-14 00:56:55 +00004834 // Return in the smallest viable integer type.
4835 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00004836 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00004837 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00004838 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4839 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00004840 }
4841
Daniel Dunbar98303b92009-09-13 08:03:58 +00004842 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004843}
4844
Manman Ren97f81572012-10-16 19:18:39 +00004845/// isIllegalVector - check whether Ty is an illegal vector type.
4846bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4847 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4848 // Check whether VT is legal.
4849 unsigned NumElements = VT->getNumElements();
Manman Ren97f81572012-10-16 19:18:39 +00004850 // NumElements should be power of 2.
Stephen Hinesc3c9d172013-01-15 23:50:35 -08004851 if (((NumElements & (NumElements - 1)) != 0) && NumElements != 3)
Manman Ren97f81572012-10-16 19:18:39 +00004852 return true;
Manman Ren97f81572012-10-16 19:18:39 +00004853 }
4854 return false;
4855}
4856
Stephen Hines176edba2014-12-01 14:53:08 -08004857bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4858 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4859 // double, or 64-bit or 128-bit vectors.
4860 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4861 if (BT->getKind() == BuiltinType::Float ||
4862 BT->getKind() == BuiltinType::Double ||
4863 BT->getKind() == BuiltinType::LongDouble)
4864 return true;
4865 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4866 unsigned VecSize = getContext().getTypeSize(VT);
4867 if (VecSize == 64 || VecSize == 128)
4868 return true;
4869 }
4870 return false;
4871}
4872
4873bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4874 uint64_t Members) const {
4875 return Members <= 4;
4876}
4877
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004878llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner77b89b82010-06-27 07:15:29 +00004879 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00004880 llvm::Type *BP = CGF.Int8PtrTy;
4881 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004882
4883 CGBuilderTy &Builder = CGF.Builder;
Chris Lattner8b418682012-02-07 00:39:47 +00004884 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004885 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rend105e732012-10-16 19:01:37 +00004886
Tim Northover373ac0a2013-06-21 23:05:33 +00004887 if (isEmptyRecord(getContext(), Ty, true)) {
4888 // These are ignored for parameter passing purposes.
4889 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4890 return Builder.CreateBitCast(Addr, PTy);
4891 }
4892
Manman Rend105e732012-10-16 19:01:37 +00004893 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindolae164c182011-08-02 22:33:37 +00004894 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Ren97f81572012-10-16 19:18:39 +00004895 bool IsIndirect = false;
Manman Rend105e732012-10-16 19:01:37 +00004896
4897 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4898 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren93371022012-10-16 19:51:48 +00004899 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4900 getABIKind() == ARMABIInfo::AAPCS)
4901 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4902 else
4903 TyAlign = 4;
Stephen Hinesc3c9d172013-01-15 23:50:35 -08004904 // Use indirect if size of the illegal vector is bigger than 32 bytes.
4905 if (isIllegalVectorType(Ty) && Size > 32) {
Manman Ren97f81572012-10-16 19:18:39 +00004906 IsIndirect = true;
4907 Size = 4;
4908 TyAlign = 4;
4909 }
Manman Rend105e732012-10-16 19:01:37 +00004910
4911 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindolae164c182011-08-02 22:33:37 +00004912 if (TyAlign > 4) {
4913 assert((TyAlign & (TyAlign - 1)) == 0 &&
4914 "Alignment is not power of 2!");
4915 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4916 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4917 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rend105e732012-10-16 19:01:37 +00004918 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindolae164c182011-08-02 22:33:37 +00004919 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004920
4921 uint64_t Offset =
Manman Rend105e732012-10-16 19:01:37 +00004922 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004923 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00004924 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004925 "ap.next");
4926 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4927
Manman Ren97f81572012-10-16 19:18:39 +00004928 if (IsIndirect)
4929 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren93371022012-10-16 19:51:48 +00004930 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rend105e732012-10-16 19:01:37 +00004931 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4932 // may not be correctly aligned for the vector type. We create an aligned
4933 // temporary space and copy the content over from ap.cur to the temporary
4934 // space. This is necessary if the natural alignment of the type is greater
4935 // than the ABI alignment.
4936 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4937 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4938 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4939 "var.align");
4940 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4941 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4942 Builder.CreateMemCpy(Dst, Src,
4943 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4944 TyAlign, false);
4945 Addr = AlignedTemp; //The content is in aligned location.
4946 }
4947 llvm::Type *PTy =
4948 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4949 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4950
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004951 return AddrTyped;
4952}
4953
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004954//===----------------------------------------------------------------------===//
Justin Holewinski2c585b92012-05-24 17:43:12 +00004955// NVPTX ABI Implementation
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004956//===----------------------------------------------------------------------===//
4957
4958namespace {
4959
Justin Holewinski2c585b92012-05-24 17:43:12 +00004960class NVPTXABIInfo : public ABIInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004961public:
Justin Holewinskidca8f332013-03-30 14:38:24 +00004962 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004963
4964 ABIArgInfo classifyReturnType(QualType RetTy) const;
4965 ABIArgInfo classifyArgumentType(QualType Ty) const;
4966
Stephen Hines651f13c2014-04-23 16:59:28 -07004967 void computeInfo(CGFunctionInfo &FI) const override;
4968 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4969 CodeGenFunction &CFG) const override;
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004970};
4971
Justin Holewinski2c585b92012-05-24 17:43:12 +00004972class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004973public:
Justin Holewinski2c585b92012-05-24 17:43:12 +00004974 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4975 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07004976
4977 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4978 CodeGen::CodeGenModule &M) const override;
Justin Holewinskidca8f332013-03-30 14:38:24 +00004979private:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004980 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
4981 // resulting MDNode to the nvvm.annotations MDNode.
4982 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004983};
4984
Justin Holewinski2c585b92012-05-24 17:43:12 +00004985ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004986 if (RetTy->isVoidType())
4987 return ABIArgInfo::getIgnore();
Bill Wendling846ff9f2013-11-21 23:31:45 +00004988
4989 // note: this is different from default ABI
4990 if (!RetTy->isScalarType())
4991 return ABIArgInfo::getDirect();
4992
4993 // Treat an enum type as its underlying type.
4994 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4995 RetTy = EnumTy->getDecl()->getIntegerType();
4996
4997 return (RetTy->isPromotableIntegerType() ?
4998 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004999}
5000
Justin Holewinski2c585b92012-05-24 17:43:12 +00005001ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Bill Wendling846ff9f2013-11-21 23:31:45 +00005002 // Treat an enum type as its underlying type.
5003 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5004 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005005
Stephen Hines176edba2014-12-01 14:53:08 -08005006 // Return aggregates type as indirect by value
5007 if (isAggregateTypeForABI(Ty))
5008 return ABIArgInfo::getIndirect(0, /* byval */ true);
5009
Bill Wendling846ff9f2013-11-21 23:31:45 +00005010 return (Ty->isPromotableIntegerType() ?
5011 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005012}
5013
Justin Holewinski2c585b92012-05-24 17:43:12 +00005014void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005015 if (!getCXXABI().classifyReturnType(FI))
5016 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07005017 for (auto &I : FI.arguments())
5018 I.info = classifyArgumentType(I.type);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005019
5020 // Always honor user-specified calling convention.
5021 if (FI.getCallingConvention() != llvm::CallingConv::C)
5022 return;
5023
John McCallbd7370a2013-02-28 19:01:20 +00005024 FI.setEffectiveCallingConvention(getRuntimeCC());
5025}
5026
Justin Holewinski2c585b92012-05-24 17:43:12 +00005027llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5028 CodeGenFunction &CFG) const {
5029 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005030}
5031
Justin Holewinski2c585b92012-05-24 17:43:12 +00005032void NVPTXTargetCodeGenInfo::
5033SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5034 CodeGen::CodeGenModule &M) const{
Justin Holewinski818eafb2011-10-05 17:58:44 +00005035 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5036 if (!FD) return;
5037
5038 llvm::Function *F = cast<llvm::Function>(GV);
5039
5040 // Perform special handling in OpenCL mode
David Blaikie4e4d0842012-03-11 07:00:24 +00005041 if (M.getLangOpts().OpenCL) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00005042 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00005043 // By default, all functions are device functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00005044 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00005045 // OpenCL __kernel functions get kernel metadata
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005046 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5047 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski818eafb2011-10-05 17:58:44 +00005048 // And kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00005049 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski818eafb2011-10-05 17:58:44 +00005050 }
Peter Collingbourne744d90b2011-10-06 16:49:54 +00005051 }
Justin Holewinski818eafb2011-10-05 17:58:44 +00005052
Peter Collingbourne744d90b2011-10-06 16:49:54 +00005053 // Perform special handling in CUDA mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00005054 if (M.getLangOpts().CUDA) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00005055 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne744d90b2011-10-06 16:49:54 +00005056 // __global__ functions cannot be called from the device, we do not
5057 // need to set the noinline attribute.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005058 if (FD->hasAttr<CUDAGlobalAttr>()) {
5059 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5060 addNVVMMetadata(F, "kernel", 1);
5061 }
5062 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5063 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5064 addNVVMMetadata(F, "maxntidx",
5065 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5066 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5067 // zero value from getMinBlocks either means it was not specified in
5068 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5069 // don't have to add a PTX directive.
5070 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5071 if (MinCTASM > 0) {
5072 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5073 addNVVMMetadata(F, "minctasm", MinCTASM);
5074 }
5075 }
Justin Holewinski818eafb2011-10-05 17:58:44 +00005076 }
5077}
5078
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005079void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5080 int Operand) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00005081 llvm::Module *M = F->getParent();
5082 llvm::LLVMContext &Ctx = M->getContext();
5083
5084 // Get "nvvm.annotations" metadata node
5085 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5086
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005087 llvm::Metadata *MDVals[] = {
5088 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5089 llvm::ConstantAsMetadata::get(
5090 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinskidca8f332013-03-30 14:38:24 +00005091 // Append metadata to nvvm.annotations
5092 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5093}
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005094}
5095
5096//===----------------------------------------------------------------------===//
Ulrich Weigandb8409212013-05-06 16:26:41 +00005097// SystemZ ABI Implementation
5098//===----------------------------------------------------------------------===//
5099
5100namespace {
5101
5102class SystemZABIInfo : public ABIInfo {
5103public:
5104 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5105
5106 bool isPromotableIntegerType(QualType Ty) const;
5107 bool isCompoundType(QualType Ty) const;
5108 bool isFPArgumentType(QualType Ty) const;
5109
5110 ABIArgInfo classifyReturnType(QualType RetTy) const;
5111 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5112
Stephen Hines651f13c2014-04-23 16:59:28 -07005113 void computeInfo(CGFunctionInfo &FI) const override {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005114 if (!getCXXABI().classifyReturnType(FI))
5115 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07005116 for (auto &I : FI.arguments())
5117 I.info = classifyArgumentType(I.type);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005118 }
5119
Stephen Hines651f13c2014-04-23 16:59:28 -07005120 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5121 CodeGenFunction &CGF) const override;
Ulrich Weigandb8409212013-05-06 16:26:41 +00005122};
5123
5124class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5125public:
5126 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5127 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5128};
5129
5130}
5131
5132bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5133 // Treat an enum type as its underlying type.
5134 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5135 Ty = EnumTy->getDecl()->getIntegerType();
5136
5137 // Promotable integer types are required to be promoted by the ABI.
5138 if (Ty->isPromotableIntegerType())
5139 return true;
5140
5141 // 32-bit values must also be promoted.
5142 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5143 switch (BT->getKind()) {
5144 case BuiltinType::Int:
5145 case BuiltinType::UInt:
5146 return true;
5147 default:
5148 return false;
5149 }
5150 return false;
5151}
5152
5153bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5154 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5155}
5156
5157bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5158 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5159 switch (BT->getKind()) {
5160 case BuiltinType::Float:
5161 case BuiltinType::Double:
5162 return true;
5163 default:
5164 return false;
5165 }
5166
5167 if (const RecordType *RT = Ty->getAsStructureType()) {
5168 const RecordDecl *RD = RT->getDecl();
5169 bool Found = false;
5170
5171 // If this is a C++ record, check the bases first.
5172 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Stephen Hines651f13c2014-04-23 16:59:28 -07005173 for (const auto &I : CXXRD->bases()) {
5174 QualType Base = I.getType();
Ulrich Weigandb8409212013-05-06 16:26:41 +00005175
5176 // Empty bases don't affect things either way.
5177 if (isEmptyRecord(getContext(), Base, true))
5178 continue;
5179
5180 if (Found)
5181 return false;
5182 Found = isFPArgumentType(Base);
5183 if (!Found)
5184 return false;
5185 }
5186
5187 // Check the fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07005188 for (const auto *FD : RD->fields()) {
Ulrich Weigandb8409212013-05-06 16:26:41 +00005189 // Empty bitfields don't affect things either way.
5190 // Unlike isSingleElementStruct(), empty structure and array fields
5191 // do count. So do anonymous bitfields that aren't zero-sized.
5192 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5193 return true;
5194
5195 // Unlike isSingleElementStruct(), arrays do not count.
5196 // Nested isFPArgumentType structures still do though.
5197 if (Found)
5198 return false;
5199 Found = isFPArgumentType(FD->getType());
5200 if (!Found)
5201 return false;
5202 }
5203
5204 // Unlike isSingleElementStruct(), trailing padding is allowed.
5205 // An 8-byte aligned struct s { float f; } is passed as a double.
5206 return Found;
5207 }
5208
5209 return false;
5210}
5211
5212llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5213 CodeGenFunction &CGF) const {
5214 // Assume that va_list type is correct; should be pointer to LLVM type:
5215 // struct {
5216 // i64 __gpr;
5217 // i64 __fpr;
5218 // i8 *__overflow_arg_area;
5219 // i8 *__reg_save_area;
5220 // };
5221
5222 // Every argument occupies 8 bytes and is passed by preference in either
5223 // GPRs or FPRs.
5224 Ty = CGF.getContext().getCanonicalType(Ty);
5225 ABIArgInfo AI = classifyArgumentType(Ty);
5226 bool InFPRs = isFPArgumentType(Ty);
5227
5228 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5229 bool IsIndirect = AI.isIndirect();
5230 unsigned UnpaddedBitSize;
5231 if (IsIndirect) {
5232 APTy = llvm::PointerType::getUnqual(APTy);
5233 UnpaddedBitSize = 64;
5234 } else
5235 UnpaddedBitSize = getContext().getTypeSize(Ty);
5236 unsigned PaddedBitSize = 64;
5237 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5238
5239 unsigned PaddedSize = PaddedBitSize / 8;
5240 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5241
5242 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5243 if (InFPRs) {
5244 MaxRegs = 4; // Maximum of 4 FPR arguments
5245 RegCountField = 1; // __fpr
5246 RegSaveIndex = 16; // save offset for f0
5247 RegPadding = 0; // floats are passed in the high bits of an FPR
5248 } else {
5249 MaxRegs = 5; // Maximum of 5 GPR arguments
5250 RegCountField = 0; // __gpr
5251 RegSaveIndex = 2; // save offset for r2
5252 RegPadding = Padding; // values are passed in the low bits of a GPR
5253 }
5254
5255 llvm::Value *RegCountPtr =
5256 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5257 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5258 llvm::Type *IndexTy = RegCount->getType();
5259 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5260 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Stephen Hines651f13c2014-04-23 16:59:28 -07005261 "fits_in_regs");
Ulrich Weigandb8409212013-05-06 16:26:41 +00005262
5263 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5264 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5265 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5266 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5267
5268 // Emit code to load the value if it was passed in registers.
5269 CGF.EmitBlock(InRegBlock);
5270
5271 // Work out the address of an argument register.
5272 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5273 llvm::Value *ScaledRegCount =
5274 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5275 llvm::Value *RegBase =
5276 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5277 llvm::Value *RegOffset =
5278 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5279 llvm::Value *RegSaveAreaPtr =
5280 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5281 llvm::Value *RegSaveArea =
5282 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5283 llvm::Value *RawRegAddr =
5284 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5285 llvm::Value *RegAddr =
5286 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5287
5288 // Update the register count
5289 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5290 llvm::Value *NewRegCount =
5291 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5292 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5293 CGF.EmitBranch(ContBlock);
5294
5295 // Emit code to load the value if it was passed in memory.
5296 CGF.EmitBlock(InMemBlock);
5297
5298 // Work out the address of a stack argument.
5299 llvm::Value *OverflowArgAreaPtr =
5300 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5301 llvm::Value *OverflowArgArea =
5302 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5303 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5304 llvm::Value *RawMemAddr =
5305 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5306 llvm::Value *MemAddr =
5307 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5308
5309 // Update overflow_arg_area_ptr pointer
5310 llvm::Value *NewOverflowArgArea =
5311 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5312 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5313 CGF.EmitBranch(ContBlock);
5314
5315 // Return the appropriate result.
5316 CGF.EmitBlock(ContBlock);
5317 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5318 ResAddr->addIncoming(RegAddr, InRegBlock);
5319 ResAddr->addIncoming(MemAddr, InMemBlock);
5320
5321 if (IsIndirect)
5322 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5323
5324 return ResAddr;
5325}
5326
Ulrich Weigandb8409212013-05-06 16:26:41 +00005327ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5328 if (RetTy->isVoidType())
5329 return ABIArgInfo::getIgnore();
5330 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5331 return ABIArgInfo::getIndirect(0);
5332 return (isPromotableIntegerType(RetTy) ?
5333 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5334}
5335
5336ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5337 // Handle the generic C++ ABI.
Mark Lacey23630722013-10-06 01:33:34 +00005338 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigandb8409212013-05-06 16:26:41 +00005339 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5340
5341 // Integers and enums are extended to full register width.
5342 if (isPromotableIntegerType(Ty))
5343 return ABIArgInfo::getExtend();
5344
5345 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5346 uint64_t Size = getContext().getTypeSize(Ty);
5347 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandiford148a3522013-12-04 10:02:36 +00005348 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005349
5350 // Handle small structures.
5351 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5352 // Structures with flexible arrays have variable length, so really
5353 // fail the size test above.
5354 const RecordDecl *RD = RT->getDecl();
5355 if (RD->hasFlexibleArrayMember())
Richard Sandiford148a3522013-12-04 10:02:36 +00005356 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005357
5358 // The structure is passed as an unextended integer, a float, or a double.
5359 llvm::Type *PassTy;
5360 if (isFPArgumentType(Ty)) {
5361 assert(Size == 32 || Size == 64);
5362 if (Size == 32)
5363 PassTy = llvm::Type::getFloatTy(getVMContext());
5364 else
5365 PassTy = llvm::Type::getDoubleTy(getVMContext());
5366 } else
5367 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5368 return ABIArgInfo::getDirect(PassTy);
5369 }
5370
5371 // Non-structure compounds are passed indirectly.
5372 if (isCompoundType(Ty))
Richard Sandiford148a3522013-12-04 10:02:36 +00005373 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005374
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005375 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005376}
5377
5378//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005379// MSP430 ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005380//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005381
5382namespace {
5383
5384class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5385public:
Chris Lattnerea044322010-07-29 02:01:43 +00005386 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5387 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005388 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -07005389 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005390};
5391
5392}
5393
5394void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5395 llvm::GlobalValue *GV,
5396 CodeGen::CodeGenModule &M) const {
5397 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5398 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5399 // Handle 'interrupt' attribute:
5400 llvm::Function *F = cast<llvm::Function>(GV);
5401
5402 // Step 1: Set ISR calling convention.
5403 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5404
5405 // Step 2: Add attributes goodness.
Bill Wendling72390b32012-12-20 19:27:06 +00005406 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005407
5408 // Step 3: Emit ISR vector alias.
Anton Korobeynikovf419a852012-11-26 18:59:10 +00005409 unsigned Num = attr->getNumber() / 2;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005410 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5411 "__isr_" + Twine(Num), F);
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005412 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005413 }
5414}
5415
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005416//===----------------------------------------------------------------------===//
John McCallaeeb7012010-05-27 06:19:26 +00005417// MIPS ABI Implementation. This works for both little-endian and
5418// big-endian variants.
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005419//===----------------------------------------------------------------------===//
5420
John McCallaeeb7012010-05-27 06:19:26 +00005421namespace {
Akira Hatanaka619e8872011-06-02 00:09:17 +00005422class MipsABIInfo : public ABIInfo {
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005423 bool IsO32;
Akira Hatanakac359f202012-07-03 19:24:06 +00005424 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5425 void CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00005426 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005427 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005428 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005429 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005430public:
Akira Hatanakab551dd32011-11-03 00:05:50 +00005431 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakac359f202012-07-03 19:24:06 +00005432 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
5433 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanaka619e8872011-06-02 00:09:17 +00005434
5435 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005436 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Stephen Hines651f13c2014-04-23 16:59:28 -07005437 void computeInfo(CGFunctionInfo &FI) const override;
5438 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5439 CodeGenFunction &CGF) const override;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005440};
5441
John McCallaeeb7012010-05-27 06:19:26 +00005442class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanakae624fa02011-09-20 18:23:28 +00005443 unsigned SizeOfUnwindException;
John McCallaeeb7012010-05-27 06:19:26 +00005444public:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005445 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5446 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
5447 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCallaeeb7012010-05-27 06:19:26 +00005448
Stephen Hines651f13c2014-04-23 16:59:28 -07005449 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallaeeb7012010-05-27 06:19:26 +00005450 return 29;
5451 }
5452
Reed Kotler7dfd1822013-01-16 17:10:28 +00005453 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -07005454 CodeGen::CodeGenModule &CGM) const override {
Reed Kotlerad4b8b42013-03-13 20:40:30 +00005455 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5456 if (!FD) return;
Rafael Espindolad8e6d6d2013-03-19 14:32:23 +00005457 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotlerad4b8b42013-03-13 20:40:30 +00005458 if (FD->hasAttr<Mips16Attr>()) {
5459 Fn->addFnAttr("mips16");
5460 }
5461 else if (FD->hasAttr<NoMips16Attr>()) {
5462 Fn->addFnAttr("nomips16");
5463 }
Reed Kotler7dfd1822013-01-16 17:10:28 +00005464 }
Reed Kotlerad4b8b42013-03-13 20:40:30 +00005465
John McCallaeeb7012010-05-27 06:19:26 +00005466 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07005467 llvm::Value *Address) const override;
John McCall49e34be2011-08-30 01:42:09 +00005468
Stephen Hines651f13c2014-04-23 16:59:28 -07005469 unsigned getSizeOfUnwindException() const override {
Akira Hatanakae624fa02011-09-20 18:23:28 +00005470 return SizeOfUnwindException;
John McCall49e34be2011-08-30 01:42:09 +00005471 }
John McCallaeeb7012010-05-27 06:19:26 +00005472};
5473}
5474
Akira Hatanakac359f202012-07-03 19:24:06 +00005475void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00005476 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00005477 llvm::IntegerType *IntTy =
5478 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005479
5480 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5481 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5482 ArgList.push_back(IntTy);
5483
5484 // If necessary, add one more integer type to ArgList.
5485 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5486
5487 if (R)
5488 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005489}
5490
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005491// In N32/64, an aligned double precision floating point field is passed in
5492// a register.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005493llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00005494 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5495
5496 if (IsO32) {
5497 CoerceToIntArgs(TySize, ArgList);
5498 return llvm::StructType::get(getVMContext(), ArgList);
5499 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005500
Akira Hatanaka2afd23d2012-01-12 00:52:17 +00005501 if (Ty->isComplexType())
5502 return CGT.ConvertType(Ty);
Akira Hatanaka6d1080f2012-01-10 23:12:19 +00005503
Akira Hatanakaa34e9212012-02-09 19:54:16 +00005504 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005505
Akira Hatanakac359f202012-07-03 19:24:06 +00005506 // Unions/vectors are passed in integer registers.
5507 if (!RT || !RT->isStructureOrClassType()) {
5508 CoerceToIntArgs(TySize, ArgList);
5509 return llvm::StructType::get(getVMContext(), ArgList);
5510 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005511
5512 const RecordDecl *RD = RT->getDecl();
5513 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005514 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005515
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005516 uint64_t LastOffset = 0;
5517 unsigned idx = 0;
5518 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5519
Akira Hatanakaa34e9212012-02-09 19:54:16 +00005520 // Iterate over fields in the struct/class and check if there are any aligned
5521 // double fields.
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005522 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5523 i != e; ++i, ++idx) {
David Blaikie262bc182012-04-30 02:36:29 +00005524 const QualType Ty = i->getType();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005525 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5526
5527 if (!BT || BT->getKind() != BuiltinType::Double)
5528 continue;
5529
5530 uint64_t Offset = Layout.getFieldOffset(idx);
5531 if (Offset % 64) // Ignore doubles that are not aligned.
5532 continue;
5533
5534 // Add ((Offset - LastOffset) / 64) args of type i64.
5535 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5536 ArgList.push_back(I64);
5537
5538 // Add double type.
5539 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5540 LastOffset = Offset + 64;
5541 }
5542
Akira Hatanakac359f202012-07-03 19:24:06 +00005543 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5544 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005545
5546 return llvm::StructType::get(getVMContext(), ArgList);
5547}
5548
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005549llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5550 uint64_t Offset) const {
5551 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005552 return nullptr;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005553
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005554 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005555}
Akira Hatanaka9659d592012-01-10 22:44:52 +00005556
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005557ABIArgInfo
5558MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005559 Ty = useFirstFieldIfTransparentUnion(Ty);
5560
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005561 uint64_t OrigOffset = Offset;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005562 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005563 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005564
Akira Hatanakac359f202012-07-03 19:24:06 +00005565 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5566 (uint64_t)StackAlignInBytes);
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005567 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5568 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005569
Akira Hatanakac359f202012-07-03 19:24:06 +00005570 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanaka619e8872011-06-02 00:09:17 +00005571 // Ignore empty aggregates.
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005572 if (TySize == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00005573 return ABIArgInfo::getIgnore();
5574
Mark Lacey23630722013-10-06 01:33:34 +00005575 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005576 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005577 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005578 }
Akira Hatanaka511949b2011-08-01 18:09:58 +00005579
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005580 // If we have reached here, aggregates are passed directly by coercing to
5581 // another structure type. Padding is inserted if the offset of the
5582 // aggregate is unaligned.
Stephen Hines176edba2014-12-01 14:53:08 -08005583 ABIArgInfo ArgInfo =
5584 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5585 getPaddingType(OrigOffset, CurrOffset));
5586 ArgInfo.setInReg(true);
5587 return ArgInfo;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005588 }
5589
5590 // Treat an enum type as its underlying type.
5591 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5592 Ty = EnumTy->getDecl()->getIntegerType();
5593
Stephen Hines176edba2014-12-01 14:53:08 -08005594 // All integral types are promoted to the GPR width.
5595 if (Ty->isIntegralOrEnumerationType())
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005596 return ABIArgInfo::getExtend();
5597
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005598 return ABIArgInfo::getDirect(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005599 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00005600}
5601
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005602llvm::Type*
5603MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakada54ff32012-02-09 18:49:26 +00005604 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakac359f202012-07-03 19:24:06 +00005605 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005606
Akira Hatanakada54ff32012-02-09 18:49:26 +00005607 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005608 const RecordDecl *RD = RT->getDecl();
Akira Hatanakada54ff32012-02-09 18:49:26 +00005609 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5610 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005611
Akira Hatanakada54ff32012-02-09 18:49:26 +00005612 // N32/64 returns struct/classes in floating point registers if the
5613 // following conditions are met:
5614 // 1. The size of the struct/class is no larger than 128-bit.
5615 // 2. The struct/class has one or two fields all of which are floating
5616 // point types.
5617 // 3. The offset of the first field is zero (this follows what gcc does).
5618 //
5619 // Any other composite results are returned in integer registers.
5620 //
5621 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5622 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5623 for (; b != e; ++b) {
David Blaikie262bc182012-04-30 02:36:29 +00005624 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005625
Akira Hatanakada54ff32012-02-09 18:49:26 +00005626 if (!BT || !BT->isFloatingPoint())
5627 break;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005628
David Blaikie262bc182012-04-30 02:36:29 +00005629 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakada54ff32012-02-09 18:49:26 +00005630 }
5631
5632 if (b == e)
5633 return llvm::StructType::get(getVMContext(), RTList,
5634 RD->hasAttr<PackedAttr>());
5635
5636 RTList.clear();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005637 }
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005638 }
5639
Akira Hatanakac359f202012-07-03 19:24:06 +00005640 CoerceToIntArgs(Size, RTList);
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005641 return llvm::StructType::get(getVMContext(), RTList);
5642}
5643
Akira Hatanaka619e8872011-06-02 00:09:17 +00005644ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanakaa8536c02012-01-23 23:18:57 +00005645 uint64_t Size = getContext().getTypeSize(RetTy);
5646
Stephen Hines176edba2014-12-01 14:53:08 -08005647 if (RetTy->isVoidType())
5648 return ABIArgInfo::getIgnore();
5649
5650 // O32 doesn't treat zero-sized structs differently from other structs.
5651 // However, N32/N64 ignores zero sized return values.
5652 if (!IsO32 && Size == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00005653 return ABIArgInfo::getIgnore();
5654
Akira Hatanaka8aeb1472012-05-11 21:01:17 +00005655 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005656 if (Size <= 128) {
5657 if (RetTy->isAnyComplexType())
5658 return ABIArgInfo::getDirect();
5659
Stephen Hines176edba2014-12-01 14:53:08 -08005660 // O32 returns integer vectors in registers and N32/N64 returns all small
5661 // aggregates in registers.
5662 if (!IsO32 ||
5663 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5664 ABIArgInfo ArgInfo =
5665 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5666 ArgInfo.setInReg(true);
5667 return ArgInfo;
5668 }
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005669 }
Akira Hatanaka619e8872011-06-02 00:09:17 +00005670
5671 return ABIArgInfo::getIndirect(0);
5672 }
5673
5674 // Treat an enum type as its underlying type.
5675 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5676 RetTy = EnumTy->getDecl()->getIntegerType();
5677
5678 return (RetTy->isPromotableIntegerType() ?
5679 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5680}
5681
5682void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakacc662542012-01-12 01:10:09 +00005683 ABIArgInfo &RetInfo = FI.getReturnInfo();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005684 if (!getCXXABI().classifyReturnType(FI))
5685 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanakacc662542012-01-12 01:10:09 +00005686
5687 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005688 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanakacc662542012-01-12 01:10:09 +00005689
Stephen Hines651f13c2014-04-23 16:59:28 -07005690 for (auto &I : FI.arguments())
5691 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanaka619e8872011-06-02 00:09:17 +00005692}
5693
5694llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5695 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00005696 llvm::Type *BP = CGF.Int8PtrTy;
5697 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Stephen Hines176edba2014-12-01 14:53:08 -08005698
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005699 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5700 // Pointers are also promoted in the same way but this only matters for N32.
Stephen Hines176edba2014-12-01 14:53:08 -08005701 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005702 unsigned PtrWidth = getTarget().getPointerWidth(0);
5703 if ((Ty->isIntegerType() &&
5704 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5705 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Stephen Hines176edba2014-12-01 14:53:08 -08005706 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5707 Ty->isSignedIntegerType());
5708 }
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005709
5710 CGBuilderTy &Builder = CGF.Builder;
5711 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5712 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Stephen Hines176edba2014-12-01 14:53:08 -08005713 int64_t TypeAlign =
5714 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005715 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5716 llvm::Value *AddrTyped;
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005717 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005718
5719 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005720 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5721 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5722 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5723 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005724 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5725 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5726 }
5727 else
5728 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5729
5730 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005731 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Stephen Hines176edba2014-12-01 14:53:08 -08005732 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5733 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005734 llvm::Value *NextAddr =
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005735 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005736 "ap.next");
5737 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5738
5739 return AddrTyped;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005740}
5741
John McCallaeeb7012010-05-27 06:19:26 +00005742bool
5743MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5744 llvm::Value *Address) const {
5745 // This information comes from gcc's implementation, which seems to
5746 // as canonical as it gets.
5747
John McCallaeeb7012010-05-27 06:19:26 +00005748 // Everything on MIPS is 4 bytes. Double-precision FP registers
5749 // are aliased to pairs of single-precision FP registers.
Chris Lattner8b418682012-02-07 00:39:47 +00005750 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCallaeeb7012010-05-27 06:19:26 +00005751
5752 // 0-31 are the general purpose registers, $0 - $31.
5753 // 32-63 are the floating-point registers, $f0 - $f31.
5754 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5755 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattner8b418682012-02-07 00:39:47 +00005756 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCallaeeb7012010-05-27 06:19:26 +00005757
5758 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5759 // They are one bit wide and ignored here.
5760
5761 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5762 // (coprocessor 1 is the FP unit)
5763 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5764 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5765 // 176-181 are the DSP accumulator registers.
Chris Lattner8b418682012-02-07 00:39:47 +00005766 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCallaeeb7012010-05-27 06:19:26 +00005767 return false;
5768}
5769
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005770//===----------------------------------------------------------------------===//
5771// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5772// Currently subclassed only to implement custom OpenCL C function attribute
5773// handling.
5774//===----------------------------------------------------------------------===//
5775
5776namespace {
5777
5778class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5779public:
5780 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5781 : DefaultTargetCodeGenInfo(CGT) {}
5782
Stephen Hines651f13c2014-04-23 16:59:28 -07005783 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5784 CodeGen::CodeGenModule &M) const override;
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005785};
5786
5787void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5788 llvm::GlobalValue *GV,
5789 CodeGen::CodeGenModule &M) const {
5790 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5791 if (!FD) return;
5792
5793 llvm::Function *F = cast<llvm::Function>(GV);
5794
David Blaikie4e4d0842012-03-11 07:00:24 +00005795 if (M.getLangOpts().OpenCL) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005796 if (FD->hasAttr<OpenCLKernelAttr>()) {
5797 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00005798 F->addFnAttr(llvm::Attribute::NoInline);
Stephen Hines651f13c2014-04-23 16:59:28 -07005799 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5800 if (Attr) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005801 // Convert the reqd_work_group_size() attributes to metadata.
5802 llvm::LLVMContext &Context = F->getContext();
5803 llvm::NamedMDNode *OpenCLMetadata =
5804 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5805
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005806 SmallVector<llvm::Metadata *, 5> Operands;
5807 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005808
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005809 Operands.push_back(
5810 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5811 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5812 Operands.push_back(
5813 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5814 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5815 Operands.push_back(
5816 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5817 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005818
5819 // Add a boolean constant operand for "required" (true) or "hint" (false)
5820 // for implementing the work_group_size_hint attr later. Currently
5821 // always true as the hint is not yet implemented.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005822 Operands.push_back(
5823 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005824 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5825 }
5826 }
5827 }
5828}
5829
5830}
John McCallaeeb7012010-05-27 06:19:26 +00005831
Tony Linthicum96319392011-12-12 21:14:55 +00005832//===----------------------------------------------------------------------===//
5833// Hexagon ABI Implementation
5834//===----------------------------------------------------------------------===//
5835
5836namespace {
5837
5838class HexagonABIInfo : public ABIInfo {
5839
5840
5841public:
5842 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5843
5844private:
5845
5846 ABIArgInfo classifyReturnType(QualType RetTy) const;
5847 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5848
Stephen Hines651f13c2014-04-23 16:59:28 -07005849 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum96319392011-12-12 21:14:55 +00005850
Stephen Hines651f13c2014-04-23 16:59:28 -07005851 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5852 CodeGenFunction &CGF) const override;
Tony Linthicum96319392011-12-12 21:14:55 +00005853};
5854
5855class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5856public:
5857 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5858 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5859
Stephen Hines651f13c2014-04-23 16:59:28 -07005860 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum96319392011-12-12 21:14:55 +00005861 return 29;
5862 }
5863};
5864
5865}
5866
5867void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005868 if (!getCXXABI().classifyReturnType(FI))
5869 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07005870 for (auto &I : FI.arguments())
5871 I.info = classifyArgumentType(I.type);
Tony Linthicum96319392011-12-12 21:14:55 +00005872}
5873
5874ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5875 if (!isAggregateTypeForABI(Ty)) {
5876 // Treat an enum type as its underlying type.
5877 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5878 Ty = EnumTy->getDecl()->getIntegerType();
5879
5880 return (Ty->isPromotableIntegerType() ?
5881 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5882 }
5883
5884 // Ignore empty records.
5885 if (isEmptyRecord(getContext(), Ty, true))
5886 return ABIArgInfo::getIgnore();
5887
Mark Lacey23630722013-10-06 01:33:34 +00005888 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005889 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum96319392011-12-12 21:14:55 +00005890
5891 uint64_t Size = getContext().getTypeSize(Ty);
5892 if (Size > 64)
5893 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5894 // Pass in the smallest viable integer type.
5895 else if (Size > 32)
5896 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5897 else if (Size > 16)
5898 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5899 else if (Size > 8)
5900 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5901 else
5902 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5903}
5904
5905ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5906 if (RetTy->isVoidType())
5907 return ABIArgInfo::getIgnore();
5908
5909 // Large vector types should be returned via memory.
5910 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5911 return ABIArgInfo::getIndirect(0);
5912
5913 if (!isAggregateTypeForABI(RetTy)) {
5914 // Treat an enum type as its underlying type.
5915 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5916 RetTy = EnumTy->getDecl()->getIntegerType();
5917
5918 return (RetTy->isPromotableIntegerType() ?
5919 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5920 }
5921
Tony Linthicum96319392011-12-12 21:14:55 +00005922 if (isEmptyRecord(getContext(), RetTy, true))
5923 return ABIArgInfo::getIgnore();
5924
5925 // Aggregates <= 8 bytes are returned in r0; other aggregates
5926 // are returned indirectly.
5927 uint64_t Size = getContext().getTypeSize(RetTy);
5928 if (Size <= 64) {
5929 // Return in the smallest viable integer type.
5930 if (Size <= 8)
5931 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5932 if (Size <= 16)
5933 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5934 if (Size <= 32)
5935 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5936 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5937 }
5938
5939 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5940}
5941
5942llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner8b418682012-02-07 00:39:47 +00005943 CodeGenFunction &CGF) const {
Tony Linthicum96319392011-12-12 21:14:55 +00005944 // FIXME: Need to handle alignment
Chris Lattner8b418682012-02-07 00:39:47 +00005945 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum96319392011-12-12 21:14:55 +00005946
5947 CGBuilderTy &Builder = CGF.Builder;
5948 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5949 "ap");
5950 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5951 llvm::Type *PTy =
5952 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5953 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5954
5955 uint64_t Offset =
5956 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5957 llvm::Value *NextAddr =
5958 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5959 "ap.next");
5960 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5961
5962 return AddrTyped;
5963}
5964
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005965//===----------------------------------------------------------------------===//
5966// AMDGPU ABI Implementation
5967//===----------------------------------------------------------------------===//
5968
5969namespace {
5970
5971class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
5972public:
5973 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
5974 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
5975 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5976 CodeGen::CodeGenModule &M) const override;
5977};
5978
5979}
5980
5981void AMDGPUTargetCodeGenInfo::SetTargetAttributes(
5982 const Decl *D,
5983 llvm::GlobalValue *GV,
5984 CodeGen::CodeGenModule &M) const {
5985 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5986 if (!FD)
5987 return;
5988
5989 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
5990 llvm::Function *F = cast<llvm::Function>(GV);
5991 uint32_t NumVGPR = Attr->getNumVGPR();
5992 if (NumVGPR != 0)
5993 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
5994 }
5995
5996 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
5997 llvm::Function *F = cast<llvm::Function>(GV);
5998 unsigned NumSGPR = Attr->getNumSGPR();
5999 if (NumSGPR != 0)
6000 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6001 }
6002}
6003
Tony Linthicum96319392011-12-12 21:14:55 +00006004
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006005//===----------------------------------------------------------------------===//
6006// SPARC v9 ABI Implementation.
6007// Based on the SPARC Compliance Definition version 2.4.1.
6008//
6009// Function arguments a mapped to a nominal "parameter array" and promoted to
6010// registers depending on their type. Each argument occupies 8 or 16 bytes in
6011// the array, structs larger than 16 bytes are passed indirectly.
6012//
6013// One case requires special care:
6014//
6015// struct mixed {
6016// int i;
6017// float f;
6018// };
6019//
6020// When a struct mixed is passed by value, it only occupies 8 bytes in the
6021// parameter array, but the int is passed in an integer register, and the float
6022// is passed in a floating point register. This is represented as two arguments
6023// with the LLVM IR inreg attribute:
6024//
6025// declare void f(i32 inreg %i, float inreg %f)
6026//
6027// The code generator will only allocate 4 bytes from the parameter array for
6028// the inreg arguments. All other arguments are allocated a multiple of 8
6029// bytes.
6030//
6031namespace {
6032class SparcV9ABIInfo : public ABIInfo {
6033public:
6034 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6035
6036private:
6037 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Stephen Hines651f13c2014-04-23 16:59:28 -07006038 void computeInfo(CGFunctionInfo &FI) const override;
6039 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6040 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00006041
6042 // Coercion type builder for structs passed in registers. The coercion type
6043 // serves two purposes:
6044 //
6045 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6046 // in registers.
6047 // 2. Expose aligned floating point elements as first-level elements, so the
6048 // code generator knows to pass them in floating point registers.
6049 //
6050 // We also compute the InReg flag which indicates that the struct contains
6051 // aligned 32-bit floats.
6052 //
6053 struct CoerceBuilder {
6054 llvm::LLVMContext &Context;
6055 const llvm::DataLayout &DL;
6056 SmallVector<llvm::Type*, 8> Elems;
6057 uint64_t Size;
6058 bool InReg;
6059
6060 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6061 : Context(c), DL(dl), Size(0), InReg(false) {}
6062
6063 // Pad Elems with integers until Size is ToSize.
6064 void pad(uint64_t ToSize) {
6065 assert(ToSize >= Size && "Cannot remove elements");
6066 if (ToSize == Size)
6067 return;
6068
6069 // Finish the current 64-bit word.
6070 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6071 if (Aligned > Size && Aligned <= ToSize) {
6072 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6073 Size = Aligned;
6074 }
6075
6076 // Add whole 64-bit words.
6077 while (Size + 64 <= ToSize) {
6078 Elems.push_back(llvm::Type::getInt64Ty(Context));
6079 Size += 64;
6080 }
6081
6082 // Final in-word padding.
6083 if (Size < ToSize) {
6084 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6085 Size = ToSize;
6086 }
6087 }
6088
6089 // Add a floating point element at Offset.
6090 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6091 // Unaligned floats are treated as integers.
6092 if (Offset % Bits)
6093 return;
6094 // The InReg flag is only required if there are any floats < 64 bits.
6095 if (Bits < 64)
6096 InReg = true;
6097 pad(Offset);
6098 Elems.push_back(Ty);
6099 Size = Offset + Bits;
6100 }
6101
6102 // Add a struct type to the coercion type, starting at Offset (in bits).
6103 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6104 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6105 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6106 llvm::Type *ElemTy = StrTy->getElementType(i);
6107 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6108 switch (ElemTy->getTypeID()) {
6109 case llvm::Type::StructTyID:
6110 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6111 break;
6112 case llvm::Type::FloatTyID:
6113 addFloat(ElemOffset, ElemTy, 32);
6114 break;
6115 case llvm::Type::DoubleTyID:
6116 addFloat(ElemOffset, ElemTy, 64);
6117 break;
6118 case llvm::Type::FP128TyID:
6119 addFloat(ElemOffset, ElemTy, 128);
6120 break;
6121 case llvm::Type::PointerTyID:
6122 if (ElemOffset % 64 == 0) {
6123 pad(ElemOffset);
6124 Elems.push_back(ElemTy);
6125 Size += 64;
6126 }
6127 break;
6128 default:
6129 break;
6130 }
6131 }
6132 }
6133
6134 // Check if Ty is a usable substitute for the coercion type.
6135 bool isUsableType(llvm::StructType *Ty) const {
6136 if (Ty->getNumElements() != Elems.size())
6137 return false;
6138 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6139 if (Elems[i] != Ty->getElementType(i))
6140 return false;
6141 return true;
6142 }
6143
6144 // Get the coercion type as a literal struct type.
6145 llvm::Type *getType() const {
6146 if (Elems.size() == 1)
6147 return Elems.front();
6148 else
6149 return llvm::StructType::get(Context, Elems);
6150 }
6151 };
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006152};
6153} // end anonymous namespace
6154
6155ABIArgInfo
6156SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6157 if (Ty->isVoidType())
6158 return ABIArgInfo::getIgnore();
6159
6160 uint64_t Size = getContext().getTypeSize(Ty);
6161
6162 // Anything too big to fit in registers is passed with an explicit indirect
6163 // pointer / sret pointer.
6164 if (Size > SizeLimit)
6165 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6166
6167 // Treat an enum type as its underlying type.
6168 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6169 Ty = EnumTy->getDecl()->getIntegerType();
6170
6171 // Integer types smaller than a register are extended.
6172 if (Size < 64 && Ty->isIntegerType())
6173 return ABIArgInfo::getExtend();
6174
6175 // Other non-aggregates go in registers.
6176 if (!isAggregateTypeForABI(Ty))
6177 return ABIArgInfo::getDirect();
6178
Stephen Hines651f13c2014-04-23 16:59:28 -07006179 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6180 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6181 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6182 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6183
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006184 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00006185 // Build a coercion type from the LLVM struct type.
6186 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6187 if (!StrTy)
6188 return ABIArgInfo::getDirect();
6189
6190 CoerceBuilder CB(getVMContext(), getDataLayout());
6191 CB.addStruct(0, StrTy);
6192 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6193
6194 // Try to use the original type for coercion.
6195 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6196
6197 if (CB.InReg)
6198 return ABIArgInfo::getDirectInReg(CoerceTy);
6199 else
6200 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006201}
6202
6203llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6204 CodeGenFunction &CGF) const {
Jakob Stoklund Olesena4b56d32013-06-05 03:00:18 +00006205 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6206 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6207 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6208 AI.setCoerceToType(ArgTy);
6209
6210 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6211 CGBuilderTy &Builder = CGF.Builder;
6212 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6213 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6214 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6215 llvm::Value *ArgAddr;
6216 unsigned Stride;
6217
6218 switch (AI.getKind()) {
6219 case ABIArgInfo::Expand:
Stephen Hines651f13c2014-04-23 16:59:28 -07006220 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesena4b56d32013-06-05 03:00:18 +00006221 llvm_unreachable("Unsupported ABI kind for va_arg");
6222
6223 case ABIArgInfo::Extend:
6224 Stride = 8;
6225 ArgAddr = Builder
6226 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6227 "extend");
6228 break;
6229
6230 case ABIArgInfo::Direct:
6231 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6232 ArgAddr = Addr;
6233 break;
6234
6235 case ABIArgInfo::Indirect:
6236 Stride = 8;
6237 ArgAddr = Builder.CreateBitCast(Addr,
6238 llvm::PointerType::getUnqual(ArgPtrTy),
6239 "indirect");
6240 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6241 break;
6242
6243 case ABIArgInfo::Ignore:
6244 return llvm::UndefValue::get(ArgPtrTy);
6245 }
6246
6247 // Update VAList.
6248 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6249 Builder.CreateStore(Addr, VAListAddrAsBPP);
6250
6251 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006252}
6253
6254void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6255 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Stephen Hines651f13c2014-04-23 16:59:28 -07006256 for (auto &I : FI.arguments())
6257 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006258}
6259
6260namespace {
6261class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6262public:
6263 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6264 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07006265
6266 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6267 return 14;
6268 }
6269
6270 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6271 llvm::Value *Address) const override;
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006272};
6273} // end anonymous namespace
6274
Stephen Hines651f13c2014-04-23 16:59:28 -07006275bool
6276SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6277 llvm::Value *Address) const {
6278 // This is calculated from the LLVM and GCC tables and verified
6279 // against gcc output. AFAIK all ABIs use the same encoding.
6280
6281 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6282
6283 llvm::IntegerType *i8 = CGF.Int8Ty;
6284 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6285 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6286
6287 // 0-31: the 8-byte general-purpose registers
6288 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6289
6290 // 32-63: f0-31, the 4-byte floating-point registers
6291 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6292
6293 // Y = 64
6294 // PSR = 65
6295 // WIM = 66
6296 // TBR = 67
6297 // PC = 68
6298 // NPC = 69
6299 // FSR = 70
6300 // CSR = 71
6301 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6302
6303 // 72-87: d0-15, the 8-byte floating-point registers
6304 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6305
6306 return false;
6307}
6308
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006309
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006310//===----------------------------------------------------------------------===//
Stephen Hines651f13c2014-04-23 16:59:28 -07006311// XCore ABI Implementation
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006312//===----------------------------------------------------------------------===//
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006313
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006314namespace {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006315
6316/// A SmallStringEnc instance is used to build up the TypeString by passing
6317/// it by reference between functions that append to it.
6318typedef llvm::SmallString<128> SmallStringEnc;
6319
6320/// TypeStringCache caches the meta encodings of Types.
6321///
6322/// The reason for caching TypeStrings is two fold:
6323/// 1. To cache a type's encoding for later uses;
6324/// 2. As a means to break recursive member type inclusion.
6325///
6326/// A cache Entry can have a Status of:
6327/// NonRecursive: The type encoding is not recursive;
6328/// Recursive: The type encoding is recursive;
6329/// Incomplete: An incomplete TypeString;
6330/// IncompleteUsed: An incomplete TypeString that has been used in a
6331/// Recursive type encoding.
6332///
6333/// A NonRecursive entry will have all of its sub-members expanded as fully
6334/// as possible. Whilst it may contain types which are recursive, the type
6335/// itself is not recursive and thus its encoding may be safely used whenever
6336/// the type is encountered.
6337///
6338/// A Recursive entry will have all of its sub-members expanded as fully as
6339/// possible. The type itself is recursive and it may contain other types which
6340/// are recursive. The Recursive encoding must not be used during the expansion
6341/// of a recursive type's recursive branch. For simplicity the code uses
6342/// IncompleteCount to reject all usage of Recursive encodings for member types.
6343///
6344/// An Incomplete entry is always a RecordType and only encodes its
6345/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6346/// are placed into the cache during type expansion as a means to identify and
6347/// handle recursive inclusion of types as sub-members. If there is recursion
6348/// the entry becomes IncompleteUsed.
6349///
6350/// During the expansion of a RecordType's members:
6351///
6352/// If the cache contains a NonRecursive encoding for the member type, the
6353/// cached encoding is used;
6354///
6355/// If the cache contains a Recursive encoding for the member type, the
6356/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6357///
6358/// If the member is a RecordType, an Incomplete encoding is placed into the
6359/// cache to break potential recursive inclusion of itself as a sub-member;
6360///
6361/// Once a member RecordType has been expanded, its temporary incomplete
6362/// entry is removed from the cache. If a Recursive encoding was swapped out
6363/// it is swapped back in;
6364///
6365/// If an incomplete entry is used to expand a sub-member, the incomplete
6366/// entry is marked as IncompleteUsed. The cache keeps count of how many
6367/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6368///
6369/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6370/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6371/// Else the member is part of a recursive type and thus the recursion has
6372/// been exited too soon for the encoding to be correct for the member.
6373///
6374class TypeStringCache {
6375 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6376 struct Entry {
6377 std::string Str; // The encoded TypeString for the type.
6378 enum Status State; // Information about the encoding in 'Str'.
6379 std::string Swapped; // A temporary place holder for a Recursive encoding
6380 // during the expansion of RecordType's members.
6381 };
6382 std::map<const IdentifierInfo *, struct Entry> Map;
6383 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6384 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6385public:
6386 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
6387 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6388 bool removeIncomplete(const IdentifierInfo *ID);
6389 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6390 bool IsRecursive);
6391 StringRef lookupStr(const IdentifierInfo *ID);
6392};
6393
6394/// TypeString encodings for enum & union fields must be order.
6395/// FieldEncoding is a helper for this ordering process.
6396class FieldEncoding {
6397 bool HasName;
6398 std::string Enc;
6399public:
6400 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6401 StringRef str() {return Enc.c_str();};
6402 bool operator<(const FieldEncoding &rhs) const {
6403 if (HasName != rhs.HasName) return HasName;
6404 return Enc < rhs.Enc;
6405 }
6406};
6407
Robert Lytton276c2892013-08-19 09:46:39 +00006408class XCoreABIInfo : public DefaultABIInfo {
6409public:
6410 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07006411 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6412 CodeGenFunction &CGF) const override;
Robert Lytton276c2892013-08-19 09:46:39 +00006413};
6414
Stephen Hines651f13c2014-04-23 16:59:28 -07006415class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006416 mutable TypeStringCache TSC;
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006417public:
Stephen Hines651f13c2014-04-23 16:59:28 -07006418 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton276c2892013-08-19 09:46:39 +00006419 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006420 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6421 CodeGen::CodeGenModule &M) const override;
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006422};
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006423
Robert Lytton645e6fd2013-10-11 10:29:34 +00006424} // End anonymous namespace.
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006425
Robert Lytton276c2892013-08-19 09:46:39 +00006426llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6427 CodeGenFunction &CGF) const {
Robert Lytton276c2892013-08-19 09:46:39 +00006428 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton276c2892013-08-19 09:46:39 +00006429
Robert Lytton645e6fd2013-10-11 10:29:34 +00006430 // Get the VAList.
Robert Lytton276c2892013-08-19 09:46:39 +00006431 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6432 CGF.Int8PtrPtrTy);
6433 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton276c2892013-08-19 09:46:39 +00006434
Robert Lytton645e6fd2013-10-11 10:29:34 +00006435 // Handle the argument.
6436 ABIArgInfo AI = classifyArgumentType(Ty);
6437 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6438 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6439 AI.setCoerceToType(ArgTy);
Robert Lytton276c2892013-08-19 09:46:39 +00006440 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton645e6fd2013-10-11 10:29:34 +00006441 llvm::Value *Val;
Andy Gibbsed9967e2013-10-14 07:02:04 +00006442 uint64_t ArgSize = 0;
Robert Lytton276c2892013-08-19 09:46:39 +00006443 switch (AI.getKind()) {
Robert Lytton276c2892013-08-19 09:46:39 +00006444 case ABIArgInfo::Expand:
Stephen Hines651f13c2014-04-23 16:59:28 -07006445 case ABIArgInfo::InAlloca:
Robert Lytton276c2892013-08-19 09:46:39 +00006446 llvm_unreachable("Unsupported ABI kind for va_arg");
6447 case ABIArgInfo::Ignore:
Robert Lytton645e6fd2013-10-11 10:29:34 +00006448 Val = llvm::UndefValue::get(ArgPtrTy);
6449 ArgSize = 0;
6450 break;
Robert Lytton276c2892013-08-19 09:46:39 +00006451 case ABIArgInfo::Extend:
6452 case ABIArgInfo::Direct:
Robert Lytton645e6fd2013-10-11 10:29:34 +00006453 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6454 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6455 if (ArgSize < 4)
6456 ArgSize = 4;
6457 break;
Robert Lytton276c2892013-08-19 09:46:39 +00006458 case ABIArgInfo::Indirect:
6459 llvm::Value *ArgAddr;
6460 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6461 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton645e6fd2013-10-11 10:29:34 +00006462 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6463 ArgSize = 4;
6464 break;
Robert Lytton276c2892013-08-19 09:46:39 +00006465 }
Robert Lytton645e6fd2013-10-11 10:29:34 +00006466
6467 // Increment the VAList.
6468 if (ArgSize) {
6469 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6470 Builder.CreateStore(APN, VAListAddrAsBPP);
6471 }
6472 return Val;
Robert Lytton276c2892013-08-19 09:46:39 +00006473}
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006474
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006475/// During the expansion of a RecordType, an incomplete TypeString is placed
6476/// into the cache as a means to identify and break recursion.
6477/// If there is a Recursive encoding in the cache, it is swapped out and will
6478/// be reinserted by removeIncomplete().
6479/// All other types of encoding should have been used rather than arriving here.
6480void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6481 std::string StubEnc) {
6482 if (!ID)
6483 return;
6484 Entry &E = Map[ID];
6485 assert( (E.Str.empty() || E.State == Recursive) &&
6486 "Incorrectly use of addIncomplete");
6487 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6488 E.Swapped.swap(E.Str); // swap out the Recursive
6489 E.Str.swap(StubEnc);
6490 E.State = Incomplete;
6491 ++IncompleteCount;
6492}
6493
6494/// Once the RecordType has been expanded, the temporary incomplete TypeString
6495/// must be removed from the cache.
6496/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6497/// Returns true if the RecordType was defined recursively.
6498bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6499 if (!ID)
6500 return false;
6501 auto I = Map.find(ID);
6502 assert(I != Map.end() && "Entry not present");
6503 Entry &E = I->second;
6504 assert( (E.State == Incomplete ||
6505 E.State == IncompleteUsed) &&
6506 "Entry must be an incomplete type");
6507 bool IsRecursive = false;
6508 if (E.State == IncompleteUsed) {
6509 // We made use of our Incomplete encoding, thus we are recursive.
6510 IsRecursive = true;
6511 --IncompleteUsedCount;
6512 }
6513 if (E.Swapped.empty())
6514 Map.erase(I);
6515 else {
6516 // Swap the Recursive back.
6517 E.Swapped.swap(E.Str);
6518 E.Swapped.clear();
6519 E.State = Recursive;
6520 }
6521 --IncompleteCount;
6522 return IsRecursive;
6523}
6524
6525/// Add the encoded TypeString to the cache only if it is NonRecursive or
6526/// Recursive (viz: all sub-members were expanded as fully as possible).
6527void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6528 bool IsRecursive) {
6529 if (!ID || IncompleteUsedCount)
6530 return; // No key or it is is an incomplete sub-type so don't add.
6531 Entry &E = Map[ID];
6532 if (IsRecursive && !E.Str.empty()) {
6533 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6534 "This is not the same Recursive entry");
6535 // The parent container was not recursive after all, so we could have used
6536 // this Recursive sub-member entry after all, but we assumed the worse when
6537 // we started viz: IncompleteCount!=0.
6538 return;
6539 }
6540 assert(E.Str.empty() && "Entry already present");
6541 E.Str = Str.str();
6542 E.State = IsRecursive? Recursive : NonRecursive;
6543}
6544
6545/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6546/// are recursively expanding a type (IncompleteCount != 0) and the cached
6547/// encoding is Recursive, return an empty StringRef.
6548StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6549 if (!ID)
6550 return StringRef(); // We have no key.
6551 auto I = Map.find(ID);
6552 if (I == Map.end())
6553 return StringRef(); // We have no encoding.
6554 Entry &E = I->second;
6555 if (E.State == Recursive && IncompleteCount)
6556 return StringRef(); // We don't use Recursive encodings for member types.
6557
6558 if (E.State == Incomplete) {
6559 // The incomplete type is being used to break out of recursion.
6560 E.State = IncompleteUsed;
6561 ++IncompleteUsedCount;
6562 }
6563 return E.Str.c_str();
6564}
6565
6566/// The XCore ABI includes a type information section that communicates symbol
6567/// type information to the linker. The linker uses this information to verify
6568/// safety/correctness of things such as array bound and pointers et al.
6569/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6570/// This type information (TypeString) is emitted into meta data for all global
6571/// symbols: definitions, declarations, functions & variables.
6572///
6573/// The TypeString carries type, qualifier, name, size & value details.
6574/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6575/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6576/// The output is tested by test/CodeGen/xcore-stringtype.c.
6577///
6578static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6579 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6580
6581/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6582void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6583 CodeGen::CodeGenModule &CGM) const {
6584 SmallStringEnc Enc;
6585 if (getTypeString(Enc, D, CGM, TSC)) {
6586 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006587 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6588 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006589 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6590 llvm::NamedMDNode *MD =
6591 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6592 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6593 }
6594}
6595
6596static bool appendType(SmallStringEnc &Enc, QualType QType,
6597 const CodeGen::CodeGenModule &CGM,
6598 TypeStringCache &TSC);
6599
6600/// Helper function for appendRecordType().
6601/// Builds a SmallVector containing the encoded field types in declaration order.
6602static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6603 const RecordDecl *RD,
6604 const CodeGen::CodeGenModule &CGM,
6605 TypeStringCache &TSC) {
Stephen Hines176edba2014-12-01 14:53:08 -08006606 for (const auto *Field : RD->fields()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006607 SmallStringEnc Enc;
6608 Enc += "m(";
Stephen Hines176edba2014-12-01 14:53:08 -08006609 Enc += Field->getName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006610 Enc += "){";
Stephen Hines176edba2014-12-01 14:53:08 -08006611 if (Field->isBitField()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006612 Enc += "b(";
6613 llvm::raw_svector_ostream OS(Enc);
6614 OS.resync();
Stephen Hines176edba2014-12-01 14:53:08 -08006615 OS << Field->getBitWidthValue(CGM.getContext());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006616 OS.flush();
6617 Enc += ':';
6618 }
Stephen Hines176edba2014-12-01 14:53:08 -08006619 if (!appendType(Enc, Field->getType(), CGM, TSC))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006620 return false;
Stephen Hines176edba2014-12-01 14:53:08 -08006621 if (Field->isBitField())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006622 Enc += ')';
6623 Enc += '}';
Stephen Hines176edba2014-12-01 14:53:08 -08006624 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006625 }
6626 return true;
6627}
6628
6629/// Appends structure and union types to Enc and adds encoding to cache.
6630/// Recursively calls appendType (via extractFieldType) for each field.
6631/// Union types have their fields ordered according to the ABI.
6632static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6633 const CodeGen::CodeGenModule &CGM,
6634 TypeStringCache &TSC, const IdentifierInfo *ID) {
6635 // Append the cached TypeString if we have one.
6636 StringRef TypeString = TSC.lookupStr(ID);
6637 if (!TypeString.empty()) {
6638 Enc += TypeString;
6639 return true;
6640 }
6641
6642 // Start to emit an incomplete TypeString.
6643 size_t Start = Enc.size();
6644 Enc += (RT->isUnionType()? 'u' : 's');
6645 Enc += '(';
6646 if (ID)
6647 Enc += ID->getName();
6648 Enc += "){";
6649
6650 // We collect all encoded fields and order as necessary.
6651 bool IsRecursive = false;
6652 const RecordDecl *RD = RT->getDecl()->getDefinition();
6653 if (RD && !RD->field_empty()) {
6654 // An incomplete TypeString stub is placed in the cache for this RecordType
6655 // so that recursive calls to this RecordType will use it whilst building a
6656 // complete TypeString for this RecordType.
6657 SmallVector<FieldEncoding, 16> FE;
6658 std::string StubEnc(Enc.substr(Start).str());
6659 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6660 TSC.addIncomplete(ID, std::move(StubEnc));
6661 if (!extractFieldType(FE, RD, CGM, TSC)) {
6662 (void) TSC.removeIncomplete(ID);
6663 return false;
6664 }
6665 IsRecursive = TSC.removeIncomplete(ID);
6666 // The ABI requires unions to be sorted but not structures.
6667 // See FieldEncoding::operator< for sort algorithm.
6668 if (RT->isUnionType())
6669 std::sort(FE.begin(), FE.end());
6670 // We can now complete the TypeString.
6671 unsigned E = FE.size();
6672 for (unsigned I = 0; I != E; ++I) {
6673 if (I)
6674 Enc += ',';
6675 Enc += FE[I].str();
6676 }
6677 }
6678 Enc += '}';
6679 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6680 return true;
6681}
6682
6683/// Appends enum types to Enc and adds the encoding to the cache.
6684static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6685 TypeStringCache &TSC,
6686 const IdentifierInfo *ID) {
6687 // Append the cached TypeString if we have one.
6688 StringRef TypeString = TSC.lookupStr(ID);
6689 if (!TypeString.empty()) {
6690 Enc += TypeString;
6691 return true;
6692 }
6693
6694 size_t Start = Enc.size();
6695 Enc += "e(";
6696 if (ID)
6697 Enc += ID->getName();
6698 Enc += "){";
6699
6700 // We collect all encoded enumerations and order them alphanumerically.
6701 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
6702 SmallVector<FieldEncoding, 16> FE;
6703 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6704 ++I) {
6705 SmallStringEnc EnumEnc;
6706 EnumEnc += "m(";
6707 EnumEnc += I->getName();
6708 EnumEnc += "){";
6709 I->getInitVal().toString(EnumEnc);
6710 EnumEnc += '}';
6711 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6712 }
6713 std::sort(FE.begin(), FE.end());
6714 unsigned E = FE.size();
6715 for (unsigned I = 0; I != E; ++I) {
6716 if (I)
6717 Enc += ',';
6718 Enc += FE[I].str();
6719 }
6720 }
6721 Enc += '}';
6722 TSC.addIfComplete(ID, Enc.substr(Start), false);
6723 return true;
6724}
6725
6726/// Appends type's qualifier to Enc.
6727/// This is done prior to appending the type's encoding.
6728static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6729 // Qualifiers are emitted in alphabetical order.
6730 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6731 int Lookup = 0;
6732 if (QT.isConstQualified())
6733 Lookup += 1<<0;
6734 if (QT.isRestrictQualified())
6735 Lookup += 1<<1;
6736 if (QT.isVolatileQualified())
6737 Lookup += 1<<2;
6738 Enc += Table[Lookup];
6739}
6740
6741/// Appends built-in types to Enc.
6742static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6743 const char *EncType;
6744 switch (BT->getKind()) {
6745 case BuiltinType::Void:
6746 EncType = "0";
6747 break;
6748 case BuiltinType::Bool:
6749 EncType = "b";
6750 break;
6751 case BuiltinType::Char_U:
6752 EncType = "uc";
6753 break;
6754 case BuiltinType::UChar:
6755 EncType = "uc";
6756 break;
6757 case BuiltinType::SChar:
6758 EncType = "sc";
6759 break;
6760 case BuiltinType::UShort:
6761 EncType = "us";
6762 break;
6763 case BuiltinType::Short:
6764 EncType = "ss";
6765 break;
6766 case BuiltinType::UInt:
6767 EncType = "ui";
6768 break;
6769 case BuiltinType::Int:
6770 EncType = "si";
6771 break;
6772 case BuiltinType::ULong:
6773 EncType = "ul";
6774 break;
6775 case BuiltinType::Long:
6776 EncType = "sl";
6777 break;
6778 case BuiltinType::ULongLong:
6779 EncType = "ull";
6780 break;
6781 case BuiltinType::LongLong:
6782 EncType = "sll";
6783 break;
6784 case BuiltinType::Float:
6785 EncType = "ft";
6786 break;
6787 case BuiltinType::Double:
6788 EncType = "d";
6789 break;
6790 case BuiltinType::LongDouble:
6791 EncType = "ld";
6792 break;
6793 default:
6794 return false;
6795 }
6796 Enc += EncType;
6797 return true;
6798}
6799
6800/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6801static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6802 const CodeGen::CodeGenModule &CGM,
6803 TypeStringCache &TSC) {
6804 Enc += "p(";
6805 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6806 return false;
6807 Enc += ')';
6808 return true;
6809}
6810
6811/// Appends array encoding to Enc before calling appendType for the element.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006812static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6813 const ArrayType *AT,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006814 const CodeGen::CodeGenModule &CGM,
6815 TypeStringCache &TSC, StringRef NoSizeEnc) {
6816 if (AT->getSizeModifier() != ArrayType::Normal)
6817 return false;
6818 Enc += "a(";
6819 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6820 CAT->getSize().toStringUnsigned(Enc);
6821 else
6822 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6823 Enc += ':';
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006824 // The Qualifiers should be attached to the type rather than the array.
6825 appendQualifier(Enc, QT);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006826 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6827 return false;
6828 Enc += ')';
6829 return true;
6830}
6831
6832/// Appends a function encoding to Enc, calling appendType for the return type
6833/// and the arguments.
6834static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6835 const CodeGen::CodeGenModule &CGM,
6836 TypeStringCache &TSC) {
6837 Enc += "f{";
6838 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6839 return false;
6840 Enc += "}(";
6841 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6842 // N.B. we are only interested in the adjusted param types.
6843 auto I = FPT->param_type_begin();
6844 auto E = FPT->param_type_end();
6845 if (I != E) {
6846 do {
6847 if (!appendType(Enc, *I, CGM, TSC))
6848 return false;
6849 ++I;
6850 if (I != E)
6851 Enc += ',';
6852 } while (I != E);
6853 if (FPT->isVariadic())
6854 Enc += ",va";
6855 } else {
6856 if (FPT->isVariadic())
6857 Enc += "va";
6858 else
6859 Enc += '0';
6860 }
6861 }
6862 Enc += ')';
6863 return true;
6864}
6865
6866/// Handles the type's qualifier before dispatching a call to handle specific
6867/// type encodings.
6868static bool appendType(SmallStringEnc &Enc, QualType QType,
6869 const CodeGen::CodeGenModule &CGM,
6870 TypeStringCache &TSC) {
6871
6872 QualType QT = QType.getCanonicalType();
6873
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006874 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6875 // The Qualifiers should be attached to the type rather than the array.
6876 // Thus we don't call appendQualifier() here.
6877 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6878
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006879 appendQualifier(Enc, QT);
6880
6881 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6882 return appendBuiltinType(Enc, BT);
6883
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006884 if (const PointerType *PT = QT->getAs<PointerType>())
6885 return appendPointerType(Enc, PT, CGM, TSC);
6886
6887 if (const EnumType *ET = QT->getAs<EnumType>())
6888 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6889
6890 if (const RecordType *RT = QT->getAsStructureType())
6891 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6892
6893 if (const RecordType *RT = QT->getAsUnionType())
6894 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6895
6896 if (const FunctionType *FT = QT->getAs<FunctionType>())
6897 return appendFunctionType(Enc, FT, CGM, TSC);
6898
6899 return false;
6900}
6901
6902static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6903 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6904 if (!D)
6905 return false;
6906
6907 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6908 if (FD->getLanguageLinkage() != CLanguageLinkage)
6909 return false;
6910 return appendType(Enc, FD->getType(), CGM, TSC);
6911 }
6912
6913 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6914 if (VD->getLanguageLinkage() != CLanguageLinkage)
6915 return false;
6916 QualType QT = VD->getType().getCanonicalType();
6917 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6918 // Global ArrayTypes are given a size of '*' if the size is unknown.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006919 // The Qualifiers should be attached to the type rather than the array.
6920 // Thus we don't call appendQualifier() here.
6921 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006922 }
6923 return appendType(Enc, QT, CGM, TSC);
6924 }
6925 return false;
6926}
6927
6928
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006929//===----------------------------------------------------------------------===//
6930// Driver code
6931//===----------------------------------------------------------------------===//
6932
Stephen Hines176edba2014-12-01 14:53:08 -08006933const llvm::Triple &CodeGenModule::getTriple() const {
6934 return getTarget().getTriple();
6935}
6936
6937bool CodeGenModule::supportsCOMDAT() const {
6938 return !getTriple().isOSBinFormatMachO();
6939}
6940
Chris Lattnerea044322010-07-29 02:01:43 +00006941const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00006942 if (TheTargetCodeGenInfo)
6943 return *TheTargetCodeGenInfo;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00006944
John McCall64aa4b32013-04-16 22:48:15 +00006945 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar1752ee42009-08-24 09:10:05 +00006946 switch (Triple.getArch()) {
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00006947 default:
Chris Lattnerea044322010-07-29 02:01:43 +00006948 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00006949
Derek Schuff9ed63f82012-09-06 17:37:28 +00006950 case llvm::Triple::le32:
6951 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCallaeeb7012010-05-27 06:19:26 +00006952 case llvm::Triple::mips:
6953 case llvm::Triple::mipsel:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00006954 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
John McCallaeeb7012010-05-27 06:19:26 +00006955
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00006956 case llvm::Triple::mips64:
6957 case llvm::Triple::mips64el:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00006958 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00006959
Tim Northoverc264e162013-01-31 12:13:10 +00006960 case llvm::Triple::aarch64:
Stephen Hines176edba2014-12-01 14:53:08 -08006961 case llvm::Triple::aarch64_be: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006962 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006963 if (getTarget().getABI() == "darwinpcs")
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006964 Kind = AArch64ABIInfo::DarwinPCS;
6965
6966 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
6967 }
Tim Northoverc264e162013-01-31 12:13:10 +00006968
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00006969 case llvm::Triple::arm:
Stephen Hines651f13c2014-04-23 16:59:28 -07006970 case llvm::Triple::armeb:
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00006971 case llvm::Triple::thumb:
Stephen Hines651f13c2014-04-23 16:59:28 -07006972 case llvm::Triple::thumbeb:
Sandeep Patel34c1af82011-04-05 00:23:47 +00006973 {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006974 if (Triple.getOS() == llvm::Triple::Win32) {
6975 TheTargetCodeGenInfo =
6976 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
6977 return *TheTargetCodeGenInfo;
6978 }
6979
Sandeep Patel34c1af82011-04-05 00:23:47 +00006980 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006981 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel34c1af82011-04-05 00:23:47 +00006982 Kind = ARMABIInfo::APCS;
David Tweedb16abb12012-10-25 13:33:01 +00006983 else if (CodeGenOpts.FloatABI == "hard" ||
John McCall64aa4b32013-04-16 22:48:15 +00006984 (CodeGenOpts.FloatABI != "soft" &&
6985 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel34c1af82011-04-05 00:23:47 +00006986 Kind = ARMABIInfo::AAPCS_VFP;
6987
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006988 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel34c1af82011-04-05 00:23:47 +00006989 }
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00006990
John McCallec853ba2010-03-11 00:10:12 +00006991 case llvm::Triple::ppc:
Chris Lattnerea044322010-07-29 02:01:43 +00006992 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divacky0fbc4b92012-05-09 18:22:46 +00006993 case llvm::Triple::ppc64:
Stephen Hines176edba2014-12-01 14:53:08 -08006994 if (Triple.isOSBinFormatELF()) {
6995 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
6996 if (getTarget().getABI() == "elfv2")
6997 Kind = PPC64_SVR4_ABIInfo::ELFv2;
6998
6999 return *(TheTargetCodeGenInfo =
7000 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7001 } else
Bill Schmidt2fc107f2012-10-03 19:18:57 +00007002 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Stephen Hines176edba2014-12-01 14:53:08 -08007003 case llvm::Triple::ppc64le: {
Bill Schmidtea7fb0c2013-07-26 01:36:11 +00007004 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Stephen Hines176edba2014-12-01 14:53:08 -08007005 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
7006 if (getTarget().getABI() == "elfv1")
7007 Kind = PPC64_SVR4_ABIInfo::ELFv1;
7008
7009 return *(TheTargetCodeGenInfo =
7010 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7011 }
John McCallec853ba2010-03-11 00:10:12 +00007012
Peter Collingbourneedb66f32012-05-20 23:28:41 +00007013 case llvm::Triple::nvptx:
7014 case llvm::Triple::nvptx64:
Justin Holewinski2c585b92012-05-24 17:43:12 +00007015 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinski0259c3a2011-04-22 11:10:38 +00007016
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00007017 case llvm::Triple::msp430:
Chris Lattnerea044322010-07-29 02:01:43 +00007018 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00007019
Ulrich Weigandb8409212013-05-06 16:26:41 +00007020 case llvm::Triple::systemz:
7021 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
7022
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00007023 case llvm::Triple::tce:
7024 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7025
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00007026 case llvm::Triple::x86: {
John McCallb8b52972013-06-18 02:46:29 +00007027 bool IsDarwinVectorABI = Triple.isOSDarwin();
7028 bool IsSmallStructInRegABI =
7029 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007030 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbardb57a4c2011-04-19 21:43:27 +00007031
John McCallb8b52972013-06-18 02:46:29 +00007032 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedman55fc7e22012-01-25 22:46:34 +00007033 return *(TheTargetCodeGenInfo =
Reid Kleckner3190ca92013-05-08 13:44:39 +00007034 new WinX86_32TargetCodeGenInfo(Types,
John McCallb8b52972013-06-18 02:46:29 +00007035 IsDarwinVectorABI, IsSmallStructInRegABI,
7036 IsWin32FloatStructABI,
Reid Kleckner3190ca92013-05-08 13:44:39 +00007037 CodeGenOpts.NumRegisterParameters));
John McCallb8b52972013-06-18 02:46:29 +00007038 } else {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00007039 return *(TheTargetCodeGenInfo =
John McCallb8b52972013-06-18 02:46:29 +00007040 new X86_32TargetCodeGenInfo(Types,
7041 IsDarwinVectorABI, IsSmallStructInRegABI,
7042 IsWin32FloatStructABI,
Rafael Espindolab48280b2012-07-31 02:44:24 +00007043 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00007044 }
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00007045 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00007046
Eli Friedmanee1ad992011-12-02 00:11:43 +00007047 case llvm::Triple::x86_64: {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007048 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanee1ad992011-12-02 00:11:43 +00007049
Chris Lattnerf13721d2010-08-31 16:44:54 +00007050 switch (Triple.getOS()) {
7051 case llvm::Triple::Win32:
Stephen Hines176edba2014-12-01 14:53:08 -08007052 return *(TheTargetCodeGenInfo =
7053 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007054 case llvm::Triple::PS4:
7055 return *(TheTargetCodeGenInfo = new PS4TargetCodeGenInfo(Types, HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00007056 default:
Stephen Hines176edba2014-12-01 14:53:08 -08007057 return *(TheTargetCodeGenInfo =
7058 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00007059 }
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00007060 }
Tony Linthicum96319392011-12-12 21:14:55 +00007061 case llvm::Triple::hexagon:
7062 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007063 case llvm::Triple::r600:
7064 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
7065 case llvm::Triple::amdgcn:
7066 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00007067 case llvm::Triple::sparcv9:
7068 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton5f15f4d2013-08-13 09:43:10 +00007069 case llvm::Triple::xcore:
Stephen Hines651f13c2014-04-23 16:59:28 -07007070 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanee1ad992011-12-02 00:11:43 +00007071 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00007072}