blob: 44e001ceb6dcb97ec4a6b5edb09cde134614c6a4 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000018#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000021#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000022#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000025#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000026
27#include <algorithm> // std::sort
28
Anton Korobeynikov244360d2009-06-05 22:08:42 +000029using namespace clang;
30using namespace CodeGen;
31
John McCall943fae92010-05-27 06:19:26 +000032static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
33 llvm::Value *Array,
34 llvm::Value *Value,
35 unsigned FirstIndex,
36 unsigned LastIndex) {
37 // Alternatively, we could emit this as a loop in the source.
38 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
39 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
40 Builder.CreateStore(Value, Cell);
41 }
42}
43
John McCalla1dee5302010-08-22 10:59:02 +000044static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000045 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000046 T->isMemberFunctionPointerType();
47}
48
Anton Korobeynikov244360d2009-06-05 22:08:42 +000049ABIInfo::~ABIInfo() {}
50
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000051static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000052 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000053 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
54 if (!RD)
55 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000056 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000057}
58
59static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000060 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000061 const RecordType *RT = T->getAs<RecordType>();
62 if (!RT)
63 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000064 return getRecordArgABI(RT, CXXABI);
65}
66
67CGCXXABI &ABIInfo::getCXXABI() const {
68 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000069}
70
Chris Lattner2b037972010-07-29 02:01:43 +000071ASTContext &ABIInfo::getContext() const {
72 return CGT.getContext();
73}
74
75llvm::LLVMContext &ABIInfo::getVMContext() const {
76 return CGT.getLLVMContext();
77}
78
Micah Villmowdd31ca12012-10-08 16:25:52 +000079const llvm::DataLayout &ABIInfo::getDataLayout() const {
80 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000081}
82
John McCallc8e01702013-04-16 22:48:15 +000083const TargetInfo &ABIInfo::getTarget() const {
84 return CGT.getTarget();
85}
Chris Lattner2b037972010-07-29 02:01:43 +000086
Anton Korobeynikov244360d2009-06-05 22:08:42 +000087void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000088 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +000089 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +000090 switch (TheKind) {
91 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +000092 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +000093 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +000094 Ty->print(OS);
95 else
96 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +000097 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +000098 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +000099 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000100 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000101 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000102 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000103 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000104 case InAlloca:
105 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
106 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000107 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000108 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000109 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000110 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000111 break;
112 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000113 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000114 break;
115 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000116 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000117}
118
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000119TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
120
John McCall3480ef22011-08-30 01:42:09 +0000121// If someone can figure out a general rule for this, that would be great.
122// It's probably just doomed to be platform-dependent, though.
123unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
124 // Verified for:
125 // x86-64 FreeBSD, Linux, Darwin
126 // x86-32 FreeBSD, Linux, Darwin
127 // PowerPC Linux, Darwin
128 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000129 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000130 return 32;
131}
132
John McCalla729c622012-02-17 03:33:10 +0000133bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
134 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000135 // The following conventions are known to require this to be false:
136 // x86_stdcall
137 // MIPS
138 // For everything else, we just prefer false unless we opt out.
139 return false;
140}
141
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000142void
143TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
144 llvm::SmallString<24> &Opt) const {
145 // This assumes the user is passing a library name like "rt" instead of a
146 // filename like "librt.a/so", and that they don't care whether it's static or
147 // dynamic.
148 Opt = "-l";
149 Opt += Lib;
150}
151
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000152static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000153
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000154/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000155/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000156static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
157 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000158 if (FD->isUnnamedBitfield())
159 return true;
160
161 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000162
Eli Friedman0b3f2012011-11-18 03:47:20 +0000163 // Constant arrays of empty records count as empty, strip them off.
164 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000165 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000166 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
167 if (AT->getSize() == 0)
168 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000169 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000170 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000171
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000172 const RecordType *RT = FT->getAs<RecordType>();
173 if (!RT)
174 return false;
175
176 // C++ record fields are never empty, at least in the Itanium ABI.
177 //
178 // FIXME: We should use a predicate for whether this behavior is true in the
179 // current ABI.
180 if (isa<CXXRecordDecl>(RT->getDecl()))
181 return false;
182
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000183 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000184}
185
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000186/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000187/// fields. Note that a structure with a flexible array member is not
188/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000189static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000190 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000191 if (!RT)
192 return 0;
193 const RecordDecl *RD = RT->getDecl();
194 if (RD->hasFlexibleArrayMember())
195 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000196
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000197 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000198 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000199 for (const auto &I : CXXRD->bases())
200 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000201 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000202
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000203 for (const auto *I : RD->fields())
204 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000205 return false;
206 return true;
207}
208
209/// isSingleElementStruct - Determine if a structure is a "single
210/// element struct", i.e. it has exactly one non-empty field or
211/// exactly one field which is itself a single element
212/// struct. Structures with flexible array members are never
213/// considered single element structs.
214///
215/// \return The field declaration for the single non-empty field, if
216/// it exists.
217static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
218 const RecordType *RT = T->getAsStructureType();
219 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000220 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000221
222 const RecordDecl *RD = RT->getDecl();
223 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000224 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000225
Craig Topper8a13c412014-05-21 05:09:00 +0000226 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000227
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000228 // If this is a C++ record, check the bases first.
229 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000230 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000231 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000232 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000233 continue;
234
235 // If we already found an element then this isn't a single-element struct.
236 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000237 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000238
239 // If this is non-empty and not a single element struct, the composite
240 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000241 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000242 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000243 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000244 }
245 }
246
247 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000248 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000249 QualType FT = FD->getType();
250
251 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000252 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000253 continue;
254
255 // If we already found an element then this isn't a single-element
256 // struct.
257 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000258 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000259
260 // Treat single element arrays as the element.
261 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
262 if (AT->getSize().getZExtValue() != 1)
263 break;
264 FT = AT->getElementType();
265 }
266
John McCalla1dee5302010-08-22 10:59:02 +0000267 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000268 Found = FT.getTypePtr();
269 } else {
270 Found = isSingleElementStruct(FT, Context);
271 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000272 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000273 }
274 }
275
Eli Friedmanee945342011-11-18 01:25:50 +0000276 // We don't consider a struct a single-element struct if it has
277 // padding beyond the element type.
278 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000279 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000280
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000281 return Found;
282}
283
284static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000285 // Treat complex types as the element type.
286 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
287 Ty = CTy->getElementType();
288
289 // Check for a type which we know has a simple scalar argument-passing
290 // convention without any padding. (We're specifically looking for 32
291 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000292 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000293 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000294 return false;
295
296 uint64_t Size = Context.getTypeSize(Ty);
297 return Size == 32 || Size == 64;
298}
299
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000300/// canExpandIndirectArgument - Test whether an argument type which is to be
301/// passed indirectly (on the stack) would have the equivalent layout if it was
302/// expanded into separate arguments. If so, we prefer to do the latter to avoid
303/// inhibiting optimizations.
304///
305// FIXME: This predicate is missing many cases, currently it just follows
306// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
307// should probably make this smarter, or better yet make the LLVM backend
308// capable of handling it.
309static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
310 // We can only expand structure types.
311 const RecordType *RT = Ty->getAs<RecordType>();
312 if (!RT)
313 return false;
314
315 // We can only expand (C) structures.
316 //
317 // FIXME: This needs to be generalized to handle classes as well.
318 const RecordDecl *RD = RT->getDecl();
319 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
320 return false;
321
Eli Friedmane5c85622011-11-18 01:32:26 +0000322 uint64_t Size = 0;
323
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000324 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000325 if (!is32Or64BitBasicType(FD->getType(), Context))
326 return false;
327
328 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
329 // how to expand them yet, and the predicate for telling if a bitfield still
330 // counts as "basic" is more complicated than what we were doing previously.
331 if (FD->isBitField())
332 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000333
334 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000335 }
336
Eli Friedmane5c85622011-11-18 01:32:26 +0000337 // Make sure there are not any holes in the struct.
338 if (Size != Context.getTypeSize(Ty))
339 return false;
340
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000341 return true;
342}
343
344namespace {
345/// DefaultABIInfo - The default implementation for ABI specific
346/// details. This implementation provides information which results in
347/// self-consistent and sensible LLVM IR generation, but does not
348/// conform to any particular ABI.
349class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000350public:
351 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000352
Chris Lattner458b2aa2010-07-29 02:16:43 +0000353 ABIArgInfo classifyReturnType(QualType RetTy) const;
354 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000355
Craig Topper4f12f102014-03-12 06:41:41 +0000356 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000357 if (!getCXXABI().classifyReturnType(FI))
358 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000359 for (auto &I : FI.arguments())
360 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000361 }
362
Craig Topper4f12f102014-03-12 06:41:41 +0000363 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
364 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000365};
366
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000367class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
368public:
Chris Lattner2b037972010-07-29 02:01:43 +0000369 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
370 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000371};
372
373llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
374 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000375 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000376}
377
Chris Lattner458b2aa2010-07-29 02:16:43 +0000378ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000379 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000380 return ABIArgInfo::getIndirect(0);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000381
Chris Lattner9723d6c2010-03-11 18:19:55 +0000382 // Treat an enum type as its underlying type.
383 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
384 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000385
Chris Lattner9723d6c2010-03-11 18:19:55 +0000386 return (Ty->isPromotableIntegerType() ?
387 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000388}
389
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000390ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
391 if (RetTy->isVoidType())
392 return ABIArgInfo::getIgnore();
393
394 if (isAggregateTypeForABI(RetTy))
395 return ABIArgInfo::getIndirect(0);
396
397 // Treat an enum type as its underlying type.
398 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
399 RetTy = EnumTy->getDecl()->getIntegerType();
400
401 return (RetTy->isPromotableIntegerType() ?
402 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
403}
404
Derek Schuff09338a22012-09-06 17:37:28 +0000405//===----------------------------------------------------------------------===//
406// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000407//
408// This is a simplified version of the x86_32 ABI. Arguments and return values
409// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000410//===----------------------------------------------------------------------===//
411
412class PNaClABIInfo : public ABIInfo {
413 public:
414 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
415
416 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000417 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000418
Craig Topper4f12f102014-03-12 06:41:41 +0000419 void computeInfo(CGFunctionInfo &FI) const override;
420 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
421 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000422};
423
424class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
425 public:
426 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
427 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
428};
429
430void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000431 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000432 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
433
Reid Kleckner40ca9132014-05-13 22:05:45 +0000434 for (auto &I : FI.arguments())
435 I.info = classifyArgumentType(I.type);
436}
Derek Schuff09338a22012-09-06 17:37:28 +0000437
438llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
439 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000440 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000441}
442
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000443/// \brief Classify argument of given type \p Ty.
444ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000445 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000446 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000447 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000448 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000449 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
450 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000451 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000452 } else if (Ty->isFloatingType()) {
453 // Floating-point types don't go inreg.
454 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000455 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000456
457 return (Ty->isPromotableIntegerType() ?
458 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000459}
460
461ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
462 if (RetTy->isVoidType())
463 return ABIArgInfo::getIgnore();
464
Eli Benderskye20dad62013-04-04 22:49:35 +0000465 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000466 if (isAggregateTypeForABI(RetTy))
467 return ABIArgInfo::getIndirect(0);
468
469 // Treat an enum type as its underlying type.
470 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
471 RetTy = EnumTy->getDecl()->getIntegerType();
472
473 return (RetTy->isPromotableIntegerType() ?
474 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
475}
476
Chad Rosier651c1832013-03-25 21:00:27 +0000477/// IsX86_MMXType - Return true if this is an MMX type.
478bool IsX86_MMXType(llvm::Type *IRType) {
479 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendling5cd41c42010-10-18 03:41:31 +0000480 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
481 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
482 IRType->getScalarSizeInBits() != 64;
483}
484
Jay Foad7c57be32011-07-11 09:56:20 +0000485static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000487 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000488 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
489 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
490 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000491 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000492 }
493
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000494 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000495 }
496
497 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000498 return Ty;
499}
500
Chris Lattner0cf24192010-06-28 20:05:43 +0000501//===----------------------------------------------------------------------===//
502// X86-32 ABI Implementation
503//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000504
Reid Kleckner661f35b2014-01-18 01:12:41 +0000505/// \brief Similar to llvm::CCState, but for Clang.
506struct CCState {
507 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
508
509 unsigned CC;
510 unsigned FreeRegs;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000511 unsigned StackOffset;
512 bool UseInAlloca;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000513};
514
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000515/// X86_32ABIInfo - The X86-32 ABI information.
516class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000517 enum Class {
518 Integer,
519 Float
520 };
521
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000522 static const unsigned MinABIStackAlignInBytes = 4;
523
David Chisnallde3a0692009-08-17 23:08:21 +0000524 bool IsDarwinVectorABI;
525 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000526 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000527 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000528
529 static bool isRegisterSize(unsigned Size) {
530 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
531 }
532
Reid Kleckner40ca9132014-05-13 22:05:45 +0000533 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000534
Daniel Dunbar557893d2010-04-21 19:10:51 +0000535 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
536 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000537 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
538
539 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000540
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000541 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000542 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000543
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000544 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000545 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000546 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
547 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000548
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000549 /// \brief Rewrite the function info so that all memory arguments use
550 /// inalloca.
551 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
552
553 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
554 unsigned &StackOffset, ABIArgInfo &Info,
555 QualType Type) const;
556
Rafael Espindola75419dc2012-07-23 23:30:29 +0000557public:
558
Craig Topper4f12f102014-03-12 06:41:41 +0000559 void computeInfo(CGFunctionInfo &FI) const override;
560 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
561 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000562
Chad Rosier651c1832013-03-25 21:00:27 +0000563 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000564 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000565 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000566 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000567};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000568
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000569class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
570public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000571 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000572 bool d, bool p, bool w, unsigned r)
573 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000574
John McCall1fe2a8c2013-06-18 02:46:29 +0000575 static bool isStructReturnInRegABI(
576 const llvm::Triple &Triple, const CodeGenOptions &Opts);
577
Charles Davis4ea31ab2010-02-13 15:54:06 +0000578 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000579 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000580
Craig Topper4f12f102014-03-12 06:41:41 +0000581 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000582 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000583 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000584 return 4;
585 }
586
587 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000588 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000589
Jay Foad7c57be32011-07-11 09:56:20 +0000590 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000591 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000592 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000593 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
594 }
595
Craig Topper4f12f102014-03-12 06:41:41 +0000596 llvm::Constant *
597 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000598 unsigned Sig = (0xeb << 0) | // jmp rel8
599 (0x06 << 8) | // .+0x08
600 ('F' << 16) |
601 ('T' << 24);
602 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
603 }
604
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000605};
606
607}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000608
609/// shouldReturnTypeInRegister - Determine if the given type should be
610/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000611bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
612 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000613 uint64_t Size = Context.getTypeSize(Ty);
614
615 // Type must be register sized.
616 if (!isRegisterSize(Size))
617 return false;
618
619 if (Ty->isVectorType()) {
620 // 64- and 128- bit vectors inside structures are not returned in
621 // registers.
622 if (Size == 64 || Size == 128)
623 return false;
624
625 return true;
626 }
627
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000628 // If this is a builtin, pointer, enum, complex type, member pointer, or
629 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000630 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000631 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000632 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000633 return true;
634
635 // Arrays are treated like records.
636 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000637 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000638
639 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000640 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000641 if (!RT) return false;
642
Anders Carlsson40446e82010-01-27 03:25:19 +0000643 // FIXME: Traverse bases here too.
644
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000645 // Structure types are passed in register if all fields would be
646 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000647 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000648 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000649 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000650 continue;
651
652 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000653 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000654 return false;
655 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000656 return true;
657}
658
Reid Kleckner661f35b2014-01-18 01:12:41 +0000659ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
660 // If the return value is indirect, then the hidden argument is consuming one
661 // integer register.
662 if (State.FreeRegs) {
663 --State.FreeRegs;
664 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
665 }
666 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
667}
668
Reid Kleckner40ca9132014-05-13 22:05:45 +0000669ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000670 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000671 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000672
Chris Lattner458b2aa2010-07-29 02:16:43 +0000673 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000674 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000675 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000676 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000677
678 // 128-bit vectors are a special case; they are returned in
679 // registers and we need to make sure to pick a type the LLVM
680 // backend will like.
681 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000682 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000683 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000684
685 // Always return in register if it fits in a general purpose
686 // register, or if it is 64 bits and has a single element.
687 if ((Size == 8 || Size == 16 || Size == 32) ||
688 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000689 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000690 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000691
Reid Kleckner661f35b2014-01-18 01:12:41 +0000692 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000693 }
694
695 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000696 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000697
John McCalla1dee5302010-08-22 10:59:02 +0000698 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000699 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000700 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000701 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000702 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000703 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000704
David Chisnallde3a0692009-08-17 23:08:21 +0000705 // If specified, structs and unions are always indirect.
706 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000707 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000708
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000709 // Small structures which are register sized are generally returned
710 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000711 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000712 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000713
714 // As a special-case, if the struct is a "single-element" struct, and
715 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000716 // floating-point register. (MSVC does not apply this special case.)
717 // We apply a similar transformation for pointer types to improve the
718 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000719 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000720 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000721 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000722 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
723
724 // FIXME: We should be able to narrow this integer in cases with dead
725 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000726 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000727 }
728
Reid Kleckner661f35b2014-01-18 01:12:41 +0000729 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000730 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000731
Chris Lattner458b2aa2010-07-29 02:16:43 +0000732 // Treat an enum type as its underlying type.
733 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
734 RetTy = EnumTy->getDecl()->getIntegerType();
735
736 return (RetTy->isPromotableIntegerType() ?
737 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000738}
739
Eli Friedman7919bea2012-06-05 19:40:46 +0000740static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
741 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
742}
743
Daniel Dunbared23de32010-09-16 20:42:00 +0000744static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
745 const RecordType *RT = Ty->getAs<RecordType>();
746 if (!RT)
747 return 0;
748 const RecordDecl *RD = RT->getDecl();
749
750 // If this is a C++ record, check the bases first.
751 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000752 for (const auto &I : CXXRD->bases())
753 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000754 return false;
755
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000756 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000757 QualType FT = i->getType();
758
Eli Friedman7919bea2012-06-05 19:40:46 +0000759 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000760 return true;
761
762 if (isRecordWithSSEVectorType(Context, FT))
763 return true;
764 }
765
766 return false;
767}
768
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000769unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
770 unsigned Align) const {
771 // Otherwise, if the alignment is less than or equal to the minimum ABI
772 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000773 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000774 return 0; // Use default alignment.
775
776 // On non-Darwin, the stack type alignment is always 4.
777 if (!IsDarwinVectorABI) {
778 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000779 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000780 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000781
Daniel Dunbared23de32010-09-16 20:42:00 +0000782 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000783 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
784 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000785 return 16;
786
787 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000788}
789
Rafael Espindola703c47f2012-10-19 05:04:37 +0000790ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000791 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000792 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000793 if (State.FreeRegs) {
794 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000795 return ABIArgInfo::getIndirectInReg(0, false);
796 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000797 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000798 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000799
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000800 // Compute the byval alignment.
801 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
802 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
803 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000804 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000805
806 // If the stack alignment is less than the type alignment, realign the
807 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000808 bool Realign = TypeAlign > StackAlign;
809 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000810}
811
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000812X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
813 const Type *T = isSingleElementStruct(Ty, getContext());
814 if (!T)
815 T = Ty.getTypePtr();
816
817 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
818 BuiltinType::Kind K = BT->getKind();
819 if (K == BuiltinType::Float || K == BuiltinType::Double)
820 return Float;
821 }
822 return Integer;
823}
824
Reid Kleckner661f35b2014-01-18 01:12:41 +0000825bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
826 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000827 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000828 Class C = classify(Ty);
829 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000830 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000831
Rafael Espindola077dd592012-10-24 01:58:58 +0000832 unsigned Size = getContext().getTypeSize(Ty);
833 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000834
835 if (SizeInRegs == 0)
836 return false;
837
Reid Kleckner661f35b2014-01-18 01:12:41 +0000838 if (SizeInRegs > State.FreeRegs) {
839 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000840 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000841 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000842
Reid Kleckner661f35b2014-01-18 01:12:41 +0000843 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000844
Reid Kleckner661f35b2014-01-18 01:12:41 +0000845 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000846 if (Size > 32)
847 return false;
848
849 if (Ty->isIntegralOrEnumerationType())
850 return true;
851
852 if (Ty->isPointerType())
853 return true;
854
855 if (Ty->isReferenceType())
856 return true;
857
Reid Kleckner661f35b2014-01-18 01:12:41 +0000858 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000859 NeedsPadding = true;
860
Rafael Espindola077dd592012-10-24 01:58:58 +0000861 return false;
862 }
863
Rafael Espindola703c47f2012-10-19 05:04:37 +0000864 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000865}
866
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000867ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
868 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000869 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000870 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000871 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000872 // Check with the C++ ABI first.
873 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
874 if (RAA == CGCXXABI::RAA_Indirect) {
875 return getIndirectResult(Ty, false, State);
876 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
877 // The field index doesn't matter, we'll fix it up later.
878 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
879 }
880
881 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000882 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000883 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000884
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000885 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000886 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000887 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000888 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000889
Eli Friedman9f061a32011-11-18 00:28:11 +0000890 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000891 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000892 return ABIArgInfo::getIgnore();
893
Rafael Espindolafad28de2012-10-24 01:59:00 +0000894 llvm::LLVMContext &LLVMContext = getVMContext();
895 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
896 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000897 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000898 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000899 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000900 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
901 return ABIArgInfo::getDirectInReg(Result);
902 }
Craig Topper8a13c412014-05-21 05:09:00 +0000903 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000904
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000905 // Expand small (<= 128-bit) record types when we know that the stack layout
906 // of those arguments will match the struct. This is important because the
907 // LLVM backend isn't smart enough to remove byval, which inhibits many
908 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +0000909 if (getContext().getTypeSize(Ty) <= 4*32 &&
910 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000911 return ABIArgInfo::getExpandWithPadding(
912 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000913
Reid Kleckner661f35b2014-01-18 01:12:41 +0000914 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000915 }
916
Chris Lattnerd774ae92010-08-26 20:05:13 +0000917 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +0000918 // On Darwin, some vectors are passed in memory, we handle this by passing
919 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +0000920 if (IsDarwinVectorABI) {
921 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +0000922 if ((Size == 8 || Size == 16 || Size == 32) ||
923 (Size == 64 && VT->getNumElements() == 1))
924 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
925 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +0000926 }
Bill Wendling5cd41c42010-10-18 03:41:31 +0000927
Chad Rosier651c1832013-03-25 21:00:27 +0000928 if (IsX86_MMXType(CGT.ConvertType(Ty)))
929 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000930
Chris Lattnerd774ae92010-08-26 20:05:13 +0000931 return ABIArgInfo::getDirect();
932 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000933
934
Chris Lattner458b2aa2010-07-29 02:16:43 +0000935 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
936 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000937
Rafael Espindolafad28de2012-10-24 01:59:00 +0000938 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000939 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000940
941 if (Ty->isPromotableIntegerType()) {
942 if (InReg)
943 return ABIArgInfo::getExtendInReg();
944 return ABIArgInfo::getExtend();
945 }
946 if (InReg)
947 return ABIArgInfo::getDirectInReg();
948 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000949}
950
Rafael Espindolaa6472962012-07-24 00:01:07 +0000951void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000952 CCState State(FI.getCallingConvention());
953 if (State.CC == llvm::CallingConv::X86_FastCall)
954 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +0000955 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000956 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +0000957 else
Reid Kleckner661f35b2014-01-18 01:12:41 +0000958 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000959
Reid Kleckner40ca9132014-05-13 22:05:45 +0000960 if (!getCXXABI().classifyReturnType(FI))
961 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000962
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000963 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000964 for (auto &I : FI.arguments()) {
965 I.info = classifyArgumentType(I.type, State);
966 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000967 }
968
969 // If we needed to use inalloca for any argument, do a second pass and rewrite
970 // all the memory arguments to use inalloca.
971 if (UsedInAlloca)
972 rewriteWithInAlloca(FI);
973}
974
975void
976X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
977 unsigned &StackOffset,
978 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +0000979 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
980 Info = ABIArgInfo::getInAlloca(FrameFields.size());
981 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
982 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
983
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000984 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
985 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +0000986 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000987 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +0000988 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000989 unsigned NumBytes = StackOffset - OldOffset;
990 assert(NumBytes);
991 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
992 Ty = llvm::ArrayType::get(Ty, NumBytes);
993 FrameFields.push_back(Ty);
994 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000995}
996
997void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
998 assert(IsWin32StructABI && "inalloca only supported on win32");
999
1000 // Build a packed struct type for all of the arguments in memory.
1001 SmallVector<llvm::Type *, 6> FrameFields;
1002
1003 unsigned StackOffset = 0;
1004
1005 // Put the sret parameter into the inalloca struct if it's in memory.
1006 ABIArgInfo &Ret = FI.getReturnInfo();
1007 if (Ret.isIndirect() && !Ret.getInReg()) {
1008 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1009 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001010 // On Windows, the hidden sret parameter is always returned in eax.
1011 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001012 }
1013
1014 // Skip the 'this' parameter in ecx.
1015 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1016 if (FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall)
1017 ++I;
1018
1019 // Put arguments passed in memory into the struct.
1020 for (; I != E; ++I) {
1021
1022 // Leave ignored and inreg arguments alone.
1023 switch (I->info.getKind()) {
1024 case ABIArgInfo::Indirect:
1025 assert(I->info.getIndirectByVal());
1026 break;
1027 case ABIArgInfo::Ignore:
1028 continue;
1029 case ABIArgInfo::Direct:
1030 case ABIArgInfo::Extend:
1031 if (I->info.getInReg())
1032 continue;
1033 break;
1034 default:
1035 break;
1036 }
1037
1038 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1039 }
1040
1041 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1042 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001043}
1044
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001045llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1046 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001047 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001048
1049 CGBuilderTy &Builder = CGF.Builder;
1050 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1051 "ap");
1052 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001053
1054 // Compute if the address needs to be aligned
1055 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1056 Align = getTypeStackAlignInBytes(Ty, Align);
1057 Align = std::max(Align, 4U);
1058 if (Align > 4) {
1059 // addr = (addr + align - 1) & -align;
1060 llvm::Value *Offset =
1061 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1062 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1063 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1064 CGF.Int32Ty);
1065 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1066 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1067 Addr->getType(),
1068 "ap.cur.aligned");
1069 }
1070
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001071 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001072 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001073 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1074
1075 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001076 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001077 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001078 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001079 "ap.next");
1080 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1081
1082 return AddrTyped;
1083}
1084
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001085bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1086 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1087 assert(Triple.getArch() == llvm::Triple::x86);
1088
1089 switch (Opts.getStructReturnConvention()) {
1090 case CodeGenOptions::SRCK_Default:
1091 break;
1092 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1093 return false;
1094 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1095 return true;
1096 }
1097
1098 if (Triple.isOSDarwin())
1099 return true;
1100
1101 switch (Triple.getOS()) {
1102 case llvm::Triple::AuroraUX:
1103 case llvm::Triple::DragonFly:
1104 case llvm::Triple::FreeBSD:
1105 case llvm::Triple::OpenBSD:
1106 case llvm::Triple::Bitrig:
1107 return true;
1108 case llvm::Triple::Win32:
1109 switch (Triple.getEnvironment()) {
1110 case llvm::Triple::UnknownEnvironment:
1111 case llvm::Triple::Cygnus:
1112 case llvm::Triple::GNU:
1113 case llvm::Triple::MSVC:
1114 return true;
1115 default:
1116 return false;
1117 }
1118 default:
1119 return false;
1120 }
1121}
1122
Charles Davis4ea31ab2010-02-13 15:54:06 +00001123void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1124 llvm::GlobalValue *GV,
1125 CodeGen::CodeGenModule &CGM) const {
1126 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1127 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1128 // Get the LLVM function.
1129 llvm::Function *Fn = cast<llvm::Function>(GV);
1130
1131 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001132 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001133 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001134 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1135 llvm::AttributeSet::get(CGM.getLLVMContext(),
1136 llvm::AttributeSet::FunctionIndex,
1137 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001138 }
1139 }
1140}
1141
John McCallbeec5a02010-03-06 00:35:14 +00001142bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1143 CodeGen::CodeGenFunction &CGF,
1144 llvm::Value *Address) const {
1145 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001146
Chris Lattnerece04092012-02-07 00:39:47 +00001147 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001148
John McCallbeec5a02010-03-06 00:35:14 +00001149 // 0-7 are the eight integer registers; the order is different
1150 // on Darwin (for EH), but the range is the same.
1151 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001152 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001153
John McCallc8e01702013-04-16 22:48:15 +00001154 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001155 // 12-16 are st(0..4). Not sure why we stop at 4.
1156 // These have size 16, which is sizeof(long double) on
1157 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001158 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001159 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001160
John McCallbeec5a02010-03-06 00:35:14 +00001161 } else {
1162 // 9 is %eflags, which doesn't get a size on Darwin for some
1163 // reason.
1164 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1165
1166 // 11-16 are st(0..5). Not sure why we stop at 5.
1167 // These have size 12, which is sizeof(long double) on
1168 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001169 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001170 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1171 }
John McCallbeec5a02010-03-06 00:35:14 +00001172
1173 return false;
1174}
1175
Chris Lattner0cf24192010-06-28 20:05:43 +00001176//===----------------------------------------------------------------------===//
1177// X86-64 ABI Implementation
1178//===----------------------------------------------------------------------===//
1179
1180
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001181namespace {
1182/// X86_64ABIInfo - The X86_64 ABI information.
1183class X86_64ABIInfo : public ABIInfo {
1184 enum Class {
1185 Integer = 0,
1186 SSE,
1187 SSEUp,
1188 X87,
1189 X87Up,
1190 ComplexX87,
1191 NoClass,
1192 Memory
1193 };
1194
1195 /// merge - Implement the X86_64 ABI merging algorithm.
1196 ///
1197 /// Merge an accumulating classification \arg Accum with a field
1198 /// classification \arg Field.
1199 ///
1200 /// \param Accum - The accumulating classification. This should
1201 /// always be either NoClass or the result of a previous merge
1202 /// call. In addition, this should never be Memory (the caller
1203 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001204 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001205
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001206 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1207 ///
1208 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1209 /// final MEMORY or SSE classes when necessary.
1210 ///
1211 /// \param AggregateSize - The size of the current aggregate in
1212 /// the classification process.
1213 ///
1214 /// \param Lo - The classification for the parts of the type
1215 /// residing in the low word of the containing object.
1216 ///
1217 /// \param Hi - The classification for the parts of the type
1218 /// residing in the higher words of the containing object.
1219 ///
1220 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1221
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001222 /// classify - Determine the x86_64 register classes in which the
1223 /// given type T should be passed.
1224 ///
1225 /// \param Lo - The classification for the parts of the type
1226 /// residing in the low word of the containing object.
1227 ///
1228 /// \param Hi - The classification for the parts of the type
1229 /// residing in the high word of the containing object.
1230 ///
1231 /// \param OffsetBase - The bit offset of this type in the
1232 /// containing object. Some parameters are classified different
1233 /// depending on whether they straddle an eightbyte boundary.
1234 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001235 /// \param isNamedArg - Whether the argument in question is a "named"
1236 /// argument, as used in AMD64-ABI 3.5.7.
1237 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001238 /// If a word is unused its result will be NoClass; if a type should
1239 /// be passed in Memory then at least the classification of \arg Lo
1240 /// will be Memory.
1241 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001242 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001243 ///
1244 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1245 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001246 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1247 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001248
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001249 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001250 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1251 unsigned IROffset, QualType SourceTy,
1252 unsigned SourceOffset) const;
1253 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1254 unsigned IROffset, QualType SourceTy,
1255 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001256
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001257 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001258 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001259 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001260
1261 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001262 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001263 ///
1264 /// \param freeIntRegs - The number of free integer registers remaining
1265 /// available.
1266 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001267
Chris Lattner458b2aa2010-07-29 02:16:43 +00001268 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001269
Bill Wendling5cd41c42010-10-18 03:41:31 +00001270 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001271 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001272 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001273 unsigned &neededSSE,
1274 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001275
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001276 bool IsIllegalVectorType(QualType Ty) const;
1277
John McCalle0fda732011-04-21 01:20:55 +00001278 /// The 0.98 ABI revision clarified a lot of ambiguities,
1279 /// unfortunately in ways that were not always consistent with
1280 /// certain previous compilers. In particular, platforms which
1281 /// required strict binary compatibility with older versions of GCC
1282 /// may need to exempt themselves.
1283 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001284 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001285 }
1286
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001287 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001288 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1289 // 64-bit hardware.
1290 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001291
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001292public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001293 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001294 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001295 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001296 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001297
John McCalla729c622012-02-17 03:33:10 +00001298 bool isPassedUsingAVXType(QualType type) const {
1299 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001300 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001301 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1302 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001303 if (info.isDirect()) {
1304 llvm::Type *ty = info.getCoerceToType();
1305 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1306 return (vectorTy->getBitWidth() > 128);
1307 }
1308 return false;
1309 }
1310
Craig Topper4f12f102014-03-12 06:41:41 +00001311 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001312
Craig Topper4f12f102014-03-12 06:41:41 +00001313 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1314 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001315};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001316
Chris Lattner04dc9572010-08-31 16:44:54 +00001317/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001318class WinX86_64ABIInfo : public ABIInfo {
1319
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001320 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001321
Chris Lattner04dc9572010-08-31 16:44:54 +00001322public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001323 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1324
Craig Topper4f12f102014-03-12 06:41:41 +00001325 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001326
Craig Topper4f12f102014-03-12 06:41:41 +00001327 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1328 CodeGenFunction &CGF) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001329};
1330
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001331class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1332public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001333 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001334 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001335
John McCalla729c622012-02-17 03:33:10 +00001336 const X86_64ABIInfo &getABIInfo() const {
1337 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1338 }
1339
Craig Topper4f12f102014-03-12 06:41:41 +00001340 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001341 return 7;
1342 }
1343
1344 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001345 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001346 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001347
John McCall943fae92010-05-27 06:19:26 +00001348 // 0-15 are the 16 integer registers.
1349 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001350 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001351 return false;
1352 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001353
Jay Foad7c57be32011-07-11 09:56:20 +00001354 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001355 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001356 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001357 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1358 }
1359
John McCalla729c622012-02-17 03:33:10 +00001360 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001361 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001362 // The default CC on x86-64 sets %al to the number of SSA
1363 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001364 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001365 // that when AVX types are involved: the ABI explicitly states it is
1366 // undefined, and it doesn't work in practice because of how the ABI
1367 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001368 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001369 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001370 for (CallArgList::const_iterator
1371 it = args.begin(), ie = args.end(); it != ie; ++it) {
1372 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1373 HasAVXType = true;
1374 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001375 }
1376 }
John McCalla729c622012-02-17 03:33:10 +00001377
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001378 if (!HasAVXType)
1379 return true;
1380 }
John McCallcbc038a2011-09-21 08:08:30 +00001381
John McCalla729c622012-02-17 03:33:10 +00001382 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001383 }
1384
Craig Topper4f12f102014-03-12 06:41:41 +00001385 llvm::Constant *
1386 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001387 unsigned Sig = (0xeb << 0) | // jmp rel8
1388 (0x0a << 8) | // .+0x0c
1389 ('F' << 16) |
1390 ('T' << 24);
1391 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1392 }
1393
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001394};
1395
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001396static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1397 // If the argument does not end in .lib, automatically add the suffix. This
1398 // matches the behavior of MSVC.
1399 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001400 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001401 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001402 return ArgStr;
1403}
1404
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001405class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1406public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001407 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1408 bool d, bool p, bool w, unsigned RegParms)
1409 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001410
1411 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001412 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001413 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001414 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001415 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001416
1417 void getDetectMismatchOption(llvm::StringRef Name,
1418 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001419 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001420 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001421 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001422};
1423
Chris Lattner04dc9572010-08-31 16:44:54 +00001424class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1425public:
1426 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1427 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1428
Craig Topper4f12f102014-03-12 06:41:41 +00001429 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001430 return 7;
1431 }
1432
1433 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001434 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001435 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001436
Chris Lattner04dc9572010-08-31 16:44:54 +00001437 // 0-15 are the 16 integer registers.
1438 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001439 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001440 return false;
1441 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001442
1443 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001444 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001445 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001446 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001447 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001448
1449 void getDetectMismatchOption(llvm::StringRef Name,
1450 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001451 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001452 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001453 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001454};
1455
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001456}
1457
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001458void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1459 Class &Hi) const {
1460 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1461 //
1462 // (a) If one of the classes is Memory, the whole argument is passed in
1463 // memory.
1464 //
1465 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1466 // memory.
1467 //
1468 // (c) If the size of the aggregate exceeds two eightbytes and the first
1469 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1470 // argument is passed in memory. NOTE: This is necessary to keep the
1471 // ABI working for processors that don't support the __m256 type.
1472 //
1473 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1474 //
1475 // Some of these are enforced by the merging logic. Others can arise
1476 // only with unions; for example:
1477 // union { _Complex double; unsigned; }
1478 //
1479 // Note that clauses (b) and (c) were added in 0.98.
1480 //
1481 if (Hi == Memory)
1482 Lo = Memory;
1483 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1484 Lo = Memory;
1485 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1486 Lo = Memory;
1487 if (Hi == SSEUp && Lo != SSE)
1488 Hi = SSE;
1489}
1490
Chris Lattnerd776fb12010-06-28 21:43:59 +00001491X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001492 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1493 // classified recursively so that always two fields are
1494 // considered. The resulting class is calculated according to
1495 // the classes of the fields in the eightbyte:
1496 //
1497 // (a) If both classes are equal, this is the resulting class.
1498 //
1499 // (b) If one of the classes is NO_CLASS, the resulting class is
1500 // the other class.
1501 //
1502 // (c) If one of the classes is MEMORY, the result is the MEMORY
1503 // class.
1504 //
1505 // (d) If one of the classes is INTEGER, the result is the
1506 // INTEGER.
1507 //
1508 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1509 // MEMORY is used as class.
1510 //
1511 // (f) Otherwise class SSE is used.
1512
1513 // Accum should never be memory (we should have returned) or
1514 // ComplexX87 (because this cannot be passed in a structure).
1515 assert((Accum != Memory && Accum != ComplexX87) &&
1516 "Invalid accumulated classification during merge.");
1517 if (Accum == Field || Field == NoClass)
1518 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001519 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001520 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001521 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001522 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001523 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001524 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001525 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1526 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001527 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001528 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001529}
1530
Chris Lattner5c740f12010-06-30 19:14:05 +00001531void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001532 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001533 // FIXME: This code can be simplified by introducing a simple value class for
1534 // Class pairs with appropriate constructor methods for the various
1535 // situations.
1536
1537 // FIXME: Some of the split computations are wrong; unaligned vectors
1538 // shouldn't be passed in registers for example, so there is no chance they
1539 // can straddle an eightbyte. Verify & simplify.
1540
1541 Lo = Hi = NoClass;
1542
1543 Class &Current = OffsetBase < 64 ? Lo : Hi;
1544 Current = Memory;
1545
John McCall9dd450b2009-09-21 23:43:11 +00001546 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001547 BuiltinType::Kind k = BT->getKind();
1548
1549 if (k == BuiltinType::Void) {
1550 Current = NoClass;
1551 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1552 Lo = Integer;
1553 Hi = Integer;
1554 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1555 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001556 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1557 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001558 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001559 Current = SSE;
1560 } else if (k == BuiltinType::LongDouble) {
1561 Lo = X87;
1562 Hi = X87Up;
1563 }
1564 // FIXME: _Decimal32 and _Decimal64 are SSE.
1565 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001566 return;
1567 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001568
Chris Lattnerd776fb12010-06-28 21:43:59 +00001569 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001570 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001571 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001572 return;
1573 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001574
Chris Lattnerd776fb12010-06-28 21:43:59 +00001575 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001576 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001577 return;
1578 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001579
Chris Lattnerd776fb12010-06-28 21:43:59 +00001580 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001581 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001582 Lo = Hi = Integer;
1583 else
1584 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001585 return;
1586 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001587
Chris Lattnerd776fb12010-06-28 21:43:59 +00001588 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001589 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001590 if (Size == 32) {
1591 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1592 // float> as integer.
1593 Current = Integer;
1594
1595 // If this type crosses an eightbyte boundary, it should be
1596 // split.
1597 uint64_t EB_Real = (OffsetBase) / 64;
1598 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1599 if (EB_Real != EB_Imag)
1600 Hi = Lo;
1601 } else if (Size == 64) {
1602 // gcc passes <1 x double> in memory. :(
1603 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1604 return;
1605
1606 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001607 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001608 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1609 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1610 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001611 Current = Integer;
1612 else
1613 Current = SSE;
1614
1615 // If this type crosses an eightbyte boundary, it should be
1616 // split.
1617 if (OffsetBase && OffsetBase != 64)
1618 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001619 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001620 // Arguments of 256-bits are split into four eightbyte chunks. The
1621 // least significant one belongs to class SSE and all the others to class
1622 // SSEUP. The original Lo and Hi design considers that types can't be
1623 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1624 // This design isn't correct for 256-bits, but since there're no cases
1625 // where the upper parts would need to be inspected, avoid adding
1626 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001627 //
1628 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1629 // registers if they are "named", i.e. not part of the "..." of a
1630 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001631 Lo = SSE;
1632 Hi = SSEUp;
1633 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001634 return;
1635 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001636
Chris Lattnerd776fb12010-06-28 21:43:59 +00001637 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001638 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001639
Chris Lattner2b037972010-07-29 02:01:43 +00001640 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001641 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001642 if (Size <= 64)
1643 Current = Integer;
1644 else if (Size <= 128)
1645 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001646 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001647 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001648 else if (ET == getContext().DoubleTy ||
1649 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001650 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001651 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001652 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001653 Current = ComplexX87;
1654
1655 // If this complex type crosses an eightbyte boundary then it
1656 // should be split.
1657 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001658 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001659 if (Hi == NoClass && EB_Real != EB_Imag)
1660 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001661
Chris Lattnerd776fb12010-06-28 21:43:59 +00001662 return;
1663 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001664
Chris Lattner2b037972010-07-29 02:01:43 +00001665 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001666 // Arrays are treated like structures.
1667
Chris Lattner2b037972010-07-29 02:01:43 +00001668 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001669
1670 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001671 // than four eightbytes, ..., it has class MEMORY.
1672 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001673 return;
1674
1675 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1676 // fields, it has class MEMORY.
1677 //
1678 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001679 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001680 return;
1681
1682 // Otherwise implement simplified merge. We could be smarter about
1683 // this, but it isn't worth it and would be harder to verify.
1684 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001685 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001686 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001687
1688 // The only case a 256-bit wide vector could be used is when the array
1689 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1690 // to work for sizes wider than 128, early check and fallback to memory.
1691 if (Size > 128 && EltSize != 256)
1692 return;
1693
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001694 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1695 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001696 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001697 Lo = merge(Lo, FieldLo);
1698 Hi = merge(Hi, FieldHi);
1699 if (Lo == Memory || Hi == Memory)
1700 break;
1701 }
1702
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001703 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001704 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001705 return;
1706 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001707
Chris Lattnerd776fb12010-06-28 21:43:59 +00001708 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001709 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001710
1711 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001712 // than four eightbytes, ..., it has class MEMORY.
1713 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001714 return;
1715
Anders Carlsson20759ad2009-09-16 15:53:40 +00001716 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1717 // copy constructor or a non-trivial destructor, it is passed by invisible
1718 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001719 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001720 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001721
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001722 const RecordDecl *RD = RT->getDecl();
1723
1724 // Assume variable sized types are passed in memory.
1725 if (RD->hasFlexibleArrayMember())
1726 return;
1727
Chris Lattner2b037972010-07-29 02:01:43 +00001728 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001729
1730 // Reset Lo class, this will be recomputed.
1731 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001732
1733 // If this is a C++ record, classify the bases first.
1734 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001735 for (const auto &I : CXXRD->bases()) {
1736 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001737 "Unexpected base class!");
1738 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001739 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001740
1741 // Classify this field.
1742 //
1743 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1744 // single eightbyte, each is classified separately. Each eightbyte gets
1745 // initialized to class NO_CLASS.
1746 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001747 uint64_t Offset =
1748 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001749 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001750 Lo = merge(Lo, FieldLo);
1751 Hi = merge(Hi, FieldHi);
1752 if (Lo == Memory || Hi == Memory)
1753 break;
1754 }
1755 }
1756
1757 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001758 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001759 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001760 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001761 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1762 bool BitField = i->isBitField();
1763
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001764 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1765 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001766 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001767 // The only case a 256-bit wide vector could be used is when the struct
1768 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1769 // to work for sizes wider than 128, early check and fallback to memory.
1770 //
1771 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1772 Lo = Memory;
1773 return;
1774 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001775 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001776 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001777 Lo = Memory;
1778 return;
1779 }
1780
1781 // Classify this field.
1782 //
1783 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1784 // exceeds a single eightbyte, each is classified
1785 // separately. Each eightbyte gets initialized to class
1786 // NO_CLASS.
1787 Class FieldLo, FieldHi;
1788
1789 // Bit-fields require special handling, they do not force the
1790 // structure to be passed in memory even if unaligned, and
1791 // therefore they can straddle an eightbyte.
1792 if (BitField) {
1793 // Ignore padding bit-fields.
1794 if (i->isUnnamedBitfield())
1795 continue;
1796
1797 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001798 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001799
1800 uint64_t EB_Lo = Offset / 64;
1801 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001802
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001803 if (EB_Lo) {
1804 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1805 FieldLo = NoClass;
1806 FieldHi = Integer;
1807 } else {
1808 FieldLo = Integer;
1809 FieldHi = EB_Hi ? Integer : NoClass;
1810 }
1811 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001812 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001813 Lo = merge(Lo, FieldLo);
1814 Hi = merge(Hi, FieldHi);
1815 if (Lo == Memory || Hi == Memory)
1816 break;
1817 }
1818
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001819 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001820 }
1821}
1822
Chris Lattner22a931e2010-06-29 06:01:59 +00001823ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001824 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1825 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001826 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001827 // Treat an enum type as its underlying type.
1828 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1829 Ty = EnumTy->getDecl()->getIntegerType();
1830
1831 return (Ty->isPromotableIntegerType() ?
1832 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1833 }
1834
1835 return ABIArgInfo::getIndirect(0);
1836}
1837
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001838bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1839 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1840 uint64_t Size = getContext().getTypeSize(VecTy);
1841 unsigned LargestVector = HasAVX ? 256 : 128;
1842 if (Size <= 64 || Size > LargestVector)
1843 return true;
1844 }
1845
1846 return false;
1847}
1848
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001849ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1850 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001851 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1852 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001853 //
1854 // This assumption is optimistic, as there could be free registers available
1855 // when we need to pass this argument in memory, and LLVM could try to pass
1856 // the argument in the free register. This does not seem to happen currently,
1857 // but this code would be much safer if we could mark the argument with
1858 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001859 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001860 // Treat an enum type as its underlying type.
1861 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1862 Ty = EnumTy->getDecl()->getIntegerType();
1863
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001864 return (Ty->isPromotableIntegerType() ?
1865 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001866 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001867
Mark Lacey3825e832013-10-06 01:33:34 +00001868 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001869 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001870
Chris Lattner44c2b902011-05-22 23:21:23 +00001871 // Compute the byval alignment. We specify the alignment of the byval in all
1872 // cases so that the mid-level optimizer knows the alignment of the byval.
1873 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001874
1875 // Attempt to avoid passing indirect results using byval when possible. This
1876 // is important for good codegen.
1877 //
1878 // We do this by coercing the value into a scalar type which the backend can
1879 // handle naturally (i.e., without using byval).
1880 //
1881 // For simplicity, we currently only do this when we have exhausted all of the
1882 // free integer registers. Doing this when there are free integer registers
1883 // would require more care, as we would have to ensure that the coerced value
1884 // did not claim the unused register. That would require either reording the
1885 // arguments to the function (so that any subsequent inreg values came first),
1886 // or only doing this optimization when there were no following arguments that
1887 // might be inreg.
1888 //
1889 // We currently expect it to be rare (particularly in well written code) for
1890 // arguments to be passed on the stack when there are still free integer
1891 // registers available (this would typically imply large structs being passed
1892 // by value), so this seems like a fair tradeoff for now.
1893 //
1894 // We can revisit this if the backend grows support for 'onstack' parameter
1895 // attributes. See PR12193.
1896 if (freeIntRegs == 0) {
1897 uint64_t Size = getContext().getTypeSize(Ty);
1898
1899 // If this type fits in an eightbyte, coerce it into the matching integral
1900 // type, which will end up on the stack (with alignment 8).
1901 if (Align == 8 && Size <= 64)
1902 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1903 Size));
1904 }
1905
Chris Lattner44c2b902011-05-22 23:21:23 +00001906 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001907}
1908
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001909/// GetByteVectorType - The ABI specifies that a value should be passed in an
1910/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00001911/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001912llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001913 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001914
Chris Lattner9fa15c32010-07-29 05:02:29 +00001915 // Wrapper structs that just contain vectors are passed just like vectors,
1916 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001917 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00001918 while (STy && STy->getNumElements() == 1) {
1919 IRType = STy->getElementType(0);
1920 STy = dyn_cast<llvm::StructType>(IRType);
1921 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001922
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001923 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001924 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1925 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001926 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001927 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00001928 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1929 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1930 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1931 EltTy->isIntegerTy(128)))
1932 return VT;
1933 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001934
Chris Lattner4200fe42010-07-29 04:56:46 +00001935 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1936}
1937
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001938/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1939/// is known to either be off the end of the specified type or being in
1940/// alignment padding. The user type specified is known to be at most 128 bits
1941/// in size, and have passed through X86_64ABIInfo::classify with a successful
1942/// classification that put one of the two halves in the INTEGER class.
1943///
1944/// It is conservatively correct to return false.
1945static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1946 unsigned EndBit, ASTContext &Context) {
1947 // If the bytes being queried are off the end of the type, there is no user
1948 // data hiding here. This handles analysis of builtins, vectors and other
1949 // types that don't contain interesting padding.
1950 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1951 if (TySize <= StartBit)
1952 return true;
1953
Chris Lattner98076a22010-07-29 07:43:55 +00001954 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1955 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1956 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1957
1958 // Check each element to see if the element overlaps with the queried range.
1959 for (unsigned i = 0; i != NumElts; ++i) {
1960 // If the element is after the span we care about, then we're done..
1961 unsigned EltOffset = i*EltSize;
1962 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001963
Chris Lattner98076a22010-07-29 07:43:55 +00001964 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1965 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1966 EndBit-EltOffset, Context))
1967 return false;
1968 }
1969 // If it overlaps no elements, then it is safe to process as padding.
1970 return true;
1971 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001972
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001973 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1974 const RecordDecl *RD = RT->getDecl();
1975 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001976
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001977 // If this is a C++ record, check the bases first.
1978 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001979 for (const auto &I : CXXRD->bases()) {
1980 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001981 "Unexpected base class!");
1982 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001983 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001984
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001985 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001986 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001987 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001988
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001989 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00001990 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001991 EndBit-BaseOffset, Context))
1992 return false;
1993 }
1994 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001995
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001996 // Verify that no field has data that overlaps the region of interest. Yes
1997 // this could be sped up a lot by being smarter about queried fields,
1998 // however we're only looking at structs up to 16 bytes, so we don't care
1999 // much.
2000 unsigned idx = 0;
2001 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2002 i != e; ++i, ++idx) {
2003 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002004
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002005 // If we found a field after the region we care about, then we're done.
2006 if (FieldOffset >= EndBit) break;
2007
2008 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2009 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2010 Context))
2011 return false;
2012 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002013
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002014 // If nothing in this record overlapped the area of interest, then we're
2015 // clean.
2016 return true;
2017 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002018
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002019 return false;
2020}
2021
Chris Lattnere556a712010-07-29 18:39:32 +00002022/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2023/// float member at the specified offset. For example, {int,{float}} has a
2024/// float at offset 4. It is conservatively correct for this routine to return
2025/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002026static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002027 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002028 // Base case if we find a float.
2029 if (IROffset == 0 && IRType->isFloatTy())
2030 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002031
Chris Lattnere556a712010-07-29 18:39:32 +00002032 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002033 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002034 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2035 unsigned Elt = SL->getElementContainingOffset(IROffset);
2036 IROffset -= SL->getElementOffset(Elt);
2037 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2038 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002039
Chris Lattnere556a712010-07-29 18:39:32 +00002040 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002041 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2042 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002043 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2044 IROffset -= IROffset/EltSize*EltSize;
2045 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2046 }
2047
2048 return false;
2049}
2050
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002051
2052/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2053/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002054llvm::Type *X86_64ABIInfo::
2055GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002056 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002057 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002058 // pass as float if the last 4 bytes is just padding. This happens for
2059 // structs that contain 3 floats.
2060 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2061 SourceOffset*8+64, getContext()))
2062 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002063
Chris Lattnere556a712010-07-29 18:39:32 +00002064 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2065 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2066 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002067 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2068 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002069 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002070
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002071 return llvm::Type::getDoubleTy(getVMContext());
2072}
2073
2074
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002075/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2076/// an 8-byte GPR. This means that we either have a scalar or we are talking
2077/// about the high or low part of an up-to-16-byte struct. This routine picks
2078/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002079/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2080/// etc).
2081///
2082/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2083/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2084/// the 8-byte value references. PrefType may be null.
2085///
Alp Toker9907f082014-07-09 14:06:35 +00002086/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002087/// an offset into this that we're processing (which is always either 0 or 8).
2088///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002089llvm::Type *X86_64ABIInfo::
2090GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002091 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002092 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2093 // returning an 8-byte unit starting with it. See if we can safely use it.
2094 if (IROffset == 0) {
2095 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002096 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2097 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002098 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002099
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002100 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2101 // goodness in the source type is just tail padding. This is allowed to
2102 // kick in for struct {double,int} on the int, but not on
2103 // struct{double,int,int} because we wouldn't return the second int. We
2104 // have to do this analysis on the source type because we can't depend on
2105 // unions being lowered a specific way etc.
2106 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002107 IRType->isIntegerTy(32) ||
2108 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2109 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2110 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002111
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002112 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2113 SourceOffset*8+64, getContext()))
2114 return IRType;
2115 }
2116 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002117
Chris Lattner2192fe52011-07-18 04:24:23 +00002118 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002119 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002120 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002121 if (IROffset < SL->getSizeInBytes()) {
2122 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2123 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002124
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002125 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2126 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002127 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002128 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002129
Chris Lattner2192fe52011-07-18 04:24:23 +00002130 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002131 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002132 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002133 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002134 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2135 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002136 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002137
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002138 // Okay, we don't have any better idea of what to pass, so we pass this in an
2139 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002140 unsigned TySizeInBytes =
2141 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002142
Chris Lattner3f763422010-07-29 17:34:39 +00002143 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002144
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002145 // It is always safe to classify this as an integer type up to i64 that
2146 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002147 return llvm::IntegerType::get(getVMContext(),
2148 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002149}
2150
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002151
2152/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2153/// be used as elements of a two register pair to pass or return, return a
2154/// first class aggregate to represent them. For example, if the low part of
2155/// a by-value argument should be passed as i32* and the high part as float,
2156/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002157static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002158GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002159 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002160 // In order to correctly satisfy the ABI, we need to the high part to start
2161 // at offset 8. If the high and low parts we inferred are both 4-byte types
2162 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2163 // the second element at offset 8. Check for this:
2164 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2165 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002166 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002167 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002168
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002169 // To handle this, we have to increase the size of the low part so that the
2170 // second element will start at an 8 byte offset. We can't increase the size
2171 // of the second element because it might make us access off the end of the
2172 // struct.
2173 if (HiStart != 8) {
2174 // There are only two sorts of types the ABI generation code can produce for
2175 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2176 // Promote these to a larger type.
2177 if (Lo->isFloatTy())
2178 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2179 else {
2180 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2181 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2182 }
2183 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002184
Chris Lattnera5f58b02011-07-09 17:41:47 +00002185 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002186
2187
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002188 // Verify that the second element is at an 8-byte offset.
2189 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2190 "Invalid x86-64 argument pair!");
2191 return Result;
2192}
2193
Chris Lattner31faff52010-07-28 23:06:14 +00002194ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002195classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002196 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2197 // classification algorithm.
2198 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002199 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002200
2201 // Check some invariants.
2202 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002203 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2204
Craig Topper8a13c412014-05-21 05:09:00 +00002205 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002206 switch (Lo) {
2207 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002208 if (Hi == NoClass)
2209 return ABIArgInfo::getIgnore();
2210 // If the low part is just padding, it takes no register, leave ResType
2211 // null.
2212 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2213 "Unknown missing lo part");
2214 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002215
2216 case SSEUp:
2217 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002218 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002219
2220 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2221 // hidden argument.
2222 case Memory:
2223 return getIndirectReturnResult(RetTy);
2224
2225 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2226 // available register of the sequence %rax, %rdx is used.
2227 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002228 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002229
Chris Lattner1f3a0632010-07-29 21:42:50 +00002230 // If we have a sign or zero extended integer, make sure to return Extend
2231 // so that the parameter gets the right LLVM IR attributes.
2232 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2233 // Treat an enum type as its underlying type.
2234 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2235 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002236
Chris Lattner1f3a0632010-07-29 21:42:50 +00002237 if (RetTy->isIntegralOrEnumerationType() &&
2238 RetTy->isPromotableIntegerType())
2239 return ABIArgInfo::getExtend();
2240 }
Chris Lattner31faff52010-07-28 23:06:14 +00002241 break;
2242
2243 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2244 // available SSE register of the sequence %xmm0, %xmm1 is used.
2245 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002246 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002247 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002248
2249 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2250 // returned on the X87 stack in %st0 as 80-bit x87 number.
2251 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002252 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002253 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002254
2255 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2256 // part of the value is returned in %st0 and the imaginary part in
2257 // %st1.
2258 case ComplexX87:
2259 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002260 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002261 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002262 NULL);
2263 break;
2264 }
2265
Craig Topper8a13c412014-05-21 05:09:00 +00002266 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002267 switch (Hi) {
2268 // Memory was handled previously and X87 should
2269 // never occur as a hi class.
2270 case Memory:
2271 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002272 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002273
2274 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002275 case NoClass:
2276 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002277
Chris Lattner52b3c132010-09-01 00:20:33 +00002278 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002279 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002280 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2281 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002282 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002283 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002284 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002285 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2286 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002287 break;
2288
2289 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002290 // is passed in the next available eightbyte chunk if the last used
2291 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002292 //
Chris Lattner57540c52011-04-15 05:22:18 +00002293 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002294 case SSEUp:
2295 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002296 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002297 break;
2298
2299 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2300 // returned together with the previous X87 value in %st0.
2301 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002302 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002303 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002304 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002305 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002306 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002307 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002308 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2309 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002310 }
Chris Lattner31faff52010-07-28 23:06:14 +00002311 break;
2312 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002313
Chris Lattner52b3c132010-09-01 00:20:33 +00002314 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002315 // known to pass in the high eightbyte of the result. We do this by forming a
2316 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002317 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002318 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002319
Chris Lattner1f3a0632010-07-29 21:42:50 +00002320 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002321}
2322
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002323ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002324 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2325 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002326 const
2327{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002328 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002329 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002330
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002331 // Check some invariants.
2332 // FIXME: Enforce these by construction.
2333 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002334 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2335
2336 neededInt = 0;
2337 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002338 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002339 switch (Lo) {
2340 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002341 if (Hi == NoClass)
2342 return ABIArgInfo::getIgnore();
2343 // If the low part is just padding, it takes no register, leave ResType
2344 // null.
2345 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2346 "Unknown missing lo part");
2347 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002348
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002349 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2350 // on the stack.
2351 case Memory:
2352
2353 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2354 // COMPLEX_X87, it is passed in memory.
2355 case X87:
2356 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002357 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002358 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002359 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002360
2361 case SSEUp:
2362 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002363 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002364
2365 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2366 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2367 // and %r9 is used.
2368 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002369 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002370
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002371 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002372 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002373
2374 // If we have a sign or zero extended integer, make sure to return Extend
2375 // so that the parameter gets the right LLVM IR attributes.
2376 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2377 // Treat an enum type as its underlying type.
2378 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2379 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002380
Chris Lattner1f3a0632010-07-29 21:42:50 +00002381 if (Ty->isIntegralOrEnumerationType() &&
2382 Ty->isPromotableIntegerType())
2383 return ABIArgInfo::getExtend();
2384 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002385
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002386 break;
2387
2388 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2389 // available SSE register is used, the registers are taken in the
2390 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002391 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002392 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002393 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002394 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002395 break;
2396 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002397 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002398
Craig Topper8a13c412014-05-21 05:09:00 +00002399 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002400 switch (Hi) {
2401 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002402 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002403 // which is passed in memory.
2404 case Memory:
2405 case X87:
2406 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002407 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002408
2409 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002410
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002411 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002412 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002413 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002414 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002415
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002416 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2417 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002418 break;
2419
2420 // X87Up generally doesn't occur here (long double is passed in
2421 // memory), except in situations involving unions.
2422 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002423 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002424 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002425
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002426 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2427 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002428
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002429 ++neededSSE;
2430 break;
2431
2432 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2433 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002434 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002435 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002436 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002437 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002438 break;
2439 }
2440
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002441 // If a high part was specified, merge it together with the low part. It is
2442 // known to pass in the high eightbyte of the result. We do this by forming a
2443 // first class struct aggregate with the high and low part: {low, high}
2444 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002445 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002446
Chris Lattner1f3a0632010-07-29 21:42:50 +00002447 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002448}
2449
Chris Lattner22326a12010-07-29 02:31:05 +00002450void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002451
Reid Kleckner40ca9132014-05-13 22:05:45 +00002452 if (!getCXXABI().classifyReturnType(FI))
2453 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002454
2455 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002456 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002457
2458 // If the return value is indirect, then the hidden argument is consuming one
2459 // integer register.
2460 if (FI.getReturnInfo().isIndirect())
2461 --freeIntRegs;
2462
Eli Friedman96fd2642013-06-12 00:13:45 +00002463 bool isVariadic = FI.isVariadic();
2464 unsigned numRequiredArgs = 0;
2465 if (isVariadic)
2466 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2467
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002468 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2469 // get assigned (in left-to-right order) for passing as follows...
2470 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2471 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002472 bool isNamedArg = true;
2473 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002474 isNamedArg = (it - FI.arg_begin()) <
2475 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002476
Bill Wendling9987c0e2010-10-18 23:51:38 +00002477 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002478 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002479 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002480
2481 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2482 // eightbyte of an argument, the whole argument is passed on the
2483 // stack. If registers have already been assigned for some
2484 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002485 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002486 freeIntRegs -= neededInt;
2487 freeSSERegs -= neededSSE;
2488 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002489 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002490 }
2491 }
2492}
2493
2494static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2495 QualType Ty,
2496 CodeGenFunction &CGF) {
2497 llvm::Value *overflow_arg_area_p =
2498 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2499 llvm::Value *overflow_arg_area =
2500 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2501
2502 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2503 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002504 // It isn't stated explicitly in the standard, but in practice we use
2505 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002506 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2507 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002508 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002509 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002510 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002511 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2512 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002513 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002514 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002515 overflow_arg_area =
2516 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2517 overflow_arg_area->getType(),
2518 "overflow_arg_area.align");
2519 }
2520
2521 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002522 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002523 llvm::Value *Res =
2524 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002525 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002526
2527 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2528 // l->overflow_arg_area + sizeof(type).
2529 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2530 // an 8 byte boundary.
2531
2532 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002533 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002534 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002535 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2536 "overflow_arg_area.next");
2537 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2538
2539 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2540 return Res;
2541}
2542
2543llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2544 CodeGenFunction &CGF) const {
2545 // Assume that va_list type is correct; should be pointer to LLVM type:
2546 // struct {
2547 // i32 gp_offset;
2548 // i32 fp_offset;
2549 // i8* overflow_arg_area;
2550 // i8* reg_save_area;
2551 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002552 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002553
Chris Lattner9723d6c2010-03-11 18:19:55 +00002554 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002555 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2556 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002557
2558 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2559 // in the registers. If not go to step 7.
2560 if (!neededInt && !neededSSE)
2561 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2562
2563 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2564 // general purpose registers needed to pass type and num_fp to hold
2565 // the number of floating point registers needed.
2566
2567 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2568 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2569 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2570 //
2571 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2572 // register save space).
2573
Craig Topper8a13c412014-05-21 05:09:00 +00002574 llvm::Value *InRegs = nullptr;
2575 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2576 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002577 if (neededInt) {
2578 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2579 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002580 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2581 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002582 }
2583
2584 if (neededSSE) {
2585 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2586 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2587 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002588 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2589 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002590 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2591 }
2592
2593 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2594 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2595 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2596 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2597
2598 // Emit code to load the value if it was passed in registers.
2599
2600 CGF.EmitBlock(InRegBlock);
2601
2602 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2603 // an offset of l->gp_offset and/or l->fp_offset. This may require
2604 // copying to a temporary location in case the parameter is passed
2605 // in different register classes or requires an alignment greater
2606 // than 8 for general purpose registers and 16 for XMM registers.
2607 //
2608 // FIXME: This really results in shameful code when we end up needing to
2609 // collect arguments from different places; often what should result in a
2610 // simple assembling of a structure from scattered addresses has many more
2611 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002612 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002613 llvm::Value *RegAddr =
2614 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2615 "reg_save_area");
2616 if (neededInt && neededSSE) {
2617 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002618 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002619 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002620 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2621 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002622 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002623 llvm::Type *TyLo = ST->getElementType(0);
2624 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002625 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002626 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002627 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2628 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002629 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2630 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002631 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2632 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002633 llvm::Value *V =
2634 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2635 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2636 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2637 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2638
Owen Anderson170229f2009-07-14 23:10:40 +00002639 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002640 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002641 } else if (neededInt) {
2642 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2643 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002644 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002645
2646 // Copy to a temporary if necessary to ensure the appropriate alignment.
2647 std::pair<CharUnits, CharUnits> SizeAlign =
2648 CGF.getContext().getTypeInfoInChars(Ty);
2649 uint64_t TySize = SizeAlign.first.getQuantity();
2650 unsigned TyAlign = SizeAlign.second.getQuantity();
2651 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002652 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2653 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2654 RegAddr = Tmp;
2655 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002656 } else if (neededSSE == 1) {
2657 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2658 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2659 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002660 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002661 assert(neededSSE == 2 && "Invalid number of needed registers!");
2662 // SSE registers are spaced 16 bytes apart in the register save
2663 // area, we need to collect the two eightbytes together.
2664 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002665 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002666 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002667 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002668 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002669 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2670 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2671 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002672 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2673 DblPtrTy));
2674 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2675 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2676 DblPtrTy));
2677 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2678 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2679 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002680 }
2681
2682 // AMD64-ABI 3.5.7p5: Step 5. Set:
2683 // l->gp_offset = l->gp_offset + num_gp * 8
2684 // l->fp_offset = l->fp_offset + num_fp * 16.
2685 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002686 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002687 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2688 gp_offset_p);
2689 }
2690 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002691 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002692 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2693 fp_offset_p);
2694 }
2695 CGF.EmitBranch(ContBlock);
2696
2697 // Emit code to load the value if it was passed in memory.
2698
2699 CGF.EmitBlock(InMemBlock);
2700 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2701
2702 // Return the appropriate result.
2703
2704 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002705 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002706 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707 ResAddr->addIncoming(RegAddr, InRegBlock);
2708 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002709 return ResAddr;
2710}
2711
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002712ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002713
2714 if (Ty->isVoidType())
2715 return ABIArgInfo::getIgnore();
2716
2717 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2718 Ty = EnumTy->getDecl()->getIntegerType();
2719
2720 uint64_t Size = getContext().getTypeSize(Ty);
2721
Reid Kleckner9005f412014-05-02 00:51:20 +00002722 const RecordType *RT = Ty->getAs<RecordType>();
2723 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002724 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002725 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002726 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2727 }
2728
2729 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002730 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2731
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002732 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00002733 if (Size == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002734 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2735 Size));
Reid Kleckner9005f412014-05-02 00:51:20 +00002736 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002737
Reid Klecknerec87fec2014-05-02 01:17:12 +00002738 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00002739 // If the member pointer is represented by an LLVM int or ptr, pass it
2740 // directly.
2741 llvm::Type *LLTy = CGT.ConvertType(Ty);
2742 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2743 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00002744 }
2745
2746 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002747 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2748 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner9005f412014-05-02 00:51:20 +00002749 if (Size > 64 || !llvm::isPowerOf2_64(Size))
2750 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002751
Reid Kleckner9005f412014-05-02 00:51:20 +00002752 // Otherwise, coerce it to a small integer.
2753 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002754 }
2755
2756 if (Ty->isPromotableIntegerType())
2757 return ABIArgInfo::getExtend();
2758
2759 return ABIArgInfo::getDirect();
2760}
2761
2762void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002763 if (!getCXXABI().classifyReturnType(FI))
2764 FI.getReturnInfo() = classify(FI.getReturnType(), true);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002765
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002766 for (auto &I : FI.arguments())
2767 I.info = classify(I.type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002768}
2769
Chris Lattner04dc9572010-08-31 16:44:54 +00002770llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2771 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002772 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002773
Chris Lattner04dc9572010-08-31 16:44:54 +00002774 CGBuilderTy &Builder = CGF.Builder;
2775 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2776 "ap");
2777 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2778 llvm::Type *PTy =
2779 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2780 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2781
2782 uint64_t Offset =
2783 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2784 llvm::Value *NextAddr =
2785 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2786 "ap.next");
2787 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2788
2789 return AddrTyped;
2790}
Chris Lattner0cf24192010-06-28 20:05:43 +00002791
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002792namespace {
2793
Derek Schuffa2020962012-10-16 22:30:41 +00002794class NaClX86_64ABIInfo : public ABIInfo {
2795 public:
2796 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2797 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00002798 void computeInfo(CGFunctionInfo &FI) const override;
2799 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2800 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00002801 private:
2802 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2803 X86_64ABIInfo NInfo; // Used for everything else.
2804};
2805
2806class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2807 public:
2808 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2809 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2810};
2811
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002812}
2813
Derek Schuffa2020962012-10-16 22:30:41 +00002814void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2815 if (FI.getASTCallingConvention() == CC_PnaclCall)
2816 PInfo.computeInfo(FI);
2817 else
2818 NInfo.computeInfo(FI);
2819}
2820
2821llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2822 CodeGenFunction &CGF) const {
2823 // Always use the native convention; calling pnacl-style varargs functions
2824 // is unuspported.
2825 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2826}
2827
2828
John McCallea8d8bb2010-03-11 00:10:12 +00002829// PowerPC-32
2830
2831namespace {
2832class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2833public:
Chris Lattner2b037972010-07-29 02:01:43 +00002834 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002835
Craig Topper4f12f102014-03-12 06:41:41 +00002836 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00002837 // This is recovered from gcc output.
2838 return 1; // r1 is the dedicated stack pointer
2839 }
2840
2841 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002842 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00002843};
2844
2845}
2846
2847bool
2848PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2849 llvm::Value *Address) const {
2850 // This is calculated from the LLVM and GCC tables and verified
2851 // against gcc output. AFAIK all ABIs use the same encoding.
2852
2853 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002854
Chris Lattnerece04092012-02-07 00:39:47 +00002855 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002856 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2857 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2858 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2859
2860 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002861 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002862
2863 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002864 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002865
2866 // 64-76 are various 4-byte special-purpose registers:
2867 // 64: mq
2868 // 65: lr
2869 // 66: ctr
2870 // 67: ap
2871 // 68-75 cr0-7
2872 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002873 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002874
2875 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002876 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002877
2878 // 109: vrsave
2879 // 110: vscr
2880 // 111: spe_acc
2881 // 112: spefscr
2882 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002883 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002884
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002885 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002886}
2887
Roman Divackyd966e722012-05-09 18:22:46 +00002888// PowerPC-64
2889
2890namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002891/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2892class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2893
2894public:
2895 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2896
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002897 bool isPromotableTypeForABI(QualType Ty) const;
2898
2899 ABIArgInfo classifyReturnType(QualType RetTy) const;
2900 ABIArgInfo classifyArgumentType(QualType Ty) const;
2901
Bill Schmidt84d37792012-10-12 19:26:17 +00002902 // TODO: We can add more logic to computeInfo to improve performance.
2903 // Example: For aggregate arguments that fit in a register, we could
2904 // use getDirectInReg (as is done below for structs containing a single
2905 // floating-point value) to avoid pushing them to memory on function
2906 // entry. This would require changing the logic in PPCISelLowering
2907 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00002908 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002909 if (!getCXXABI().classifyReturnType(FI))
2910 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002911 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002912 // We rely on the default argument classification for the most part.
2913 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00002914 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002915 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00002916 if (T) {
2917 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidt179afae2013-07-23 22:15:57 +00002918 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002919 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002920 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00002921 continue;
2922 }
2923 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002924 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00002925 }
2926 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002927
Craig Topper4f12f102014-03-12 06:41:41 +00002928 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2929 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002930};
2931
2932class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2933public:
2934 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2935 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2936
Craig Topper4f12f102014-03-12 06:41:41 +00002937 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002938 // This is recovered from gcc output.
2939 return 1; // r1 is the dedicated stack pointer
2940 }
2941
2942 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002943 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002944};
2945
Roman Divackyd966e722012-05-09 18:22:46 +00002946class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2947public:
2948 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2949
Craig Topper4f12f102014-03-12 06:41:41 +00002950 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00002951 // This is recovered from gcc output.
2952 return 1; // r1 is the dedicated stack pointer
2953 }
2954
2955 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002956 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00002957};
2958
2959}
2960
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002961// Return true if the ABI requires Ty to be passed sign- or zero-
2962// extended to 64 bits.
2963bool
2964PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2965 // Treat an enum type as its underlying type.
2966 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2967 Ty = EnumTy->getDecl()->getIntegerType();
2968
2969 // Promotable integer types are required to be promoted by the ABI.
2970 if (Ty->isPromotableIntegerType())
2971 return true;
2972
2973 // In addition to the usual promotable integer types, we also need to
2974 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2975 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2976 switch (BT->getKind()) {
2977 case BuiltinType::Int:
2978 case BuiltinType::UInt:
2979 return true;
2980 default:
2981 break;
2982 }
2983
2984 return false;
2985}
2986
2987ABIArgInfo
2988PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00002989 if (Ty->isAnyComplexType())
2990 return ABIArgInfo::getDirect();
2991
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002992 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00002993 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002994 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002995
2996 return ABIArgInfo::getIndirect(0);
2997 }
2998
2999 return (isPromotableTypeForABI(Ty) ?
3000 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3001}
3002
3003ABIArgInfo
3004PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3005 if (RetTy->isVoidType())
3006 return ABIArgInfo::getIgnore();
3007
Bill Schmidta3d121c2012-12-17 04:20:17 +00003008 if (RetTy->isAnyComplexType())
3009 return ABIArgInfo::getDirect();
3010
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003011 if (isAggregateTypeForABI(RetTy))
3012 return ABIArgInfo::getIndirect(0);
3013
3014 return (isPromotableTypeForABI(RetTy) ?
3015 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3016}
3017
Bill Schmidt25cb3492012-10-03 19:18:57 +00003018// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3019llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3020 QualType Ty,
3021 CodeGenFunction &CGF) const {
3022 llvm::Type *BP = CGF.Int8PtrTy;
3023 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3024
3025 CGBuilderTy &Builder = CGF.Builder;
3026 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3027 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3028
Bill Schmidt924c4782013-01-14 17:45:36 +00003029 // Update the va_list pointer. The pointer should be bumped by the
3030 // size of the object. We can trust getTypeSize() except for a complex
3031 // type whose base type is smaller than a doubleword. For these, the
3032 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003033 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003034 QualType BaseTy;
3035 unsigned CplxBaseSize = 0;
3036
3037 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3038 BaseTy = CTy->getElementType();
3039 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3040 if (CplxBaseSize < 8)
3041 SizeInBytes = 16;
3042 }
3043
Bill Schmidt25cb3492012-10-03 19:18:57 +00003044 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3045 llvm::Value *NextAddr =
3046 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3047 "ap.next");
3048 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3049
Bill Schmidt924c4782013-01-14 17:45:36 +00003050 // If we have a complex type and the base type is smaller than 8 bytes,
3051 // the ABI calls for the real and imaginary parts to be right-adjusted
3052 // in separate doublewords. However, Clang expects us to produce a
3053 // pointer to a structure with the two parts packed tightly. So generate
3054 // loads of the real and imaginary parts relative to the va_list pointer,
3055 // and store them to a temporary structure.
3056 if (CplxBaseSize && CplxBaseSize < 8) {
3057 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3058 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003059 if (CGF.CGM.getDataLayout().isBigEndian()) {
3060 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3061 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3062 } else {
3063 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3064 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003065 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3066 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3067 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3068 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3069 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3070 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3071 "vacplx");
3072 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3073 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3074 Builder.CreateStore(Real, RealPtr, false);
3075 Builder.CreateStore(Imag, ImagPtr, false);
3076 return Ptr;
3077 }
3078
Bill Schmidt25cb3492012-10-03 19:18:57 +00003079 // If the argument is smaller than 8 bytes, it is right-adjusted in
3080 // its doubleword slot. Adjust the pointer to pick it up from the
3081 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003082 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003083 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3084 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3085 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3086 }
3087
3088 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3089 return Builder.CreateBitCast(Addr, PTy);
3090}
3091
3092static bool
3093PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3094 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003095 // This is calculated from the LLVM and GCC tables and verified
3096 // against gcc output. AFAIK all ABIs use the same encoding.
3097
3098 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3099
3100 llvm::IntegerType *i8 = CGF.Int8Ty;
3101 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3102 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3103 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3104
3105 // 0-31: r0-31, the 8-byte general-purpose registers
3106 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3107
3108 // 32-63: fp0-31, the 8-byte floating-point registers
3109 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3110
3111 // 64-76 are various 4-byte special-purpose registers:
3112 // 64: mq
3113 // 65: lr
3114 // 66: ctr
3115 // 67: ap
3116 // 68-75 cr0-7
3117 // 76: xer
3118 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3119
3120 // 77-108: v0-31, the 16-byte vector registers
3121 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3122
3123 // 109: vrsave
3124 // 110: vscr
3125 // 111: spe_acc
3126 // 112: spefscr
3127 // 113: sfp
3128 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3129
3130 return false;
3131}
John McCallea8d8bb2010-03-11 00:10:12 +00003132
Bill Schmidt25cb3492012-10-03 19:18:57 +00003133bool
3134PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3135 CodeGen::CodeGenFunction &CGF,
3136 llvm::Value *Address) const {
3137
3138 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3139}
3140
3141bool
3142PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3143 llvm::Value *Address) const {
3144
3145 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3146}
3147
Chris Lattner0cf24192010-06-28 20:05:43 +00003148//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003149// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003150//===----------------------------------------------------------------------===//
3151
3152namespace {
3153
Tim Northover573cbee2014-05-24 12:52:07 +00003154class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003155public:
3156 enum ABIKind {
3157 AAPCS = 0,
3158 DarwinPCS
3159 };
3160
3161private:
3162 ABIKind Kind;
3163
3164public:
Tim Northover573cbee2014-05-24 12:52:07 +00003165 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003166
3167private:
3168 ABIKind getABIKind() const { return Kind; }
3169 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3170
3171 ABIArgInfo classifyReturnType(QualType RetTy) const;
3172 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3173 bool &IsHA, unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003174 bool &IsSmallAggr, bool IsNamedArg) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00003175 bool isIllegalVectorType(QualType Ty) const;
3176
3177 virtual void computeInfo(CGFunctionInfo &FI) const {
3178 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3179 // number of SIMD and Floating-point registers allocated so far.
3180 // If the argument is an HFA or an HVA and there are sufficient unallocated
3181 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3182 // and Floating-point Registers (with one register per member of the HFA or
3183 // HVA). Otherwise, the NSRN is set to 8.
3184 unsigned AllocatedVFP = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003185
Tim Northovera2ee4332014-03-29 15:09:45 +00003186 // To correctly handle small aggregates, we need to keep track of the number
3187 // of GPRs allocated so far. If the small aggregate can't all fit into
3188 // registers, it will be on stack. We don't allow the aggregate to be
3189 // partially in registers.
3190 unsigned AllocatedGPR = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003191
3192 // Find the number of named arguments. Variadic arguments get special
3193 // treatment with the Darwin ABI.
3194 unsigned NumRequiredArgs = (FI.isVariadic() ?
3195 FI.getRequiredArgs().getNumRequiredArgs() :
3196 FI.arg_size());
3197
Reid Kleckner40ca9132014-05-13 22:05:45 +00003198 if (!getCXXABI().classifyReturnType(FI))
3199 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northovera2ee4332014-03-29 15:09:45 +00003200 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3201 it != ie; ++it) {
3202 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3203 bool IsHA = false, IsSmallAggr = false;
3204 const unsigned NumVFPs = 8;
3205 const unsigned NumGPRs = 8;
Bob Wilson373af732014-04-21 01:23:39 +00003206 bool IsNamedArg = ((it - FI.arg_begin()) <
3207 static_cast<signed>(NumRequiredArgs));
Tim Northovera2ee4332014-03-29 15:09:45 +00003208 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Bob Wilson373af732014-04-21 01:23:39 +00003209 AllocatedGPR, IsSmallAggr, IsNamedArg);
Tim Northover5ffc0922014-04-17 10:20:38 +00003210
3211 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3212 // as sequences of floats since they'll get "holes" inserted as
3213 // padding by the back end.
Tim Northover07f16242014-04-18 10:47:44 +00003214 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3215 getContext().getTypeAlign(it->type) < 64) {
3216 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3217 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
Tim Northover5ffc0922014-04-17 10:20:38 +00003218
Tim Northover07f16242014-04-18 10:47:44 +00003219 llvm::Type *CoerceTy = llvm::ArrayType::get(
3220 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3221 it->info = ABIArgInfo::getDirect(CoerceTy);
Tim Northover5ffc0922014-04-17 10:20:38 +00003222 }
3223
Tim Northovera2ee4332014-03-29 15:09:45 +00003224 // If we do not have enough VFP registers for the HA, any VFP registers
3225 // that are unallocated are marked as unavailable. To achieve this, we add
3226 // padding of (NumVFPs - PreAllocation) floats.
3227 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3228 llvm::Type *PaddingTy = llvm::ArrayType::get(
3229 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Tim Northover5ffc0922014-04-17 10:20:38 +00003230 it->info.setPaddingType(PaddingTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00003231 }
Tim Northover5ffc0922014-04-17 10:20:38 +00003232
Tim Northovera2ee4332014-03-29 15:09:45 +00003233 // If we do not have enough GPRs for the small aggregate, any GPR regs
3234 // that are unallocated are marked as unavailable.
3235 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3236 llvm::Type *PaddingTy = llvm::ArrayType::get(
3237 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3238 it->info =
3239 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3240 }
3241 }
3242 }
3243
3244 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3245 CodeGenFunction &CGF) const;
3246
3247 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3248 CodeGenFunction &CGF) const;
3249
3250 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3251 CodeGenFunction &CGF) const {
3252 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3253 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3254 }
3255};
3256
Tim Northover573cbee2014-05-24 12:52:07 +00003257class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003258public:
Tim Northover573cbee2014-05-24 12:52:07 +00003259 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3260 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003261
3262 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3263 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3264 }
3265
3266 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3267
3268 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3269};
3270}
3271
3272static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3273 ASTContext &Context,
Craig Topper8a13c412014-05-21 05:09:00 +00003274 uint64_t *HAMembers = nullptr);
Tim Northovera2ee4332014-03-29 15:09:45 +00003275
Tim Northover573cbee2014-05-24 12:52:07 +00003276ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3277 unsigned &AllocatedVFP,
3278 bool &IsHA,
3279 unsigned &AllocatedGPR,
3280 bool &IsSmallAggr,
3281 bool IsNamedArg) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003282 // Handle illegal vector types here.
3283 if (isIllegalVectorType(Ty)) {
3284 uint64_t Size = getContext().getTypeSize(Ty);
3285 if (Size <= 32) {
3286 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3287 AllocatedGPR++;
3288 return ABIArgInfo::getDirect(ResType);
3289 }
3290 if (Size == 64) {
3291 llvm::Type *ResType =
3292 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3293 AllocatedVFP++;
3294 return ABIArgInfo::getDirect(ResType);
3295 }
3296 if (Size == 128) {
3297 llvm::Type *ResType =
3298 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3299 AllocatedVFP++;
3300 return ABIArgInfo::getDirect(ResType);
3301 }
3302 AllocatedGPR++;
3303 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3304 }
3305 if (Ty->isVectorType())
3306 // Size of a legal vector should be either 64 or 128.
3307 AllocatedVFP++;
3308 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3309 if (BT->getKind() == BuiltinType::Half ||
3310 BT->getKind() == BuiltinType::Float ||
3311 BT->getKind() == BuiltinType::Double ||
3312 BT->getKind() == BuiltinType::LongDouble)
3313 AllocatedVFP++;
3314 }
3315
3316 if (!isAggregateTypeForABI(Ty)) {
3317 // Treat an enum type as its underlying type.
3318 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3319 Ty = EnumTy->getDecl()->getIntegerType();
3320
3321 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003322 unsigned Alignment = getContext().getTypeAlign(Ty);
3323 if (!isDarwinPCS() && Alignment > 64)
3324 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3325
Tim Northovera2ee4332014-03-29 15:09:45 +00003326 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3327 AllocatedGPR += RegsNeeded;
3328 }
3329 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3330 ? ABIArgInfo::getExtend()
3331 : ABIArgInfo::getDirect());
3332 }
3333
3334 // Structures with either a non-trivial destructor or a non-trivial
3335 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003336 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003337 AllocatedGPR++;
Reid Kleckner40ca9132014-05-13 22:05:45 +00003338 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3339 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003340 }
3341
3342 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3343 // elsewhere for GNU compatibility.
3344 if (isEmptyRecord(getContext(), Ty, true)) {
3345 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3346 return ABIArgInfo::getIgnore();
3347
3348 ++AllocatedGPR;
3349 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3350 }
3351
3352 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003353 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003354 uint64_t Members = 0;
3355 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003356 IsHA = true;
Bob Wilson373af732014-04-21 01:23:39 +00003357 if (!IsNamedArg && isDarwinPCS()) {
3358 // With the Darwin ABI, variadic arguments are always passed on the stack
3359 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3360 uint64_t Size = getContext().getTypeSize(Ty);
3361 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3362 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3363 }
3364 AllocatedVFP += Members;
Tim Northovera2ee4332014-03-29 15:09:45 +00003365 return ABIArgInfo::getExpand();
3366 }
3367
3368 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3369 uint64_t Size = getContext().getTypeSize(Ty);
3370 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003371 unsigned Alignment = getContext().getTypeAlign(Ty);
3372 if (!isDarwinPCS() && Alignment > 64)
3373 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3374
Tim Northovera2ee4332014-03-29 15:09:45 +00003375 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3376 AllocatedGPR += Size / 64;
3377 IsSmallAggr = true;
3378 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3379 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003380 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003381 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3382 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3383 }
3384 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3385 }
3386
3387 AllocatedGPR++;
3388 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3389}
3390
Tim Northover573cbee2014-05-24 12:52:07 +00003391ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003392 if (RetTy->isVoidType())
3393 return ABIArgInfo::getIgnore();
3394
3395 // Large vector types should be returned via memory.
3396 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3397 return ABIArgInfo::getIndirect(0);
3398
3399 if (!isAggregateTypeForABI(RetTy)) {
3400 // Treat an enum type as its underlying type.
3401 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3402 RetTy = EnumTy->getDecl()->getIntegerType();
3403
Tim Northover4dab6982014-04-18 13:46:08 +00003404 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3405 ? ABIArgInfo::getExtend()
3406 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003407 }
3408
Tim Northovera2ee4332014-03-29 15:09:45 +00003409 if (isEmptyRecord(getContext(), RetTy, true))
3410 return ABIArgInfo::getIgnore();
3411
Craig Topper8a13c412014-05-21 05:09:00 +00003412 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003413 if (isHomogeneousAggregate(RetTy, Base, getContext()))
3414 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3415 return ABIArgInfo::getDirect();
3416
3417 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3418 uint64_t Size = getContext().getTypeSize(RetTy);
3419 if (Size <= 128) {
3420 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3421 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3422 }
3423
3424 return ABIArgInfo::getIndirect(0);
3425}
3426
Tim Northover573cbee2014-05-24 12:52:07 +00003427/// isIllegalVectorType - check whether the vector type is legal for AArch64.
3428bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003429 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3430 // Check whether VT is legal.
3431 unsigned NumElements = VT->getNumElements();
3432 uint64_t Size = getContext().getTypeSize(VT);
3433 // NumElements should be power of 2 between 1 and 16.
3434 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3435 return true;
3436 return Size != 64 && (Size != 128 || NumElements == 1);
3437 }
3438 return false;
3439}
3440
3441static llvm::Value *EmitAArch64VAArg(llvm::Value *VAListAddr, QualType Ty,
3442 int AllocatedGPR, int AllocatedVFP,
3443 bool IsIndirect, CodeGenFunction &CGF) {
3444 // The AArch64 va_list type and handling is specified in the Procedure Call
3445 // Standard, section B.4:
3446 //
3447 // struct {
3448 // void *__stack;
3449 // void *__gr_top;
3450 // void *__vr_top;
3451 // int __gr_offs;
3452 // int __vr_offs;
3453 // };
3454
3455 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3456 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3457 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3458 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3459 auto &Ctx = CGF.getContext();
3460
Craig Topper8a13c412014-05-21 05:09:00 +00003461 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003462 int reg_top_index;
3463 int RegSize;
3464 if (AllocatedGPR) {
3465 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
3466 // 3 is the field number of __gr_offs
3467 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3468 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3469 reg_top_index = 1; // field number for __gr_top
3470 RegSize = 8 * AllocatedGPR;
3471 } else {
3472 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
3473 // 4 is the field number of __vr_offs.
3474 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3475 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3476 reg_top_index = 2; // field number for __vr_top
3477 RegSize = 16 * AllocatedVFP;
3478 }
3479
3480 //=======================================
3481 // Find out where argument was passed
3482 //=======================================
3483
3484 // If reg_offs >= 0 we're already using the stack for this type of
3485 // argument. We don't want to keep updating reg_offs (in case it overflows,
3486 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3487 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00003488 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003489 UsingStack = CGF.Builder.CreateICmpSGE(
3490 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
3491
3492 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3493
3494 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00003495 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00003496 CGF.EmitBlock(MaybeRegBlock);
3497
3498 // Integer arguments may need to correct register alignment (for example a
3499 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3500 // align __gr_offs to calculate the potential address.
3501 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3502 int Align = Ctx.getTypeAlign(Ty) / 8;
3503
3504 reg_offs = CGF.Builder.CreateAdd(
3505 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3506 "align_regoffs");
3507 reg_offs = CGF.Builder.CreateAnd(
3508 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3509 "aligned_regoffs");
3510 }
3511
3512 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00003513 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003514 NewOffset = CGF.Builder.CreateAdd(
3515 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
3516 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3517
3518 // Now we're in a position to decide whether this argument really was in
3519 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00003520 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003521 InRegs = CGF.Builder.CreateICmpSLE(
3522 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
3523
3524 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3525
3526 //=======================================
3527 // Argument was in registers
3528 //=======================================
3529
3530 // Now we emit the code for if the argument was originally passed in
3531 // registers. First start the appropriate block:
3532 CGF.EmitBlock(InRegBlock);
3533
Craig Topper8a13c412014-05-21 05:09:00 +00003534 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003535 reg_top_p =
3536 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3537 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3538 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00003539 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003540 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
3541
3542 if (IsIndirect) {
3543 // If it's been passed indirectly (actually a struct), whatever we find from
3544 // stored registers or on the stack will actually be a struct **.
3545 MemTy = llvm::PointerType::getUnqual(MemTy);
3546 }
3547
Craig Topper8a13c412014-05-21 05:09:00 +00003548 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003549 uint64_t NumMembers;
James Molloy467be602014-05-07 14:45:55 +00003550 bool IsHFA = isHomogeneousAggregate(Ty, Base, Ctx, &NumMembers);
3551 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003552 // Homogeneous aggregates passed in registers will have their elements split
3553 // and stored 16-bytes apart regardless of size (they're notionally in qN,
3554 // qN+1, ...). We reload and store into a temporary local variable
3555 // contiguously.
3556 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
3557 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
3558 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
3559 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
3560 int Offset = 0;
3561
3562 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
3563 Offset = 16 - Ctx.getTypeSize(Base) / 8;
3564 for (unsigned i = 0; i < NumMembers; ++i) {
3565 llvm::Value *BaseOffset =
3566 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
3567 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
3568 LoadAddr = CGF.Builder.CreateBitCast(
3569 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
3570 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
3571
3572 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
3573 CGF.Builder.CreateStore(Elem, StoreAddr);
3574 }
3575
3576 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
3577 } else {
3578 // Otherwise the object is contiguous in memory
3579 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00003580 if (CGF.CGM.getDataLayout().isBigEndian() &&
3581 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00003582 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
3583 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
3584 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
3585
3586 BaseAddr = CGF.Builder.CreateAdd(
3587 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3588
3589 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
3590 }
3591
3592 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
3593 }
3594
3595 CGF.EmitBranch(ContBlock);
3596
3597 //=======================================
3598 // Argument was on the stack
3599 //=======================================
3600 CGF.EmitBlock(OnStackBlock);
3601
Craig Topper8a13c412014-05-21 05:09:00 +00003602 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003603 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
3604 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
3605
3606 // Again, stack arguments may need realigmnent. In this case both integer and
3607 // floating-point ones might be affected.
3608 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3609 int Align = Ctx.getTypeAlign(Ty) / 8;
3610
3611 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3612
3613 OnStackAddr = CGF.Builder.CreateAdd(
3614 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
3615 "align_stack");
3616 OnStackAddr = CGF.Builder.CreateAnd(
3617 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
3618 "align_stack");
3619
3620 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3621 }
3622
3623 uint64_t StackSize;
3624 if (IsIndirect)
3625 StackSize = 8;
3626 else
3627 StackSize = Ctx.getTypeSize(Ty) / 8;
3628
3629 // All stack slots are 8 bytes
3630 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
3631
3632 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
3633 llvm::Value *NewStack =
3634 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
3635
3636 // Write the new value of __stack for the next call to va_arg
3637 CGF.Builder.CreateStore(NewStack, stack_p);
3638
3639 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
3640 Ctx.getTypeSize(Ty) < 64) {
3641 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
3642 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3643
3644 OnStackAddr = CGF.Builder.CreateAdd(
3645 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3646
3647 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3648 }
3649
3650 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
3651
3652 CGF.EmitBranch(ContBlock);
3653
3654 //=======================================
3655 // Tidy up
3656 //=======================================
3657 CGF.EmitBlock(ContBlock);
3658
3659 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
3660 ResAddr->addIncoming(RegAddr, InRegBlock);
3661 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
3662
3663 if (IsIndirect)
3664 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
3665
3666 return ResAddr;
3667}
3668
Tim Northover573cbee2014-05-24 12:52:07 +00003669llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00003670 CodeGenFunction &CGF) const {
3671
3672 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
3673 bool IsHA = false, IsSmallAggr = false;
Bob Wilson373af732014-04-21 01:23:39 +00003674 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
3675 IsSmallAggr, false /*IsNamedArg*/);
Tim Northovera2ee4332014-03-29 15:09:45 +00003676
3677 return EmitAArch64VAArg(VAListAddr, Ty, AllocatedGPR, AllocatedVFP,
3678 AI.isIndirect(), CGF);
3679}
3680
Tim Northover573cbee2014-05-24 12:52:07 +00003681llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00003682 CodeGenFunction &CGF) const {
3683 // We do not support va_arg for aggregates or illegal vector types.
3684 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
3685 // other cases.
3686 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00003687 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003688
3689 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
3690 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
3691
Craig Topper8a13c412014-05-21 05:09:00 +00003692 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003693 bool isHA = isHomogeneousAggregate(Ty, Base, getContext());
3694
3695 bool isIndirect = false;
3696 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
3697 // be passed indirectly.
3698 if (Size > 16 && !isHA) {
3699 isIndirect = true;
3700 Size = 8;
3701 Align = 8;
3702 }
3703
3704 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
3705 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
3706
3707 CGBuilderTy &Builder = CGF.Builder;
3708 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3709 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3710
3711 if (isEmptyRecord(getContext(), Ty, true)) {
3712 // These are ignored for parameter passing purposes.
3713 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3714 return Builder.CreateBitCast(Addr, PTy);
3715 }
3716
3717 const uint64_t MinABIAlign = 8;
3718 if (Align > MinABIAlign) {
3719 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
3720 Addr = Builder.CreateGEP(Addr, Offset);
3721 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3722 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
3723 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
3724 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
3725 }
3726
3727 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
3728 llvm::Value *NextAddr = Builder.CreateGEP(
3729 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
3730 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3731
3732 if (isIndirect)
3733 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
3734 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3735 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3736
3737 return AddrTyped;
3738}
3739
3740//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003741// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00003742//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003743
3744namespace {
3745
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003746class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003747public:
3748 enum ABIKind {
3749 APCS = 0,
3750 AAPCS = 1,
3751 AAPCS_VFP
3752 };
3753
3754private:
3755 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00003756 mutable int VFPRegs[16];
3757 const unsigned NumVFPs;
3758 const unsigned NumGPRs;
3759 mutable unsigned AllocatedGPRs;
3760 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003761
3762public:
Oliver Stannard405bded2014-02-11 09:25:50 +00003763 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
3764 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00003765 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003766 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00003767 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003768
John McCall3480ef22011-08-30 01:42:09 +00003769 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003770 switch (getTarget().getTriple().getEnvironment()) {
3771 case llvm::Triple::Android:
3772 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003773 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003774 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00003775 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003776 return true;
3777 default:
3778 return false;
3779 }
John McCall3480ef22011-08-30 01:42:09 +00003780 }
3781
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003782 bool isEABIHF() const {
3783 switch (getTarget().getTriple().getEnvironment()) {
3784 case llvm::Triple::EABIHF:
3785 case llvm::Triple::GNUEABIHF:
3786 return true;
3787 default:
3788 return false;
3789 }
3790 }
3791
Daniel Dunbar020daa92009-09-12 01:00:39 +00003792 ABIKind getABIKind() const { return Kind; }
3793
Tim Northovera484bc02013-10-01 14:34:25 +00003794private:
Amara Emerson9dc78782014-01-28 10:56:36 +00003795 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00003796 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00003797 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00003798 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003799
Craig Topper4f12f102014-03-12 06:41:41 +00003800 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003801
Craig Topper4f12f102014-03-12 06:41:41 +00003802 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3803 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00003804
3805 llvm::CallingConv::ID getLLVMDefaultCC() const;
3806 llvm::CallingConv::ID getABIDefaultCC() const;
3807 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003808
3809 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
3810 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
3811 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003812};
3813
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003814class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3815public:
Chris Lattner2b037972010-07-29 02:01:43 +00003816 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3817 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00003818
John McCall3480ef22011-08-30 01:42:09 +00003819 const ARMABIInfo &getABIInfo() const {
3820 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3821 }
3822
Craig Topper4f12f102014-03-12 06:41:41 +00003823 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00003824 return 13;
3825 }
Roman Divackyc1617352011-05-18 19:36:54 +00003826
Craig Topper4f12f102014-03-12 06:41:41 +00003827 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00003828 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3829 }
3830
Roman Divackyc1617352011-05-18 19:36:54 +00003831 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003832 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00003833 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00003834
3835 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00003836 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00003837 return false;
3838 }
John McCall3480ef22011-08-30 01:42:09 +00003839
Craig Topper4f12f102014-03-12 06:41:41 +00003840 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00003841 if (getABIInfo().isEABI()) return 88;
3842 return TargetCodeGenInfo::getSizeOfUnwindException();
3843 }
Tim Northovera484bc02013-10-01 14:34:25 +00003844
3845 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00003846 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00003847 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3848 if (!FD)
3849 return;
3850
3851 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3852 if (!Attr)
3853 return;
3854
3855 const char *Kind;
3856 switch (Attr->getInterrupt()) {
3857 case ARMInterruptAttr::Generic: Kind = ""; break;
3858 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3859 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3860 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3861 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3862 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3863 }
3864
3865 llvm::Function *Fn = cast<llvm::Function>(GV);
3866
3867 Fn->addFnAttr("interrupt", Kind);
3868
3869 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3870 return;
3871
3872 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3873 // however this is not necessarily true on taking any interrupt. Instruct
3874 // the backend to perform a realignment as part of the function prologue.
3875 llvm::AttrBuilder B;
3876 B.addStackAlignmentAttr(8);
3877 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3878 llvm::AttributeSet::get(CGM.getLLVMContext(),
3879 llvm::AttributeSet::FunctionIndex,
3880 B));
3881 }
3882
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003883};
3884
Daniel Dunbard59655c2009-09-12 00:59:49 +00003885}
3886
Chris Lattner22326a12010-07-29 02:31:05 +00003887void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003888 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00003889 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00003890 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3891 // VFP registers of the appropriate type unallocated then the argument is
3892 // allocated to the lowest-numbered sequence of such registers.
3893 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3894 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00003895 resetAllocatedRegs();
3896
Reid Kleckner40ca9132014-05-13 22:05:45 +00003897 if (getCXXABI().classifyReturnType(FI)) {
3898 if (FI.getReturnInfo().isIndirect())
3899 markAllocatedGPRs(1, 1);
3900 } else {
3901 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
3902 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003903 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00003904 unsigned PreAllocationVFPs = AllocatedVFPs;
3905 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00003906 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00003907 // 6.1.2.3 There is one VFP co-processor register class using registers
3908 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00003909 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00003910
3911 // If we have allocated some arguments onto the stack (due to running
3912 // out of VFP registers), we cannot split an argument between GPRs and
3913 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00003914 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00003915 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
3916 // unusable anyway.
3917 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
3918 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs && StackUsed) {
3919 llvm::Type *PaddingTy = llvm::ArrayType::get(
3920 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00003921 if (I.info.canHaveCoerceToType()) {
3922 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */, 0 /* offset */,
3923 PaddingTy);
3924 } else {
3925 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
3926 PaddingTy);
3927 }
Manman Ren2a523d82012-10-30 23:21:41 +00003928 }
3929 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003930
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003931 // Always honor user-specified calling convention.
3932 if (FI.getCallingConvention() != llvm::CallingConv::C)
3933 return;
3934
John McCall882987f2013-02-28 19:01:20 +00003935 llvm::CallingConv::ID cc = getRuntimeCC();
3936 if (cc != llvm::CallingConv::C)
3937 FI.setEffectiveCallingConvention(cc);
3938}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003939
John McCall882987f2013-02-28 19:01:20 +00003940/// Return the default calling convention that LLVM will use.
3941llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3942 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003943 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00003944 return llvm::CallingConv::ARM_AAPCS_VFP;
3945 else if (isEABI())
3946 return llvm::CallingConv::ARM_AAPCS;
3947 else
3948 return llvm::CallingConv::ARM_APCS;
3949}
3950
3951/// Return the calling convention that our ABI would like us to use
3952/// as the C calling convention.
3953llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003954 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003955 case APCS: return llvm::CallingConv::ARM_APCS;
3956 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3957 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003958 }
John McCall882987f2013-02-28 19:01:20 +00003959 llvm_unreachable("bad ABI kind");
3960}
3961
3962void ARMABIInfo::setRuntimeCC() {
3963 assert(getRuntimeCC() == llvm::CallingConv::C);
3964
3965 // Don't muddy up the IR with a ton of explicit annotations if
3966 // they'd just match what LLVM will infer from the triple.
3967 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3968 if (abiCC != getLLVMDefaultCC())
3969 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003970}
3971
Bob Wilsone826a2a2011-08-03 05:58:22 +00003972/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3973/// aggregate. If HAMembers is non-null, the number of base elements
3974/// contained in the type is returned through it; this is used for the
3975/// recursive calls that check aggregate component types.
3976static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
Tim Northovera2ee4332014-03-29 15:09:45 +00003977 ASTContext &Context, uint64_t *HAMembers) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003978 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003979 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3980 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3981 return false;
3982 Members *= AT->getSize().getZExtValue();
3983 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3984 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003985 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003986 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003987
Bob Wilsone826a2a2011-08-03 05:58:22 +00003988 Members = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003989 for (const auto *FD : RD->fields()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00003990 uint64_t FldMembers;
3991 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3992 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003993
3994 Members = (RD->isUnion() ?
3995 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003996 }
3997 } else {
3998 Members = 1;
3999 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4000 Members = 2;
4001 Ty = CT->getElementType();
4002 }
4003
4004 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4005 // double, or 64-bit or 128-bit vectors.
4006 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4007 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00004008 BT->getKind() != BuiltinType::Double &&
4009 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00004010 return false;
4011 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4012 unsigned VecSize = Context.getTypeSize(VT);
4013 if (VecSize != 64 && VecSize != 128)
4014 return false;
4015 } else {
4016 return false;
4017 }
4018
4019 // The base type must be the same for all members. Vector types of the
4020 // same total size are treated as being equivalent here.
4021 const Type *TyPtr = Ty.getTypePtr();
4022 if (!Base)
4023 Base = TyPtr;
Oliver Stannard5e8558f2014-02-07 11:25:57 +00004024
4025 if (Base != TyPtr) {
4026 // Homogeneous aggregates are defined as containing members with the
4027 // same machine type. There are two cases in which two members have
4028 // different TypePtrs but the same machine type:
4029
4030 // 1) Vectors of the same length, regardless of the type and number
4031 // of their members.
4032 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
4033 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4034
4035 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
4036 // machine type. This is not the case for the 64-bit AAPCS.
4037 const bool SameSizeDoubles =
4038 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
4039 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
4040 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
4041 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
4042 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4043
4044 if (!SameLengthVectors && !SameSizeDoubles)
4045 return false;
4046 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004047 }
4048
4049 // Homogeneous Aggregates can have at most 4 members of the base type.
4050 if (HAMembers)
4051 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004052
4053 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00004054}
4055
Manman Renb505d332012-10-31 19:02:26 +00004056/// markAllocatedVFPs - update VFPRegs according to the alignment and
4057/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004058void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4059 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004060 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004061 if (AllocatedVFPs >= 16) {
4062 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4063 // the stack.
4064 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004065 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004066 }
Manman Renb505d332012-10-31 19:02:26 +00004067 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4068 // VFP registers of the appropriate type unallocated then the argument is
4069 // allocated to the lowest-numbered sequence of such registers.
4070 for (unsigned I = 0; I < 16; I += Alignment) {
4071 bool FoundSlot = true;
4072 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4073 if (J >= 16 || VFPRegs[J]) {
4074 FoundSlot = false;
4075 break;
4076 }
4077 if (FoundSlot) {
4078 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4079 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004080 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004081 return;
4082 }
4083 }
4084 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4085 // unallocated are marked as unavailable.
4086 for (unsigned I = 0; I < 16; I++)
4087 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004088 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004089}
4090
Oliver Stannard405bded2014-02-11 09:25:50 +00004091/// Update AllocatedGPRs to record the number of general purpose registers
4092/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4093/// this represents arguments being stored on the stack.
4094void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004095 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004096 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4097
4098 if (Alignment == 2 && AllocatedGPRs & 0x1)
4099 AllocatedGPRs += 1;
4100
4101 AllocatedGPRs += NumRequired;
4102}
4103
4104void ARMABIInfo::resetAllocatedRegs(void) const {
4105 AllocatedGPRs = 0;
4106 AllocatedVFPs = 0;
4107 for (unsigned i = 0; i < NumVFPs; ++i)
4108 VFPRegs[i] = 0;
4109}
4110
James Molloy6f244b62014-05-09 16:21:39 +00004111ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004112 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004113 // We update number of allocated VFPs according to
4114 // 6.1.2.1 The following argument types are VFP CPRCs:
4115 // A single-precision floating-point type (including promoted
4116 // half-precision types); A double-precision floating-point type;
4117 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4118 // with a Base Type of a single- or double-precision floating-point type,
4119 // 64-bit containerized vectors or 128-bit containerized vectors with one
4120 // to four Elements.
4121
Manman Renfef9e312012-10-16 19:18:39 +00004122 // Handle illegal vector types here.
4123 if (isIllegalVectorType(Ty)) {
4124 uint64_t Size = getContext().getTypeSize(Ty);
4125 if (Size <= 32) {
4126 llvm::Type *ResType =
4127 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004128 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004129 return ABIArgInfo::getDirect(ResType);
4130 }
4131 if (Size == 64) {
4132 llvm::Type *ResType = llvm::VectorType::get(
4133 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004134 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4135 markAllocatedGPRs(2, 2);
4136 } else {
4137 markAllocatedVFPs(2, 2);
4138 IsCPRC = true;
4139 }
Manman Renfef9e312012-10-16 19:18:39 +00004140 return ABIArgInfo::getDirect(ResType);
4141 }
4142 if (Size == 128) {
4143 llvm::Type *ResType = llvm::VectorType::get(
4144 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004145 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4146 markAllocatedGPRs(2, 4);
4147 } else {
4148 markAllocatedVFPs(4, 4);
4149 IsCPRC = true;
4150 }
Manman Renfef9e312012-10-16 19:18:39 +00004151 return ABIArgInfo::getDirect(ResType);
4152 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004153 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004154 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4155 }
Manman Renb505d332012-10-31 19:02:26 +00004156 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004157 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4158 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4159 uint64_t Size = getContext().getTypeSize(VT);
4160 // Size of a legal vector should be power of 2 and above 64.
4161 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4162 IsCPRC = true;
4163 }
Manman Ren2a523d82012-10-30 23:21:41 +00004164 }
Manman Renb505d332012-10-31 19:02:26 +00004165 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004166 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4167 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4168 if (BT->getKind() == BuiltinType::Half ||
4169 BT->getKind() == BuiltinType::Float) {
4170 markAllocatedVFPs(1, 1);
4171 IsCPRC = true;
4172 }
4173 if (BT->getKind() == BuiltinType::Double ||
4174 BT->getKind() == BuiltinType::LongDouble) {
4175 markAllocatedVFPs(2, 2);
4176 IsCPRC = true;
4177 }
4178 }
Manman Ren2a523d82012-10-30 23:21:41 +00004179 }
Manman Renfef9e312012-10-16 19:18:39 +00004180
John McCalla1dee5302010-08-22 10:59:02 +00004181 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004182 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004183 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004184 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004185 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004186
Oliver Stannard405bded2014-02-11 09:25:50 +00004187 unsigned Size = getContext().getTypeSize(Ty);
4188 if (!IsCPRC)
4189 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00004190 return (Ty->isPromotableIntegerType() ?
4191 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004192 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004193
Oliver Stannard405bded2014-02-11 09:25:50 +00004194 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4195 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004196 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004197 }
Tim Northover1060eae2013-06-21 22:49:34 +00004198
Daniel Dunbar09d33622009-09-14 21:54:03 +00004199 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004200 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004201 return ABIArgInfo::getIgnore();
4202
Amara Emerson9dc78782014-01-28 10:56:36 +00004203 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
Manman Ren2a523d82012-10-30 23:21:41 +00004204 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4205 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004206 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004207 uint64_t Members = 0;
4208 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004209 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004210 // Base can be a floating-point or a vector.
4211 if (Base->isVectorType()) {
4212 // ElementSize is in number of floats.
4213 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004214 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004215 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004216 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004217 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004218 else {
4219 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4220 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004221 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004222 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004223 IsCPRC = true;
James Molloy6f244b62014-05-09 16:21:39 +00004224 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004225 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004226 }
4227
Manman Ren6c30e132012-08-13 21:23:55 +00004228 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004229 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4230 // most 8-byte. We realign the indirect argument if type alignment is bigger
4231 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004232 uint64_t ABIAlign = 4;
4233 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4234 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4235 getABIKind() == ARMABIInfo::AAPCS)
4236 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004237 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004238 // Update Allocated GPRs. Since this is only used when the size of the
4239 // argument is greater than 64 bytes, this will always use up any available
4240 // registers (of which there are 4). We also don't care about getting the
4241 // alignment right, because general-purpose registers cannot be back-filled.
4242 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004243 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004244 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004245 }
4246
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004247 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004248 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004249 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004250 // FIXME: Try to match the types of the arguments more accurately where
4251 // we can.
4252 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004253 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4254 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004255 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004256 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004257 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4258 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004259 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004260 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004261
Chris Lattnera5f58b02011-07-09 17:41:47 +00004262 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00004263 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00004264 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004265}
4266
Chris Lattner458b2aa2010-07-29 02:16:43 +00004267static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004268 llvm::LLVMContext &VMContext) {
4269 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4270 // is called integer-like if its size is less than or equal to one word, and
4271 // the offset of each of its addressable sub-fields is zero.
4272
4273 uint64_t Size = Context.getTypeSize(Ty);
4274
4275 // Check that the type fits in a word.
4276 if (Size > 32)
4277 return false;
4278
4279 // FIXME: Handle vector types!
4280 if (Ty->isVectorType())
4281 return false;
4282
Daniel Dunbard53bac72009-09-14 02:20:34 +00004283 // Float types are never treated as "integer like".
4284 if (Ty->isRealFloatingType())
4285 return false;
4286
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004287 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004288 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004289 return true;
4290
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004291 // Small complex integer types are "integer like".
4292 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4293 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004294
4295 // Single element and zero sized arrays should be allowed, by the definition
4296 // above, but they are not.
4297
4298 // Otherwise, it must be a record type.
4299 const RecordType *RT = Ty->getAs<RecordType>();
4300 if (!RT) return false;
4301
4302 // Ignore records with flexible arrays.
4303 const RecordDecl *RD = RT->getDecl();
4304 if (RD->hasFlexibleArrayMember())
4305 return false;
4306
4307 // Check that all sub-fields are at offset 0, and are themselves "integer
4308 // like".
4309 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4310
4311 bool HadField = false;
4312 unsigned idx = 0;
4313 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4314 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004315 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004316
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004317 // Bit-fields are not addressable, we only need to verify they are "integer
4318 // like". We still have to disallow a subsequent non-bitfield, for example:
4319 // struct { int : 0; int x }
4320 // is non-integer like according to gcc.
4321 if (FD->isBitField()) {
4322 if (!RD->isUnion())
4323 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004324
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004325 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4326 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004327
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004328 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004329 }
4330
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004331 // Check if this field is at offset 0.
4332 if (Layout.getFieldOffset(idx) != 0)
4333 return false;
4334
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004335 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4336 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004337
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004338 // Only allow at most one field in a structure. This doesn't match the
4339 // wording above, but follows gcc in situations with a field following an
4340 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004341 if (!RD->isUnion()) {
4342 if (HadField)
4343 return false;
4344
4345 HadField = true;
4346 }
4347 }
4348
4349 return true;
4350}
4351
Oliver Stannard405bded2014-02-11 09:25:50 +00004352ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4353 bool isVariadic) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004354 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004355 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004356
Daniel Dunbar19964db2010-09-23 01:54:32 +00004357 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004358 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4359 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004360 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004361 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004362
John McCalla1dee5302010-08-22 10:59:02 +00004363 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004364 // Treat an enum type as its underlying type.
4365 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4366 RetTy = EnumTy->getDecl()->getIntegerType();
4367
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00004368 return (RetTy->isPromotableIntegerType() ?
4369 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004370 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004371
4372 // Are we following APCS?
4373 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004374 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004375 return ABIArgInfo::getIgnore();
4376
Daniel Dunbareedf1512010-02-01 23:31:19 +00004377 // Complex types are all returned as packed integers.
4378 //
4379 // FIXME: Consider using 2 x vector types if the back end handles them
4380 // correctly.
4381 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004382 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00004383 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004384
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004385 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004386 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004387 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004388 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004389 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004390 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004391 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004392 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4393 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004394 }
4395
4396 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004397 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004398 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004399 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004400
4401 // Otherwise this is an AAPCS variant.
4402
Chris Lattner458b2aa2010-07-29 02:16:43 +00004403 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004404 return ABIArgInfo::getIgnore();
4405
Bob Wilson1d9269a2011-11-02 04:51:36 +00004406 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00004407 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Craig Topper8a13c412014-05-21 05:09:00 +00004408 const Type *Base = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004409 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
4410 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004411 // Homogeneous Aggregates are returned directly.
4412 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004413 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004414 }
4415
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004416 // Aggregates <= 4 bytes are returned in r0; other aggregates
4417 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004418 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004419 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004420 if (getDataLayout().isBigEndian())
4421 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
4422 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
4423
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004424 // Return in the smallest viable integer type.
4425 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004426 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004427 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004428 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4429 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004430 }
4431
Oliver Stannard405bded2014-02-11 09:25:50 +00004432 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004433 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004434}
4435
Manman Renfef9e312012-10-16 19:18:39 +00004436/// isIllegalVector - check whether Ty is an illegal vector type.
4437bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4438 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4439 // Check whether VT is legal.
4440 unsigned NumElements = VT->getNumElements();
4441 uint64_t Size = getContext().getTypeSize(VT);
4442 // NumElements should be power of 2.
4443 if ((NumElements & (NumElements - 1)) != 0)
4444 return true;
4445 // Size should be greater than 32 bits.
4446 return Size <= 32;
4447 }
4448 return false;
4449}
4450
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004451llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004452 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004453 llvm::Type *BP = CGF.Int8PtrTy;
4454 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004455
4456 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004457 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004458 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004459
Tim Northover1711cc92013-06-21 23:05:33 +00004460 if (isEmptyRecord(getContext(), Ty, true)) {
4461 // These are ignored for parameter passing purposes.
4462 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4463 return Builder.CreateBitCast(Addr, PTy);
4464 }
4465
Manman Rencca54d02012-10-16 19:01:37 +00004466 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004467 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004468 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004469
4470 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4471 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004472 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4473 getABIKind() == ARMABIInfo::AAPCS)
4474 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4475 else
4476 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004477 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4478 if (isIllegalVectorType(Ty) && Size > 16) {
4479 IsIndirect = true;
4480 Size = 4;
4481 TyAlign = 4;
4482 }
Manman Rencca54d02012-10-16 19:01:37 +00004483
4484 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004485 if (TyAlign > 4) {
4486 assert((TyAlign & (TyAlign - 1)) == 0 &&
4487 "Alignment is not power of 2!");
4488 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4489 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4490 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004491 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004492 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004493
4494 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004495 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004496 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004497 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004498 "ap.next");
4499 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4500
Manman Renfef9e312012-10-16 19:18:39 +00004501 if (IsIndirect)
4502 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004503 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004504 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4505 // may not be correctly aligned for the vector type. We create an aligned
4506 // temporary space and copy the content over from ap.cur to the temporary
4507 // space. This is necessary if the natural alignment of the type is greater
4508 // than the ABI alignment.
4509 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4510 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4511 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4512 "var.align");
4513 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4514 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4515 Builder.CreateMemCpy(Dst, Src,
4516 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4517 TyAlign, false);
4518 Addr = AlignedTemp; //The content is in aligned location.
4519 }
4520 llvm::Type *PTy =
4521 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4522 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4523
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004524 return AddrTyped;
4525}
4526
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004527namespace {
4528
Derek Schuffa2020962012-10-16 22:30:41 +00004529class NaClARMABIInfo : public ABIInfo {
4530 public:
4531 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4532 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004533 void computeInfo(CGFunctionInfo &FI) const override;
4534 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4535 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00004536 private:
4537 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
4538 ARMABIInfo NInfo; // Used for everything else.
4539};
4540
4541class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
4542 public:
4543 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4544 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
4545};
4546
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004547}
4548
Derek Schuffa2020962012-10-16 22:30:41 +00004549void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4550 if (FI.getASTCallingConvention() == CC_PnaclCall)
4551 PInfo.computeInfo(FI);
4552 else
4553 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
4554}
4555
4556llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4557 CodeGenFunction &CGF) const {
4558 // Always use the native convention; calling pnacl-style varargs functions
4559 // is unsupported.
4560 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
4561}
4562
Chris Lattner0cf24192010-06-28 20:05:43 +00004563//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004564// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004565//===----------------------------------------------------------------------===//
4566
4567namespace {
4568
Justin Holewinski83e96682012-05-24 17:43:12 +00004569class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004570public:
Justin Holewinski36837432013-03-30 14:38:24 +00004571 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004572
4573 ABIArgInfo classifyReturnType(QualType RetTy) const;
4574 ABIArgInfo classifyArgumentType(QualType Ty) const;
4575
Craig Topper4f12f102014-03-12 06:41:41 +00004576 void computeInfo(CGFunctionInfo &FI) const override;
4577 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4578 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004579};
4580
Justin Holewinski83e96682012-05-24 17:43:12 +00004581class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004582public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004583 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4584 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004585
4586 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4587 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00004588private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00004589 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
4590 // resulting MDNode to the nvvm.annotations MDNode.
4591 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004592};
4593
Justin Holewinski83e96682012-05-24 17:43:12 +00004594ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004595 if (RetTy->isVoidType())
4596 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004597
4598 // note: this is different from default ABI
4599 if (!RetTy->isScalarType())
4600 return ABIArgInfo::getDirect();
4601
4602 // Treat an enum type as its underlying type.
4603 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4604 RetTy = EnumTy->getDecl()->getIntegerType();
4605
4606 return (RetTy->isPromotableIntegerType() ?
4607 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004608}
4609
Justin Holewinski83e96682012-05-24 17:43:12 +00004610ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004611 // Treat an enum type as its underlying type.
4612 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4613 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004614
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004615 return (Ty->isPromotableIntegerType() ?
4616 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004617}
4618
Justin Holewinski83e96682012-05-24 17:43:12 +00004619void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004620 if (!getCXXABI().classifyReturnType(FI))
4621 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004622 for (auto &I : FI.arguments())
4623 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004624
4625 // Always honor user-specified calling convention.
4626 if (FI.getCallingConvention() != llvm::CallingConv::C)
4627 return;
4628
John McCall882987f2013-02-28 19:01:20 +00004629 FI.setEffectiveCallingConvention(getRuntimeCC());
4630}
4631
Justin Holewinski83e96682012-05-24 17:43:12 +00004632llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4633 CodeGenFunction &CFG) const {
4634 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004635}
4636
Justin Holewinski83e96682012-05-24 17:43:12 +00004637void NVPTXTargetCodeGenInfo::
4638SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4639 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004640 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4641 if (!FD) return;
4642
4643 llvm::Function *F = cast<llvm::Function>(GV);
4644
4645 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004646 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004647 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004648 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004649 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004650 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00004651 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4652 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00004653 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004654 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004655 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004656 }
Justin Holewinski38031972011-10-05 17:58:44 +00004657
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004658 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004659 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004660 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004661 // __global__ functions cannot be called from the device, we do not
4662 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00004663 if (FD->hasAttr<CUDAGlobalAttr>()) {
4664 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4665 addNVVMMetadata(F, "kernel", 1);
4666 }
4667 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
4668 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
4669 addNVVMMetadata(F, "maxntidx",
4670 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
4671 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
4672 // zero value from getMinBlocks either means it was not specified in
4673 // __launch_bounds__ or the user specified a 0 value. In both cases, we
4674 // don't have to add a PTX directive.
4675 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
4676 if (MinCTASM > 0) {
4677 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
4678 addNVVMMetadata(F, "minctasm", MinCTASM);
4679 }
4680 }
Justin Holewinski38031972011-10-05 17:58:44 +00004681 }
4682}
4683
Eli Benderskye06a2c42014-04-15 16:57:05 +00004684void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
4685 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00004686 llvm::Module *M = F->getParent();
4687 llvm::LLVMContext &Ctx = M->getContext();
4688
4689 // Get "nvvm.annotations" metadata node
4690 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4691
Eli Benderskye1627b42014-04-15 17:19:26 +00004692 llvm::Value *MDVals[] = {
4693 F, llvm::MDString::get(Ctx, Name),
4694 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinski36837432013-03-30 14:38:24 +00004695 // Append metadata to nvvm.annotations
4696 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4697}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004698}
4699
4700//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004701// SystemZ ABI Implementation
4702//===----------------------------------------------------------------------===//
4703
4704namespace {
4705
4706class SystemZABIInfo : public ABIInfo {
4707public:
4708 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4709
4710 bool isPromotableIntegerType(QualType Ty) const;
4711 bool isCompoundType(QualType Ty) const;
4712 bool isFPArgumentType(QualType Ty) const;
4713
4714 ABIArgInfo classifyReturnType(QualType RetTy) const;
4715 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4716
Craig Topper4f12f102014-03-12 06:41:41 +00004717 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004718 if (!getCXXABI().classifyReturnType(FI))
4719 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004720 for (auto &I : FI.arguments())
4721 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00004722 }
4723
Craig Topper4f12f102014-03-12 06:41:41 +00004724 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4725 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00004726};
4727
4728class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4729public:
4730 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4731 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4732};
4733
4734}
4735
4736bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4737 // Treat an enum type as its underlying type.
4738 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4739 Ty = EnumTy->getDecl()->getIntegerType();
4740
4741 // Promotable integer types are required to be promoted by the ABI.
4742 if (Ty->isPromotableIntegerType())
4743 return true;
4744
4745 // 32-bit values must also be promoted.
4746 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4747 switch (BT->getKind()) {
4748 case BuiltinType::Int:
4749 case BuiltinType::UInt:
4750 return true;
4751 default:
4752 return false;
4753 }
4754 return false;
4755}
4756
4757bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4758 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4759}
4760
4761bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4762 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4763 switch (BT->getKind()) {
4764 case BuiltinType::Float:
4765 case BuiltinType::Double:
4766 return true;
4767 default:
4768 return false;
4769 }
4770
4771 if (const RecordType *RT = Ty->getAsStructureType()) {
4772 const RecordDecl *RD = RT->getDecl();
4773 bool Found = false;
4774
4775 // If this is a C++ record, check the bases first.
4776 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00004777 for (const auto &I : CXXRD->bases()) {
4778 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00004779
4780 // Empty bases don't affect things either way.
4781 if (isEmptyRecord(getContext(), Base, true))
4782 continue;
4783
4784 if (Found)
4785 return false;
4786 Found = isFPArgumentType(Base);
4787 if (!Found)
4788 return false;
4789 }
4790
4791 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004792 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00004793 // Empty bitfields don't affect things either way.
4794 // Unlike isSingleElementStruct(), empty structure and array fields
4795 // do count. So do anonymous bitfields that aren't zero-sized.
4796 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4797 return true;
4798
4799 // Unlike isSingleElementStruct(), arrays do not count.
4800 // Nested isFPArgumentType structures still do though.
4801 if (Found)
4802 return false;
4803 Found = isFPArgumentType(FD->getType());
4804 if (!Found)
4805 return false;
4806 }
4807
4808 // Unlike isSingleElementStruct(), trailing padding is allowed.
4809 // An 8-byte aligned struct s { float f; } is passed as a double.
4810 return Found;
4811 }
4812
4813 return false;
4814}
4815
4816llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4817 CodeGenFunction &CGF) const {
4818 // Assume that va_list type is correct; should be pointer to LLVM type:
4819 // struct {
4820 // i64 __gpr;
4821 // i64 __fpr;
4822 // i8 *__overflow_arg_area;
4823 // i8 *__reg_save_area;
4824 // };
4825
4826 // Every argument occupies 8 bytes and is passed by preference in either
4827 // GPRs or FPRs.
4828 Ty = CGF.getContext().getCanonicalType(Ty);
4829 ABIArgInfo AI = classifyArgumentType(Ty);
4830 bool InFPRs = isFPArgumentType(Ty);
4831
4832 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4833 bool IsIndirect = AI.isIndirect();
4834 unsigned UnpaddedBitSize;
4835 if (IsIndirect) {
4836 APTy = llvm::PointerType::getUnqual(APTy);
4837 UnpaddedBitSize = 64;
4838 } else
4839 UnpaddedBitSize = getContext().getTypeSize(Ty);
4840 unsigned PaddedBitSize = 64;
4841 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4842
4843 unsigned PaddedSize = PaddedBitSize / 8;
4844 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4845
4846 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4847 if (InFPRs) {
4848 MaxRegs = 4; // Maximum of 4 FPR arguments
4849 RegCountField = 1; // __fpr
4850 RegSaveIndex = 16; // save offset for f0
4851 RegPadding = 0; // floats are passed in the high bits of an FPR
4852 } else {
4853 MaxRegs = 5; // Maximum of 5 GPR arguments
4854 RegCountField = 0; // __gpr
4855 RegSaveIndex = 2; // save offset for r2
4856 RegPadding = Padding; // values are passed in the low bits of a GPR
4857 }
4858
4859 llvm::Value *RegCountPtr =
4860 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4861 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4862 llvm::Type *IndexTy = RegCount->getType();
4863 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4864 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00004865 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00004866
4867 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4868 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4869 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4870 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4871
4872 // Emit code to load the value if it was passed in registers.
4873 CGF.EmitBlock(InRegBlock);
4874
4875 // Work out the address of an argument register.
4876 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4877 llvm::Value *ScaledRegCount =
4878 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4879 llvm::Value *RegBase =
4880 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4881 llvm::Value *RegOffset =
4882 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4883 llvm::Value *RegSaveAreaPtr =
4884 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4885 llvm::Value *RegSaveArea =
4886 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4887 llvm::Value *RawRegAddr =
4888 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4889 llvm::Value *RegAddr =
4890 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4891
4892 // Update the register count
4893 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4894 llvm::Value *NewRegCount =
4895 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4896 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4897 CGF.EmitBranch(ContBlock);
4898
4899 // Emit code to load the value if it was passed in memory.
4900 CGF.EmitBlock(InMemBlock);
4901
4902 // Work out the address of a stack argument.
4903 llvm::Value *OverflowArgAreaPtr =
4904 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4905 llvm::Value *OverflowArgArea =
4906 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4907 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4908 llvm::Value *RawMemAddr =
4909 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4910 llvm::Value *MemAddr =
4911 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4912
4913 // Update overflow_arg_area_ptr pointer
4914 llvm::Value *NewOverflowArgArea =
4915 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4916 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4917 CGF.EmitBranch(ContBlock);
4918
4919 // Return the appropriate result.
4920 CGF.EmitBlock(ContBlock);
4921 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4922 ResAddr->addIncoming(RegAddr, InRegBlock);
4923 ResAddr->addIncoming(MemAddr, InMemBlock);
4924
4925 if (IsIndirect)
4926 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4927
4928 return ResAddr;
4929}
4930
Ulrich Weigand47445072013-05-06 16:26:41 +00004931ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4932 if (RetTy->isVoidType())
4933 return ABIArgInfo::getIgnore();
4934 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4935 return ABIArgInfo::getIndirect(0);
4936 return (isPromotableIntegerType(RetTy) ?
4937 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4938}
4939
4940ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4941 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00004942 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00004943 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4944
4945 // Integers and enums are extended to full register width.
4946 if (isPromotableIntegerType(Ty))
4947 return ABIArgInfo::getExtend();
4948
4949 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4950 uint64_t Size = getContext().getTypeSize(Ty);
4951 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00004952 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004953
4954 // Handle small structures.
4955 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4956 // Structures with flexible arrays have variable length, so really
4957 // fail the size test above.
4958 const RecordDecl *RD = RT->getDecl();
4959 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00004960 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004961
4962 // The structure is passed as an unextended integer, a float, or a double.
4963 llvm::Type *PassTy;
4964 if (isFPArgumentType(Ty)) {
4965 assert(Size == 32 || Size == 64);
4966 if (Size == 32)
4967 PassTy = llvm::Type::getFloatTy(getVMContext());
4968 else
4969 PassTy = llvm::Type::getDoubleTy(getVMContext());
4970 } else
4971 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4972 return ABIArgInfo::getDirect(PassTy);
4973 }
4974
4975 // Non-structure compounds are passed indirectly.
4976 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00004977 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004978
Craig Topper8a13c412014-05-21 05:09:00 +00004979 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00004980}
4981
4982//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004983// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004984//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004985
4986namespace {
4987
4988class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4989public:
Chris Lattner2b037972010-07-29 02:01:43 +00004990 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4991 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004992 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004993 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004994};
4995
4996}
4997
4998void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4999 llvm::GlobalValue *GV,
5000 CodeGen::CodeGenModule &M) const {
5001 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5002 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5003 // Handle 'interrupt' attribute:
5004 llvm::Function *F = cast<llvm::Function>(GV);
5005
5006 // Step 1: Set ISR calling convention.
5007 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5008
5009 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005010 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005011
5012 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005013 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005014 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5015 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005016 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005017 }
5018}
5019
Chris Lattner0cf24192010-06-28 20:05:43 +00005020//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005021// MIPS ABI Implementation. This works for both little-endian and
5022// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005023//===----------------------------------------------------------------------===//
5024
John McCall943fae92010-05-27 06:19:26 +00005025namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005026class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005027 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005028 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5029 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005030 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005031 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005032 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005033 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005034public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005035 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005036 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005037 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005038
5039 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005040 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005041 void computeInfo(CGFunctionInfo &FI) const override;
5042 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5043 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005044};
5045
John McCall943fae92010-05-27 06:19:26 +00005046class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005047 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005048public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005049 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5050 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005051 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005052
Craig Topper4f12f102014-03-12 06:41:41 +00005053 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005054 return 29;
5055 }
5056
Reed Kotler373feca2013-01-16 17:10:28 +00005057 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005058 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005059 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5060 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005061 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005062 if (FD->hasAttr<Mips16Attr>()) {
5063 Fn->addFnAttr("mips16");
5064 }
5065 else if (FD->hasAttr<NoMips16Attr>()) {
5066 Fn->addFnAttr("nomips16");
5067 }
Reed Kotler373feca2013-01-16 17:10:28 +00005068 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005069
John McCall943fae92010-05-27 06:19:26 +00005070 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005071 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005072
Craig Topper4f12f102014-03-12 06:41:41 +00005073 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005074 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005075 }
John McCall943fae92010-05-27 06:19:26 +00005076};
5077}
5078
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005079void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005080 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005081 llvm::IntegerType *IntTy =
5082 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005083
5084 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5085 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5086 ArgList.push_back(IntTy);
5087
5088 // If necessary, add one more integer type to ArgList.
5089 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5090
5091 if (R)
5092 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005093}
5094
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005095// In N32/64, an aligned double precision floating point field is passed in
5096// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005097llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005098 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5099
5100 if (IsO32) {
5101 CoerceToIntArgs(TySize, ArgList);
5102 return llvm::StructType::get(getVMContext(), ArgList);
5103 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005104
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005105 if (Ty->isComplexType())
5106 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005107
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005108 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005109
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005110 // Unions/vectors are passed in integer registers.
5111 if (!RT || !RT->isStructureOrClassType()) {
5112 CoerceToIntArgs(TySize, ArgList);
5113 return llvm::StructType::get(getVMContext(), ArgList);
5114 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005115
5116 const RecordDecl *RD = RT->getDecl();
5117 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005118 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005119
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005120 uint64_t LastOffset = 0;
5121 unsigned idx = 0;
5122 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5123
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005124 // Iterate over fields in the struct/class and check if there are any aligned
5125 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005126 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5127 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005128 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005129 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5130
5131 if (!BT || BT->getKind() != BuiltinType::Double)
5132 continue;
5133
5134 uint64_t Offset = Layout.getFieldOffset(idx);
5135 if (Offset % 64) // Ignore doubles that are not aligned.
5136 continue;
5137
5138 // Add ((Offset - LastOffset) / 64) args of type i64.
5139 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5140 ArgList.push_back(I64);
5141
5142 // Add double type.
5143 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5144 LastOffset = Offset + 64;
5145 }
5146
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005147 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5148 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005149
5150 return llvm::StructType::get(getVMContext(), ArgList);
5151}
5152
Akira Hatanakaddd66342013-10-29 18:41:15 +00005153llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5154 uint64_t Offset) const {
5155 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005156 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005157
Akira Hatanakaddd66342013-10-29 18:41:15 +00005158 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005159}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005160
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005161ABIArgInfo
5162MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005163 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005164 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005165 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005166
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005167 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5168 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005169 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5170 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005171
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005172 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005173 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005174 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005175 return ABIArgInfo::getIgnore();
5176
Mark Lacey3825e832013-10-06 01:33:34 +00005177 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005178 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005179 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005180 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005181
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005182 // If we have reached here, aggregates are passed directly by coercing to
5183 // another structure type. Padding is inserted if the offset of the
5184 // aggregate is unaligned.
5185 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00005186 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005187 }
5188
5189 // Treat an enum type as its underlying type.
5190 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5191 Ty = EnumTy->getDecl()->getIntegerType();
5192
Akira Hatanaka1632af62012-01-09 19:31:25 +00005193 if (Ty->isPromotableIntegerType())
5194 return ABIArgInfo::getExtend();
5195
Akira Hatanakaddd66342013-10-29 18:41:15 +00005196 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005197 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005198}
5199
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005200llvm::Type*
5201MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005202 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005203 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005204
Akira Hatanakab6f74432012-02-09 18:49:26 +00005205 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005206 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005207 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5208 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005209
Akira Hatanakab6f74432012-02-09 18:49:26 +00005210 // N32/64 returns struct/classes in floating point registers if the
5211 // following conditions are met:
5212 // 1. The size of the struct/class is no larger than 128-bit.
5213 // 2. The struct/class has one or two fields all of which are floating
5214 // point types.
5215 // 3. The offset of the first field is zero (this follows what gcc does).
5216 //
5217 // Any other composite results are returned in integer registers.
5218 //
5219 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5220 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5221 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005222 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005223
Akira Hatanakab6f74432012-02-09 18:49:26 +00005224 if (!BT || !BT->isFloatingPoint())
5225 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005226
David Blaikie2d7c57e2012-04-30 02:36:29 +00005227 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005228 }
5229
5230 if (b == e)
5231 return llvm::StructType::get(getVMContext(), RTList,
5232 RD->hasAttr<PackedAttr>());
5233
5234 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005235 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005236 }
5237
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005238 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005239 return llvm::StructType::get(getVMContext(), RTList);
5240}
5241
Akira Hatanakab579fe52011-06-02 00:09:17 +00005242ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005243 uint64_t Size = getContext().getTypeSize(RetTy);
5244
5245 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005246 return ABIArgInfo::getIgnore();
5247
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005248 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005249 if (Size <= 128) {
5250 if (RetTy->isAnyComplexType())
5251 return ABIArgInfo::getDirect();
5252
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005253 // O32 returns integer vectors in registers.
5254 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
5255 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5256
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005257 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005258 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5259 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005260
5261 return ABIArgInfo::getIndirect(0);
5262 }
5263
5264 // Treat an enum type as its underlying type.
5265 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5266 RetTy = EnumTy->getDecl()->getIntegerType();
5267
5268 return (RetTy->isPromotableIntegerType() ?
5269 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5270}
5271
5272void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005273 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005274 if (!getCXXABI().classifyReturnType(FI))
5275 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005276
5277 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005278 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005279
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005280 for (auto &I : FI.arguments())
5281 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005282}
5283
5284llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5285 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00005286 llvm::Type *BP = CGF.Int8PtrTy;
5287 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005288
5289 CGBuilderTy &Builder = CGF.Builder;
5290 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5291 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00005292 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005293 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5294 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00005295 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00005296 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005297
5298 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00005299 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5300 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5301 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5302 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005303 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5304 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5305 }
5306 else
5307 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5308
5309 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00005310 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005311 uint64_t Offset =
5312 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5313 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00005314 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005315 "ap.next");
5316 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5317
5318 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005319}
5320
John McCall943fae92010-05-27 06:19:26 +00005321bool
5322MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5323 llvm::Value *Address) const {
5324 // This information comes from gcc's implementation, which seems to
5325 // as canonical as it gets.
5326
John McCall943fae92010-05-27 06:19:26 +00005327 // Everything on MIPS is 4 bytes. Double-precision FP registers
5328 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005329 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005330
5331 // 0-31 are the general purpose registers, $0 - $31.
5332 // 32-63 are the floating-point registers, $f0 - $f31.
5333 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5334 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005335 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005336
5337 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5338 // They are one bit wide and ignored here.
5339
5340 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5341 // (coprocessor 1 is the FP unit)
5342 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5343 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5344 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005345 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005346 return false;
5347}
5348
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005349//===----------------------------------------------------------------------===//
5350// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5351// Currently subclassed only to implement custom OpenCL C function attribute
5352// handling.
5353//===----------------------------------------------------------------------===//
5354
5355namespace {
5356
5357class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5358public:
5359 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5360 : DefaultTargetCodeGenInfo(CGT) {}
5361
Craig Topper4f12f102014-03-12 06:41:41 +00005362 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5363 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005364};
5365
5366void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5367 llvm::GlobalValue *GV,
5368 CodeGen::CodeGenModule &M) const {
5369 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5370 if (!FD) return;
5371
5372 llvm::Function *F = cast<llvm::Function>(GV);
5373
David Blaikiebbafb8a2012-03-11 07:00:24 +00005374 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005375 if (FD->hasAttr<OpenCLKernelAttr>()) {
5376 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005377 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005378 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5379 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005380 // Convert the reqd_work_group_size() attributes to metadata.
5381 llvm::LLVMContext &Context = F->getContext();
5382 llvm::NamedMDNode *OpenCLMetadata =
5383 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5384
5385 SmallVector<llvm::Value*, 5> Operands;
5386 Operands.push_back(F);
5387
Chris Lattnerece04092012-02-07 00:39:47 +00005388 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005389 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005390 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005391 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005392 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005393 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005394
5395 // Add a boolean constant operand for "required" (true) or "hint" (false)
5396 // for implementing the work_group_size_hint attr later. Currently
5397 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005398 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005399 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5400 }
5401 }
5402 }
5403}
5404
5405}
John McCall943fae92010-05-27 06:19:26 +00005406
Tony Linthicum76329bf2011-12-12 21:14:55 +00005407//===----------------------------------------------------------------------===//
5408// Hexagon ABI Implementation
5409//===----------------------------------------------------------------------===//
5410
5411namespace {
5412
5413class HexagonABIInfo : public ABIInfo {
5414
5415
5416public:
5417 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5418
5419private:
5420
5421 ABIArgInfo classifyReturnType(QualType RetTy) const;
5422 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5423
Craig Topper4f12f102014-03-12 06:41:41 +00005424 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005425
Craig Topper4f12f102014-03-12 06:41:41 +00005426 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5427 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005428};
5429
5430class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5431public:
5432 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5433 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5434
Craig Topper4f12f102014-03-12 06:41:41 +00005435 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005436 return 29;
5437 }
5438};
5439
5440}
5441
5442void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005443 if (!getCXXABI().classifyReturnType(FI))
5444 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005445 for (auto &I : FI.arguments())
5446 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005447}
5448
5449ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5450 if (!isAggregateTypeForABI(Ty)) {
5451 // Treat an enum type as its underlying type.
5452 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5453 Ty = EnumTy->getDecl()->getIntegerType();
5454
5455 return (Ty->isPromotableIntegerType() ?
5456 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5457 }
5458
5459 // Ignore empty records.
5460 if (isEmptyRecord(getContext(), Ty, true))
5461 return ABIArgInfo::getIgnore();
5462
Mark Lacey3825e832013-10-06 01:33:34 +00005463 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005464 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005465
5466 uint64_t Size = getContext().getTypeSize(Ty);
5467 if (Size > 64)
5468 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5469 // Pass in the smallest viable integer type.
5470 else if (Size > 32)
5471 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5472 else if (Size > 16)
5473 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5474 else if (Size > 8)
5475 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5476 else
5477 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5478}
5479
5480ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5481 if (RetTy->isVoidType())
5482 return ABIArgInfo::getIgnore();
5483
5484 // Large vector types should be returned via memory.
5485 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5486 return ABIArgInfo::getIndirect(0);
5487
5488 if (!isAggregateTypeForABI(RetTy)) {
5489 // Treat an enum type as its underlying type.
5490 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5491 RetTy = EnumTy->getDecl()->getIntegerType();
5492
5493 return (RetTy->isPromotableIntegerType() ?
5494 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5495 }
5496
Tony Linthicum76329bf2011-12-12 21:14:55 +00005497 if (isEmptyRecord(getContext(), RetTy, true))
5498 return ABIArgInfo::getIgnore();
5499
5500 // Aggregates <= 8 bytes are returned in r0; other aggregates
5501 // are returned indirectly.
5502 uint64_t Size = getContext().getTypeSize(RetTy);
5503 if (Size <= 64) {
5504 // Return in the smallest viable integer type.
5505 if (Size <= 8)
5506 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5507 if (Size <= 16)
5508 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5509 if (Size <= 32)
5510 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5511 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5512 }
5513
5514 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5515}
5516
5517llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005518 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005519 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005520 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005521
5522 CGBuilderTy &Builder = CGF.Builder;
5523 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5524 "ap");
5525 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5526 llvm::Type *PTy =
5527 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5528 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5529
5530 uint64_t Offset =
5531 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5532 llvm::Value *NextAddr =
5533 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5534 "ap.next");
5535 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5536
5537 return AddrTyped;
5538}
5539
5540
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005541//===----------------------------------------------------------------------===//
5542// SPARC v9 ABI Implementation.
5543// Based on the SPARC Compliance Definition version 2.4.1.
5544//
5545// Function arguments a mapped to a nominal "parameter array" and promoted to
5546// registers depending on their type. Each argument occupies 8 or 16 bytes in
5547// the array, structs larger than 16 bytes are passed indirectly.
5548//
5549// One case requires special care:
5550//
5551// struct mixed {
5552// int i;
5553// float f;
5554// };
5555//
5556// When a struct mixed is passed by value, it only occupies 8 bytes in the
5557// parameter array, but the int is passed in an integer register, and the float
5558// is passed in a floating point register. This is represented as two arguments
5559// with the LLVM IR inreg attribute:
5560//
5561// declare void f(i32 inreg %i, float inreg %f)
5562//
5563// The code generator will only allocate 4 bytes from the parameter array for
5564// the inreg arguments. All other arguments are allocated a multiple of 8
5565// bytes.
5566//
5567namespace {
5568class SparcV9ABIInfo : public ABIInfo {
5569public:
5570 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5571
5572private:
5573 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005574 void computeInfo(CGFunctionInfo &FI) const override;
5575 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5576 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005577
5578 // Coercion type builder for structs passed in registers. The coercion type
5579 // serves two purposes:
5580 //
5581 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5582 // in registers.
5583 // 2. Expose aligned floating point elements as first-level elements, so the
5584 // code generator knows to pass them in floating point registers.
5585 //
5586 // We also compute the InReg flag which indicates that the struct contains
5587 // aligned 32-bit floats.
5588 //
5589 struct CoerceBuilder {
5590 llvm::LLVMContext &Context;
5591 const llvm::DataLayout &DL;
5592 SmallVector<llvm::Type*, 8> Elems;
5593 uint64_t Size;
5594 bool InReg;
5595
5596 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5597 : Context(c), DL(dl), Size(0), InReg(false) {}
5598
5599 // Pad Elems with integers until Size is ToSize.
5600 void pad(uint64_t ToSize) {
5601 assert(ToSize >= Size && "Cannot remove elements");
5602 if (ToSize == Size)
5603 return;
5604
5605 // Finish the current 64-bit word.
5606 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5607 if (Aligned > Size && Aligned <= ToSize) {
5608 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5609 Size = Aligned;
5610 }
5611
5612 // Add whole 64-bit words.
5613 while (Size + 64 <= ToSize) {
5614 Elems.push_back(llvm::Type::getInt64Ty(Context));
5615 Size += 64;
5616 }
5617
5618 // Final in-word padding.
5619 if (Size < ToSize) {
5620 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5621 Size = ToSize;
5622 }
5623 }
5624
5625 // Add a floating point element at Offset.
5626 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5627 // Unaligned floats are treated as integers.
5628 if (Offset % Bits)
5629 return;
5630 // The InReg flag is only required if there are any floats < 64 bits.
5631 if (Bits < 64)
5632 InReg = true;
5633 pad(Offset);
5634 Elems.push_back(Ty);
5635 Size = Offset + Bits;
5636 }
5637
5638 // Add a struct type to the coercion type, starting at Offset (in bits).
5639 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5640 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5641 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5642 llvm::Type *ElemTy = StrTy->getElementType(i);
5643 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5644 switch (ElemTy->getTypeID()) {
5645 case llvm::Type::StructTyID:
5646 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5647 break;
5648 case llvm::Type::FloatTyID:
5649 addFloat(ElemOffset, ElemTy, 32);
5650 break;
5651 case llvm::Type::DoubleTyID:
5652 addFloat(ElemOffset, ElemTy, 64);
5653 break;
5654 case llvm::Type::FP128TyID:
5655 addFloat(ElemOffset, ElemTy, 128);
5656 break;
5657 case llvm::Type::PointerTyID:
5658 if (ElemOffset % 64 == 0) {
5659 pad(ElemOffset);
5660 Elems.push_back(ElemTy);
5661 Size += 64;
5662 }
5663 break;
5664 default:
5665 break;
5666 }
5667 }
5668 }
5669
5670 // Check if Ty is a usable substitute for the coercion type.
5671 bool isUsableType(llvm::StructType *Ty) const {
5672 if (Ty->getNumElements() != Elems.size())
5673 return false;
5674 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5675 if (Elems[i] != Ty->getElementType(i))
5676 return false;
5677 return true;
5678 }
5679
5680 // Get the coercion type as a literal struct type.
5681 llvm::Type *getType() const {
5682 if (Elems.size() == 1)
5683 return Elems.front();
5684 else
5685 return llvm::StructType::get(Context, Elems);
5686 }
5687 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005688};
5689} // end anonymous namespace
5690
5691ABIArgInfo
5692SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5693 if (Ty->isVoidType())
5694 return ABIArgInfo::getIgnore();
5695
5696 uint64_t Size = getContext().getTypeSize(Ty);
5697
5698 // Anything too big to fit in registers is passed with an explicit indirect
5699 // pointer / sret pointer.
5700 if (Size > SizeLimit)
5701 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5702
5703 // Treat an enum type as its underlying type.
5704 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5705 Ty = EnumTy->getDecl()->getIntegerType();
5706
5707 // Integer types smaller than a register are extended.
5708 if (Size < 64 && Ty->isIntegerType())
5709 return ABIArgInfo::getExtend();
5710
5711 // Other non-aggregates go in registers.
5712 if (!isAggregateTypeForABI(Ty))
5713 return ABIArgInfo::getDirect();
5714
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00005715 // If a C++ object has either a non-trivial copy constructor or a non-trivial
5716 // destructor, it is passed with an explicit indirect pointer / sret pointer.
5717 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5718 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5719
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005720 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005721 // Build a coercion type from the LLVM struct type.
5722 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5723 if (!StrTy)
5724 return ABIArgInfo::getDirect();
5725
5726 CoerceBuilder CB(getVMContext(), getDataLayout());
5727 CB.addStruct(0, StrTy);
5728 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5729
5730 // Try to use the original type for coercion.
5731 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5732
5733 if (CB.InReg)
5734 return ABIArgInfo::getDirectInReg(CoerceTy);
5735 else
5736 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005737}
5738
5739llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5740 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005741 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5742 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5743 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5744 AI.setCoerceToType(ArgTy);
5745
5746 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5747 CGBuilderTy &Builder = CGF.Builder;
5748 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5749 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5750 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5751 llvm::Value *ArgAddr;
5752 unsigned Stride;
5753
5754 switch (AI.getKind()) {
5755 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00005756 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005757 llvm_unreachable("Unsupported ABI kind for va_arg");
5758
5759 case ABIArgInfo::Extend:
5760 Stride = 8;
5761 ArgAddr = Builder
5762 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5763 "extend");
5764 break;
5765
5766 case ABIArgInfo::Direct:
5767 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5768 ArgAddr = Addr;
5769 break;
5770
5771 case ABIArgInfo::Indirect:
5772 Stride = 8;
5773 ArgAddr = Builder.CreateBitCast(Addr,
5774 llvm::PointerType::getUnqual(ArgPtrTy),
5775 "indirect");
5776 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5777 break;
5778
5779 case ABIArgInfo::Ignore:
5780 return llvm::UndefValue::get(ArgPtrTy);
5781 }
5782
5783 // Update VAList.
5784 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5785 Builder.CreateStore(Addr, VAListAddrAsBPP);
5786
5787 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005788}
5789
5790void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5791 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005792 for (auto &I : FI.arguments())
5793 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005794}
5795
5796namespace {
5797class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5798public:
5799 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5800 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00005801
Craig Topper4f12f102014-03-12 06:41:41 +00005802 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00005803 return 14;
5804 }
5805
5806 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005807 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005808};
5809} // end anonymous namespace
5810
Roman Divackyf02c9942014-02-24 18:46:27 +00005811bool
5812SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5813 llvm::Value *Address) const {
5814 // This is calculated from the LLVM and GCC tables and verified
5815 // against gcc output. AFAIK all ABIs use the same encoding.
5816
5817 CodeGen::CGBuilderTy &Builder = CGF.Builder;
5818
5819 llvm::IntegerType *i8 = CGF.Int8Ty;
5820 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
5821 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
5822
5823 // 0-31: the 8-byte general-purpose registers
5824 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
5825
5826 // 32-63: f0-31, the 4-byte floating-point registers
5827 AssignToArrayRange(Builder, Address, Four8, 32, 63);
5828
5829 // Y = 64
5830 // PSR = 65
5831 // WIM = 66
5832 // TBR = 67
5833 // PC = 68
5834 // NPC = 69
5835 // FSR = 70
5836 // CSR = 71
5837 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
5838
5839 // 72-87: d0-15, the 8-byte floating-point registers
5840 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
5841
5842 return false;
5843}
5844
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005845
Robert Lytton0e076492013-08-13 09:43:10 +00005846//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00005847// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00005848//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00005849
Robert Lytton0e076492013-08-13 09:43:10 +00005850namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00005851
5852/// A SmallStringEnc instance is used to build up the TypeString by passing
5853/// it by reference between functions that append to it.
5854typedef llvm::SmallString<128> SmallStringEnc;
5855
5856/// TypeStringCache caches the meta encodings of Types.
5857///
5858/// The reason for caching TypeStrings is two fold:
5859/// 1. To cache a type's encoding for later uses;
5860/// 2. As a means to break recursive member type inclusion.
5861///
5862/// A cache Entry can have a Status of:
5863/// NonRecursive: The type encoding is not recursive;
5864/// Recursive: The type encoding is recursive;
5865/// Incomplete: An incomplete TypeString;
5866/// IncompleteUsed: An incomplete TypeString that has been used in a
5867/// Recursive type encoding.
5868///
5869/// A NonRecursive entry will have all of its sub-members expanded as fully
5870/// as possible. Whilst it may contain types which are recursive, the type
5871/// itself is not recursive and thus its encoding may be safely used whenever
5872/// the type is encountered.
5873///
5874/// A Recursive entry will have all of its sub-members expanded as fully as
5875/// possible. The type itself is recursive and it may contain other types which
5876/// are recursive. The Recursive encoding must not be used during the expansion
5877/// of a recursive type's recursive branch. For simplicity the code uses
5878/// IncompleteCount to reject all usage of Recursive encodings for member types.
5879///
5880/// An Incomplete entry is always a RecordType and only encodes its
5881/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
5882/// are placed into the cache during type expansion as a means to identify and
5883/// handle recursive inclusion of types as sub-members. If there is recursion
5884/// the entry becomes IncompleteUsed.
5885///
5886/// During the expansion of a RecordType's members:
5887///
5888/// If the cache contains a NonRecursive encoding for the member type, the
5889/// cached encoding is used;
5890///
5891/// If the cache contains a Recursive encoding for the member type, the
5892/// cached encoding is 'Swapped' out, as it may be incorrect, and...
5893///
5894/// If the member is a RecordType, an Incomplete encoding is placed into the
5895/// cache to break potential recursive inclusion of itself as a sub-member;
5896///
5897/// Once a member RecordType has been expanded, its temporary incomplete
5898/// entry is removed from the cache. If a Recursive encoding was swapped out
5899/// it is swapped back in;
5900///
5901/// If an incomplete entry is used to expand a sub-member, the incomplete
5902/// entry is marked as IncompleteUsed. The cache keeps count of how many
5903/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
5904///
5905/// If a member's encoding is found to be a NonRecursive or Recursive viz:
5906/// IncompleteUsedCount==0, the member's encoding is added to the cache.
5907/// Else the member is part of a recursive type and thus the recursion has
5908/// been exited too soon for the encoding to be correct for the member.
5909///
5910class TypeStringCache {
5911 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
5912 struct Entry {
5913 std::string Str; // The encoded TypeString for the type.
5914 enum Status State; // Information about the encoding in 'Str'.
5915 std::string Swapped; // A temporary place holder for a Recursive encoding
5916 // during the expansion of RecordType's members.
5917 };
5918 std::map<const IdentifierInfo *, struct Entry> Map;
5919 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
5920 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
5921public:
Robert Lyttond263f142014-05-06 09:38:54 +00005922 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00005923 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
5924 bool removeIncomplete(const IdentifierInfo *ID);
5925 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
5926 bool IsRecursive);
5927 StringRef lookupStr(const IdentifierInfo *ID);
5928};
5929
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00005930/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00005931/// FieldEncoding is a helper for this ordering process.
5932class FieldEncoding {
5933 bool HasName;
5934 std::string Enc;
5935public:
5936 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
5937 StringRef str() {return Enc.c_str();};
5938 bool operator<(const FieldEncoding &rhs) const {
5939 if (HasName != rhs.HasName) return HasName;
5940 return Enc < rhs.Enc;
5941 }
5942};
5943
Robert Lytton7d1db152013-08-19 09:46:39 +00005944class XCoreABIInfo : public DefaultABIInfo {
5945public:
5946 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005947 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5948 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00005949};
5950
Robert Lyttond21e2d72014-03-03 13:45:29 +00005951class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00005952 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00005953public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00005954 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00005955 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00005956 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
5957 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00005958};
Robert Lytton844aeeb2014-05-02 09:33:20 +00005959
Robert Lytton2d196952013-10-11 10:29:34 +00005960} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00005961
Robert Lytton7d1db152013-08-19 09:46:39 +00005962llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5963 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00005964 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00005965
Robert Lytton2d196952013-10-11 10:29:34 +00005966 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00005967 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5968 CGF.Int8PtrPtrTy);
5969 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00005970
Robert Lytton2d196952013-10-11 10:29:34 +00005971 // Handle the argument.
5972 ABIArgInfo AI = classifyArgumentType(Ty);
5973 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5974 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5975 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00005976 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00005977 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00005978 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00005979 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00005980 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00005981 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00005982 llvm_unreachable("Unsupported ABI kind for va_arg");
5983 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00005984 Val = llvm::UndefValue::get(ArgPtrTy);
5985 ArgSize = 0;
5986 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005987 case ABIArgInfo::Extend:
5988 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00005989 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5990 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5991 if (ArgSize < 4)
5992 ArgSize = 4;
5993 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005994 case ABIArgInfo::Indirect:
5995 llvm::Value *ArgAddr;
5996 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5997 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00005998 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5999 ArgSize = 4;
6000 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006001 }
Robert Lytton2d196952013-10-11 10:29:34 +00006002
6003 // Increment the VAList.
6004 if (ArgSize) {
6005 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6006 Builder.CreateStore(APN, VAListAddrAsBPP);
6007 }
6008 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006009}
Robert Lytton0e076492013-08-13 09:43:10 +00006010
Robert Lytton844aeeb2014-05-02 09:33:20 +00006011/// During the expansion of a RecordType, an incomplete TypeString is placed
6012/// into the cache as a means to identify and break recursion.
6013/// If there is a Recursive encoding in the cache, it is swapped out and will
6014/// be reinserted by removeIncomplete().
6015/// All other types of encoding should have been used rather than arriving here.
6016void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6017 std::string StubEnc) {
6018 if (!ID)
6019 return;
6020 Entry &E = Map[ID];
6021 assert( (E.Str.empty() || E.State == Recursive) &&
6022 "Incorrectly use of addIncomplete");
6023 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6024 E.Swapped.swap(E.Str); // swap out the Recursive
6025 E.Str.swap(StubEnc);
6026 E.State = Incomplete;
6027 ++IncompleteCount;
6028}
6029
6030/// Once the RecordType has been expanded, the temporary incomplete TypeString
6031/// must be removed from the cache.
6032/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6033/// Returns true if the RecordType was defined recursively.
6034bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6035 if (!ID)
6036 return false;
6037 auto I = Map.find(ID);
6038 assert(I != Map.end() && "Entry not present");
6039 Entry &E = I->second;
6040 assert( (E.State == Incomplete ||
6041 E.State == IncompleteUsed) &&
6042 "Entry must be an incomplete type");
6043 bool IsRecursive = false;
6044 if (E.State == IncompleteUsed) {
6045 // We made use of our Incomplete encoding, thus we are recursive.
6046 IsRecursive = true;
6047 --IncompleteUsedCount;
6048 }
6049 if (E.Swapped.empty())
6050 Map.erase(I);
6051 else {
6052 // Swap the Recursive back.
6053 E.Swapped.swap(E.Str);
6054 E.Swapped.clear();
6055 E.State = Recursive;
6056 }
6057 --IncompleteCount;
6058 return IsRecursive;
6059}
6060
6061/// Add the encoded TypeString to the cache only if it is NonRecursive or
6062/// Recursive (viz: all sub-members were expanded as fully as possible).
6063void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6064 bool IsRecursive) {
6065 if (!ID || IncompleteUsedCount)
6066 return; // No key or it is is an incomplete sub-type so don't add.
6067 Entry &E = Map[ID];
6068 if (IsRecursive && !E.Str.empty()) {
6069 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6070 "This is not the same Recursive entry");
6071 // The parent container was not recursive after all, so we could have used
6072 // this Recursive sub-member entry after all, but we assumed the worse when
6073 // we started viz: IncompleteCount!=0.
6074 return;
6075 }
6076 assert(E.Str.empty() && "Entry already present");
6077 E.Str = Str.str();
6078 E.State = IsRecursive? Recursive : NonRecursive;
6079}
6080
6081/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6082/// are recursively expanding a type (IncompleteCount != 0) and the cached
6083/// encoding is Recursive, return an empty StringRef.
6084StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6085 if (!ID)
6086 return StringRef(); // We have no key.
6087 auto I = Map.find(ID);
6088 if (I == Map.end())
6089 return StringRef(); // We have no encoding.
6090 Entry &E = I->second;
6091 if (E.State == Recursive && IncompleteCount)
6092 return StringRef(); // We don't use Recursive encodings for member types.
6093
6094 if (E.State == Incomplete) {
6095 // The incomplete type is being used to break out of recursion.
6096 E.State = IncompleteUsed;
6097 ++IncompleteUsedCount;
6098 }
6099 return E.Str.c_str();
6100}
6101
6102/// The XCore ABI includes a type information section that communicates symbol
6103/// type information to the linker. The linker uses this information to verify
6104/// safety/correctness of things such as array bound and pointers et al.
6105/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6106/// This type information (TypeString) is emitted into meta data for all global
6107/// symbols: definitions, declarations, functions & variables.
6108///
6109/// The TypeString carries type, qualifier, name, size & value details.
6110/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6111/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6112/// The output is tested by test/CodeGen/xcore-stringtype.c.
6113///
6114static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6115 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6116
6117/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6118void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6119 CodeGen::CodeGenModule &CGM) const {
6120 SmallStringEnc Enc;
6121 if (getTypeString(Enc, D, CGM, TSC)) {
6122 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6123 llvm::SmallVector<llvm::Value *, 2> MDVals;
6124 MDVals.push_back(GV);
6125 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6126 llvm::NamedMDNode *MD =
6127 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6128 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6129 }
6130}
6131
6132static bool appendType(SmallStringEnc &Enc, QualType QType,
6133 const CodeGen::CodeGenModule &CGM,
6134 TypeStringCache &TSC);
6135
6136/// Helper function for appendRecordType().
6137/// Builds a SmallVector containing the encoded field types in declaration order.
6138static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6139 const RecordDecl *RD,
6140 const CodeGen::CodeGenModule &CGM,
6141 TypeStringCache &TSC) {
6142 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
6143 I != E; ++I) {
6144 SmallStringEnc Enc;
6145 Enc += "m(";
6146 Enc += I->getName();
6147 Enc += "){";
6148 if (I->isBitField()) {
6149 Enc += "b(";
6150 llvm::raw_svector_ostream OS(Enc);
6151 OS.resync();
6152 OS << I->getBitWidthValue(CGM.getContext());
6153 OS.flush();
6154 Enc += ':';
6155 }
6156 if (!appendType(Enc, I->getType(), CGM, TSC))
6157 return false;
6158 if (I->isBitField())
6159 Enc += ')';
6160 Enc += '}';
6161 FE.push_back(FieldEncoding(!I->getName().empty(), Enc));
6162 }
6163 return true;
6164}
6165
6166/// Appends structure and union types to Enc and adds encoding to cache.
6167/// Recursively calls appendType (via extractFieldType) for each field.
6168/// Union types have their fields ordered according to the ABI.
6169static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6170 const CodeGen::CodeGenModule &CGM,
6171 TypeStringCache &TSC, const IdentifierInfo *ID) {
6172 // Append the cached TypeString if we have one.
6173 StringRef TypeString = TSC.lookupStr(ID);
6174 if (!TypeString.empty()) {
6175 Enc += TypeString;
6176 return true;
6177 }
6178
6179 // Start to emit an incomplete TypeString.
6180 size_t Start = Enc.size();
6181 Enc += (RT->isUnionType()? 'u' : 's');
6182 Enc += '(';
6183 if (ID)
6184 Enc += ID->getName();
6185 Enc += "){";
6186
6187 // We collect all encoded fields and order as necessary.
6188 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006189 const RecordDecl *RD = RT->getDecl()->getDefinition();
6190 if (RD && !RD->field_empty()) {
6191 // An incomplete TypeString stub is placed in the cache for this RecordType
6192 // so that recursive calls to this RecordType will use it whilst building a
6193 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006194 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006195 std::string StubEnc(Enc.substr(Start).str());
6196 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6197 TSC.addIncomplete(ID, std::move(StubEnc));
6198 if (!extractFieldType(FE, RD, CGM, TSC)) {
6199 (void) TSC.removeIncomplete(ID);
6200 return false;
6201 }
6202 IsRecursive = TSC.removeIncomplete(ID);
6203 // The ABI requires unions to be sorted but not structures.
6204 // See FieldEncoding::operator< for sort algorithm.
6205 if (RT->isUnionType())
6206 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006207 // We can now complete the TypeString.
6208 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006209 for (unsigned I = 0; I != E; ++I) {
6210 if (I)
6211 Enc += ',';
6212 Enc += FE[I].str();
6213 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006214 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006215 Enc += '}';
6216 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6217 return true;
6218}
6219
6220/// Appends enum types to Enc and adds the encoding to the cache.
6221static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6222 TypeStringCache &TSC,
6223 const IdentifierInfo *ID) {
6224 // Append the cached TypeString if we have one.
6225 StringRef TypeString = TSC.lookupStr(ID);
6226 if (!TypeString.empty()) {
6227 Enc += TypeString;
6228 return true;
6229 }
6230
6231 size_t Start = Enc.size();
6232 Enc += "e(";
6233 if (ID)
6234 Enc += ID->getName();
6235 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006236
6237 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006238 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006239 SmallVector<FieldEncoding, 16> FE;
6240 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6241 ++I) {
6242 SmallStringEnc EnumEnc;
6243 EnumEnc += "m(";
6244 EnumEnc += I->getName();
6245 EnumEnc += "){";
6246 I->getInitVal().toString(EnumEnc);
6247 EnumEnc += '}';
6248 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6249 }
6250 std::sort(FE.begin(), FE.end());
6251 unsigned E = FE.size();
6252 for (unsigned I = 0; I != E; ++I) {
6253 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006254 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006255 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006256 }
6257 }
6258 Enc += '}';
6259 TSC.addIfComplete(ID, Enc.substr(Start), false);
6260 return true;
6261}
6262
6263/// Appends type's qualifier to Enc.
6264/// This is done prior to appending the type's encoding.
6265static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6266 // Qualifiers are emitted in alphabetical order.
6267 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6268 int Lookup = 0;
6269 if (QT.isConstQualified())
6270 Lookup += 1<<0;
6271 if (QT.isRestrictQualified())
6272 Lookup += 1<<1;
6273 if (QT.isVolatileQualified())
6274 Lookup += 1<<2;
6275 Enc += Table[Lookup];
6276}
6277
6278/// Appends built-in types to Enc.
6279static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6280 const char *EncType;
6281 switch (BT->getKind()) {
6282 case BuiltinType::Void:
6283 EncType = "0";
6284 break;
6285 case BuiltinType::Bool:
6286 EncType = "b";
6287 break;
6288 case BuiltinType::Char_U:
6289 EncType = "uc";
6290 break;
6291 case BuiltinType::UChar:
6292 EncType = "uc";
6293 break;
6294 case BuiltinType::SChar:
6295 EncType = "sc";
6296 break;
6297 case BuiltinType::UShort:
6298 EncType = "us";
6299 break;
6300 case BuiltinType::Short:
6301 EncType = "ss";
6302 break;
6303 case BuiltinType::UInt:
6304 EncType = "ui";
6305 break;
6306 case BuiltinType::Int:
6307 EncType = "si";
6308 break;
6309 case BuiltinType::ULong:
6310 EncType = "ul";
6311 break;
6312 case BuiltinType::Long:
6313 EncType = "sl";
6314 break;
6315 case BuiltinType::ULongLong:
6316 EncType = "ull";
6317 break;
6318 case BuiltinType::LongLong:
6319 EncType = "sll";
6320 break;
6321 case BuiltinType::Float:
6322 EncType = "ft";
6323 break;
6324 case BuiltinType::Double:
6325 EncType = "d";
6326 break;
6327 case BuiltinType::LongDouble:
6328 EncType = "ld";
6329 break;
6330 default:
6331 return false;
6332 }
6333 Enc += EncType;
6334 return true;
6335}
6336
6337/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6338static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6339 const CodeGen::CodeGenModule &CGM,
6340 TypeStringCache &TSC) {
6341 Enc += "p(";
6342 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6343 return false;
6344 Enc += ')';
6345 return true;
6346}
6347
6348/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006349static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6350 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006351 const CodeGen::CodeGenModule &CGM,
6352 TypeStringCache &TSC, StringRef NoSizeEnc) {
6353 if (AT->getSizeModifier() != ArrayType::Normal)
6354 return false;
6355 Enc += "a(";
6356 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6357 CAT->getSize().toStringUnsigned(Enc);
6358 else
6359 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6360 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006361 // The Qualifiers should be attached to the type rather than the array.
6362 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006363 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6364 return false;
6365 Enc += ')';
6366 return true;
6367}
6368
6369/// Appends a function encoding to Enc, calling appendType for the return type
6370/// and the arguments.
6371static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6372 const CodeGen::CodeGenModule &CGM,
6373 TypeStringCache &TSC) {
6374 Enc += "f{";
6375 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6376 return false;
6377 Enc += "}(";
6378 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6379 // N.B. we are only interested in the adjusted param types.
6380 auto I = FPT->param_type_begin();
6381 auto E = FPT->param_type_end();
6382 if (I != E) {
6383 do {
6384 if (!appendType(Enc, *I, CGM, TSC))
6385 return false;
6386 ++I;
6387 if (I != E)
6388 Enc += ',';
6389 } while (I != E);
6390 if (FPT->isVariadic())
6391 Enc += ",va";
6392 } else {
6393 if (FPT->isVariadic())
6394 Enc += "va";
6395 else
6396 Enc += '0';
6397 }
6398 }
6399 Enc += ')';
6400 return true;
6401}
6402
6403/// Handles the type's qualifier before dispatching a call to handle specific
6404/// type encodings.
6405static bool appendType(SmallStringEnc &Enc, QualType QType,
6406 const CodeGen::CodeGenModule &CGM,
6407 TypeStringCache &TSC) {
6408
6409 QualType QT = QType.getCanonicalType();
6410
Robert Lytton6adb20f2014-06-05 09:06:21 +00006411 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6412 // The Qualifiers should be attached to the type rather than the array.
6413 // Thus we don't call appendQualifier() here.
6414 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6415
Robert Lytton844aeeb2014-05-02 09:33:20 +00006416 appendQualifier(Enc, QT);
6417
6418 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6419 return appendBuiltinType(Enc, BT);
6420
Robert Lytton844aeeb2014-05-02 09:33:20 +00006421 if (const PointerType *PT = QT->getAs<PointerType>())
6422 return appendPointerType(Enc, PT, CGM, TSC);
6423
6424 if (const EnumType *ET = QT->getAs<EnumType>())
6425 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6426
6427 if (const RecordType *RT = QT->getAsStructureType())
6428 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6429
6430 if (const RecordType *RT = QT->getAsUnionType())
6431 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6432
6433 if (const FunctionType *FT = QT->getAs<FunctionType>())
6434 return appendFunctionType(Enc, FT, CGM, TSC);
6435
6436 return false;
6437}
6438
6439static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6440 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6441 if (!D)
6442 return false;
6443
6444 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6445 if (FD->getLanguageLinkage() != CLanguageLinkage)
6446 return false;
6447 return appendType(Enc, FD->getType(), CGM, TSC);
6448 }
6449
6450 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6451 if (VD->getLanguageLinkage() != CLanguageLinkage)
6452 return false;
6453 QualType QT = VD->getType().getCanonicalType();
6454 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6455 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006456 // The Qualifiers should be attached to the type rather than the array.
6457 // Thus we don't call appendQualifier() here.
6458 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00006459 }
6460 return appendType(Enc, QT, CGM, TSC);
6461 }
6462 return false;
6463}
6464
6465
Robert Lytton0e076492013-08-13 09:43:10 +00006466//===----------------------------------------------------------------------===//
6467// Driver code
6468//===----------------------------------------------------------------------===//
6469
Chris Lattner2b037972010-07-29 02:01:43 +00006470const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006471 if (TheTargetCodeGenInfo)
6472 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006473
John McCallc8e01702013-04-16 22:48:15 +00006474 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00006475 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00006476 default:
Chris Lattner2b037972010-07-29 02:01:43 +00006477 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00006478
Derek Schuff09338a22012-09-06 17:37:28 +00006479 case llvm::Triple::le32:
6480 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00006481 case llvm::Triple::mips:
6482 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006483 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
6484
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00006485 case llvm::Triple::mips64:
6486 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006487 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
6488
Tim Northover25e8a672014-05-24 12:51:25 +00006489 case llvm::Triple::aarch64:
6490 case llvm::Triple::aarch64_be:
James Molloy7f4ba532014-04-23 10:26:08 +00006491 case llvm::Triple::arm64:
6492 case llvm::Triple::arm64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00006493 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006494 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00006495 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00006496
Tim Northover573cbee2014-05-24 12:52:07 +00006497 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00006498 }
6499
Daniel Dunbard59655c2009-09-12 00:59:49 +00006500 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006501 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00006502 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006503 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006504 {
6505 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006506 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006507 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00006508 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00006509 (CodeGenOpts.FloatABI != "soft" &&
6510 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006511 Kind = ARMABIInfo::AAPCS_VFP;
6512
Derek Schuffa2020962012-10-16 22:30:41 +00006513 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00006514 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00006515 return *(TheTargetCodeGenInfo =
6516 new NaClARMTargetCodeGenInfo(Types, Kind));
6517 default:
6518 return *(TheTargetCodeGenInfo =
6519 new ARMTargetCodeGenInfo(Types, Kind));
6520 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006521 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00006522
John McCallea8d8bb2010-03-11 00:10:12 +00006523 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00006524 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00006525 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00006526 if (Triple.isOSBinFormatELF())
6527 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
6528 else
6529 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00006530 case llvm::Triple::ppc64le:
6531 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
6532 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00006533
Peter Collingbournec947aae2012-05-20 23:28:41 +00006534 case llvm::Triple::nvptx:
6535 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00006536 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006537
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006538 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00006539 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00006540
Ulrich Weigand47445072013-05-06 16:26:41 +00006541 case llvm::Triple::systemz:
6542 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
6543
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006544 case llvm::Triple::tce:
6545 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
6546
Eli Friedman33465822011-07-08 23:31:17 +00006547 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00006548 bool IsDarwinVectorABI = Triple.isOSDarwin();
6549 bool IsSmallStructInRegABI =
6550 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00006551 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00006552
John McCall1fe2a8c2013-06-18 02:46:29 +00006553 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00006554 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00006555 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00006556 IsDarwinVectorABI, IsSmallStructInRegABI,
6557 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00006558 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00006559 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006560 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00006561 new X86_32TargetCodeGenInfo(Types,
6562 IsDarwinVectorABI, IsSmallStructInRegABI,
6563 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00006564 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006565 }
Eli Friedman33465822011-07-08 23:31:17 +00006566 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006567
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006568 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00006569 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006570
Chris Lattner04dc9572010-08-31 16:44:54 +00006571 switch (Triple.getOS()) {
6572 case llvm::Triple::Win32:
Chris Lattner04dc9572010-08-31 16:44:54 +00006573 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00006574 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00006575 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
6576 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00006577 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006578 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
6579 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00006580 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00006581 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00006582 case llvm::Triple::hexagon:
6583 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006584 case llvm::Triple::sparcv9:
6585 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00006586 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006587 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006588 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006589}