blob: 4dbbc55915a44b64cf5f68ce3cac0387162bc8ef [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 Kleckner677539d2014-07-10 01:58:55 +0000960 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000961 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +0000962 } else if (FI.getReturnInfo().isIndirect()) {
963 // The C++ ABI is not aware of register usage, so we have to check if the
964 // return value was sret and put it in a register ourselves if appropriate.
965 if (State.FreeRegs) {
966 --State.FreeRegs; // The sret parameter consumes a register.
967 FI.getReturnInfo().setInReg(true);
968 }
969 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000970
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000971 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000972 for (auto &I : FI.arguments()) {
973 I.info = classifyArgumentType(I.type, State);
974 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000975 }
976
977 // If we needed to use inalloca for any argument, do a second pass and rewrite
978 // all the memory arguments to use inalloca.
979 if (UsedInAlloca)
980 rewriteWithInAlloca(FI);
981}
982
983void
984X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
985 unsigned &StackOffset,
986 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +0000987 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
988 Info = ABIArgInfo::getInAlloca(FrameFields.size());
989 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
990 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
991
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000992 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
993 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +0000994 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000995 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +0000996 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000997 unsigned NumBytes = StackOffset - OldOffset;
998 assert(NumBytes);
999 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1000 Ty = llvm::ArrayType::get(Ty, NumBytes);
1001 FrameFields.push_back(Ty);
1002 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001003}
1004
Reid Kleckner852361d2014-07-26 00:12:26 +00001005static bool isArgInAlloca(const ABIArgInfo &Info) {
1006 // Leave ignored and inreg arguments alone.
1007 switch (Info.getKind()) {
1008 case ABIArgInfo::InAlloca:
1009 return true;
1010 case ABIArgInfo::Indirect:
1011 assert(Info.getIndirectByVal());
1012 return true;
1013 case ABIArgInfo::Ignore:
1014 return false;
1015 case ABIArgInfo::Direct:
1016 case ABIArgInfo::Extend:
1017 case ABIArgInfo::Expand:
1018 if (Info.getInReg())
1019 return false;
1020 return true;
1021 }
1022 llvm_unreachable("invalid enum");
1023}
1024
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001025void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1026 assert(IsWin32StructABI && "inalloca only supported on win32");
1027
1028 // Build a packed struct type for all of the arguments in memory.
1029 SmallVector<llvm::Type *, 6> FrameFields;
1030
1031 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001032 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1033
1034 // Put 'this' into the struct before 'sret', if necessary.
1035 bool IsThisCall =
1036 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1037 ABIArgInfo &Ret = FI.getReturnInfo();
1038 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1039 isArgInAlloca(I->info)) {
1040 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1041 ++I;
1042 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001043
1044 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001045 if (Ret.isIndirect() && !Ret.getInReg()) {
1046 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1047 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001048 // On Windows, the hidden sret parameter is always returned in eax.
1049 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001050 }
1051
1052 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001053 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001054 ++I;
1055
1056 // Put arguments passed in memory into the struct.
1057 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001058 if (isArgInAlloca(I->info))
1059 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001060 }
1061
1062 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1063 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001064}
1065
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001066llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1067 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001068 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001069
1070 CGBuilderTy &Builder = CGF.Builder;
1071 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1072 "ap");
1073 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001074
1075 // Compute if the address needs to be aligned
1076 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1077 Align = getTypeStackAlignInBytes(Ty, Align);
1078 Align = std::max(Align, 4U);
1079 if (Align > 4) {
1080 // addr = (addr + align - 1) & -align;
1081 llvm::Value *Offset =
1082 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1083 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1084 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1085 CGF.Int32Ty);
1086 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1087 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1088 Addr->getType(),
1089 "ap.cur.aligned");
1090 }
1091
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001092 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001093 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001094 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1095
1096 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001097 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001098 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001099 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001100 "ap.next");
1101 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1102
1103 return AddrTyped;
1104}
1105
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001106bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1107 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1108 assert(Triple.getArch() == llvm::Triple::x86);
1109
1110 switch (Opts.getStructReturnConvention()) {
1111 case CodeGenOptions::SRCK_Default:
1112 break;
1113 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1114 return false;
1115 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1116 return true;
1117 }
1118
1119 if (Triple.isOSDarwin())
1120 return true;
1121
1122 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001123 case llvm::Triple::DragonFly:
1124 case llvm::Triple::FreeBSD:
1125 case llvm::Triple::OpenBSD:
1126 case llvm::Triple::Bitrig:
1127 return true;
1128 case llvm::Triple::Win32:
1129 switch (Triple.getEnvironment()) {
1130 case llvm::Triple::UnknownEnvironment:
1131 case llvm::Triple::Cygnus:
1132 case llvm::Triple::GNU:
1133 case llvm::Triple::MSVC:
1134 return true;
1135 default:
1136 return false;
1137 }
1138 default:
1139 return false;
1140 }
1141}
1142
Charles Davis4ea31ab2010-02-13 15:54:06 +00001143void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1144 llvm::GlobalValue *GV,
1145 CodeGen::CodeGenModule &CGM) const {
1146 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1147 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1148 // Get the LLVM function.
1149 llvm::Function *Fn = cast<llvm::Function>(GV);
1150
1151 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001152 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001153 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001154 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1155 llvm::AttributeSet::get(CGM.getLLVMContext(),
1156 llvm::AttributeSet::FunctionIndex,
1157 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001158 }
1159 }
1160}
1161
John McCallbeec5a02010-03-06 00:35:14 +00001162bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1163 CodeGen::CodeGenFunction &CGF,
1164 llvm::Value *Address) const {
1165 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001166
Chris Lattnerece04092012-02-07 00:39:47 +00001167 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001168
John McCallbeec5a02010-03-06 00:35:14 +00001169 // 0-7 are the eight integer registers; the order is different
1170 // on Darwin (for EH), but the range is the same.
1171 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001172 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001173
John McCallc8e01702013-04-16 22:48:15 +00001174 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001175 // 12-16 are st(0..4). Not sure why we stop at 4.
1176 // These have size 16, which is sizeof(long double) on
1177 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001178 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001179 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001180
John McCallbeec5a02010-03-06 00:35:14 +00001181 } else {
1182 // 9 is %eflags, which doesn't get a size on Darwin for some
1183 // reason.
1184 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1185
1186 // 11-16 are st(0..5). Not sure why we stop at 5.
1187 // These have size 12, which is sizeof(long double) on
1188 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001189 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001190 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1191 }
John McCallbeec5a02010-03-06 00:35:14 +00001192
1193 return false;
1194}
1195
Chris Lattner0cf24192010-06-28 20:05:43 +00001196//===----------------------------------------------------------------------===//
1197// X86-64 ABI Implementation
1198//===----------------------------------------------------------------------===//
1199
1200
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001201namespace {
1202/// X86_64ABIInfo - The X86_64 ABI information.
1203class X86_64ABIInfo : public ABIInfo {
1204 enum Class {
1205 Integer = 0,
1206 SSE,
1207 SSEUp,
1208 X87,
1209 X87Up,
1210 ComplexX87,
1211 NoClass,
1212 Memory
1213 };
1214
1215 /// merge - Implement the X86_64 ABI merging algorithm.
1216 ///
1217 /// Merge an accumulating classification \arg Accum with a field
1218 /// classification \arg Field.
1219 ///
1220 /// \param Accum - The accumulating classification. This should
1221 /// always be either NoClass or the result of a previous merge
1222 /// call. In addition, this should never be Memory (the caller
1223 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001224 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001225
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001226 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1227 ///
1228 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1229 /// final MEMORY or SSE classes when necessary.
1230 ///
1231 /// \param AggregateSize - The size of the current aggregate in
1232 /// the classification process.
1233 ///
1234 /// \param Lo - The classification for the parts of the type
1235 /// residing in the low word of the containing object.
1236 ///
1237 /// \param Hi - The classification for the parts of the type
1238 /// residing in the higher words of the containing object.
1239 ///
1240 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1241
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001242 /// classify - Determine the x86_64 register classes in which the
1243 /// given type T should be passed.
1244 ///
1245 /// \param Lo - The classification for the parts of the type
1246 /// residing in the low word of the containing object.
1247 ///
1248 /// \param Hi - The classification for the parts of the type
1249 /// residing in the high word of the containing object.
1250 ///
1251 /// \param OffsetBase - The bit offset of this type in the
1252 /// containing object. Some parameters are classified different
1253 /// depending on whether they straddle an eightbyte boundary.
1254 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001255 /// \param isNamedArg - Whether the argument in question is a "named"
1256 /// argument, as used in AMD64-ABI 3.5.7.
1257 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001258 /// If a word is unused its result will be NoClass; if a type should
1259 /// be passed in Memory then at least the classification of \arg Lo
1260 /// will be Memory.
1261 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001262 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001263 ///
1264 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1265 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001266 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1267 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001268
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001269 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001270 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1271 unsigned IROffset, QualType SourceTy,
1272 unsigned SourceOffset) const;
1273 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1274 unsigned IROffset, QualType SourceTy,
1275 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001276
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001277 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001278 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001279 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001280
1281 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001282 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001283 ///
1284 /// \param freeIntRegs - The number of free integer registers remaining
1285 /// available.
1286 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001287
Chris Lattner458b2aa2010-07-29 02:16:43 +00001288 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001289
Bill Wendling5cd41c42010-10-18 03:41:31 +00001290 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001291 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001292 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001293 unsigned &neededSSE,
1294 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001295
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001296 bool IsIllegalVectorType(QualType Ty) const;
1297
John McCalle0fda732011-04-21 01:20:55 +00001298 /// The 0.98 ABI revision clarified a lot of ambiguities,
1299 /// unfortunately in ways that were not always consistent with
1300 /// certain previous compilers. In particular, platforms which
1301 /// required strict binary compatibility with older versions of GCC
1302 /// may need to exempt themselves.
1303 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001304 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001305 }
1306
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001307 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001308 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1309 // 64-bit hardware.
1310 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001311
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001312public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001313 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001314 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001315 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001316 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001317
John McCalla729c622012-02-17 03:33:10 +00001318 bool isPassedUsingAVXType(QualType type) const {
1319 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001320 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001321 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1322 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001323 if (info.isDirect()) {
1324 llvm::Type *ty = info.getCoerceToType();
1325 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1326 return (vectorTy->getBitWidth() > 128);
1327 }
1328 return false;
1329 }
1330
Craig Topper4f12f102014-03-12 06:41:41 +00001331 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001332
Craig Topper4f12f102014-03-12 06:41:41 +00001333 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1334 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001335};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001336
Chris Lattner04dc9572010-08-31 16:44:54 +00001337/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001338class WinX86_64ABIInfo : public ABIInfo {
1339
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001340 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001341
Chris Lattner04dc9572010-08-31 16:44:54 +00001342public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001343 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1344
Craig Topper4f12f102014-03-12 06:41:41 +00001345 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001346
Craig Topper4f12f102014-03-12 06:41:41 +00001347 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1348 CodeGenFunction &CGF) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001349};
1350
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001351class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1352public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001353 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001354 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001355
John McCalla729c622012-02-17 03:33:10 +00001356 const X86_64ABIInfo &getABIInfo() const {
1357 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1358 }
1359
Craig Topper4f12f102014-03-12 06:41:41 +00001360 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001361 return 7;
1362 }
1363
1364 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001365 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001366 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001367
John McCall943fae92010-05-27 06:19:26 +00001368 // 0-15 are the 16 integer registers.
1369 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001370 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001371 return false;
1372 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001373
Jay Foad7c57be32011-07-11 09:56:20 +00001374 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001375 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001376 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001377 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1378 }
1379
John McCalla729c622012-02-17 03:33:10 +00001380 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001381 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001382 // The default CC on x86-64 sets %al to the number of SSA
1383 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001384 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001385 // that when AVX types are involved: the ABI explicitly states it is
1386 // undefined, and it doesn't work in practice because of how the ABI
1387 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001388 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001389 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001390 for (CallArgList::const_iterator
1391 it = args.begin(), ie = args.end(); it != ie; ++it) {
1392 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1393 HasAVXType = true;
1394 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001395 }
1396 }
John McCalla729c622012-02-17 03:33:10 +00001397
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001398 if (!HasAVXType)
1399 return true;
1400 }
John McCallcbc038a2011-09-21 08:08:30 +00001401
John McCalla729c622012-02-17 03:33:10 +00001402 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001403 }
1404
Craig Topper4f12f102014-03-12 06:41:41 +00001405 llvm::Constant *
1406 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001407 unsigned Sig = (0xeb << 0) | // jmp rel8
1408 (0x0a << 8) | // .+0x0c
1409 ('F' << 16) |
1410 ('T' << 24);
1411 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1412 }
1413
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001414};
1415
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001416static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1417 // If the argument does not end in .lib, automatically add the suffix. This
1418 // matches the behavior of MSVC.
1419 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001420 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001421 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001422 return ArgStr;
1423}
1424
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001425class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1426public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001427 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1428 bool d, bool p, bool w, unsigned RegParms)
1429 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001430
1431 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001432 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001433 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001434 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001435 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001436
1437 void getDetectMismatchOption(llvm::StringRef Name,
1438 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001439 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001440 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001441 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001442};
1443
Chris Lattner04dc9572010-08-31 16:44:54 +00001444class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1445public:
1446 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1447 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1448
Craig Topper4f12f102014-03-12 06:41:41 +00001449 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001450 return 7;
1451 }
1452
1453 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001454 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001455 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001456
Chris Lattner04dc9572010-08-31 16:44:54 +00001457 // 0-15 are the 16 integer registers.
1458 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001459 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001460 return false;
1461 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001462
1463 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001464 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001465 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001466 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001467 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001468
1469 void getDetectMismatchOption(llvm::StringRef Name,
1470 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001471 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001472 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001473 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001474};
1475
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001476}
1477
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001478void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1479 Class &Hi) const {
1480 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1481 //
1482 // (a) If one of the classes is Memory, the whole argument is passed in
1483 // memory.
1484 //
1485 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1486 // memory.
1487 //
1488 // (c) If the size of the aggregate exceeds two eightbytes and the first
1489 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1490 // argument is passed in memory. NOTE: This is necessary to keep the
1491 // ABI working for processors that don't support the __m256 type.
1492 //
1493 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1494 //
1495 // Some of these are enforced by the merging logic. Others can arise
1496 // only with unions; for example:
1497 // union { _Complex double; unsigned; }
1498 //
1499 // Note that clauses (b) and (c) were added in 0.98.
1500 //
1501 if (Hi == Memory)
1502 Lo = Memory;
1503 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1504 Lo = Memory;
1505 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1506 Lo = Memory;
1507 if (Hi == SSEUp && Lo != SSE)
1508 Hi = SSE;
1509}
1510
Chris Lattnerd776fb12010-06-28 21:43:59 +00001511X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001512 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1513 // classified recursively so that always two fields are
1514 // considered. The resulting class is calculated according to
1515 // the classes of the fields in the eightbyte:
1516 //
1517 // (a) If both classes are equal, this is the resulting class.
1518 //
1519 // (b) If one of the classes is NO_CLASS, the resulting class is
1520 // the other class.
1521 //
1522 // (c) If one of the classes is MEMORY, the result is the MEMORY
1523 // class.
1524 //
1525 // (d) If one of the classes is INTEGER, the result is the
1526 // INTEGER.
1527 //
1528 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1529 // MEMORY is used as class.
1530 //
1531 // (f) Otherwise class SSE is used.
1532
1533 // Accum should never be memory (we should have returned) or
1534 // ComplexX87 (because this cannot be passed in a structure).
1535 assert((Accum != Memory && Accum != ComplexX87) &&
1536 "Invalid accumulated classification during merge.");
1537 if (Accum == Field || Field == NoClass)
1538 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001539 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001540 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001541 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001542 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001543 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001544 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001545 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1546 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001547 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001548 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001549}
1550
Chris Lattner5c740f12010-06-30 19:14:05 +00001551void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001552 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001553 // FIXME: This code can be simplified by introducing a simple value class for
1554 // Class pairs with appropriate constructor methods for the various
1555 // situations.
1556
1557 // FIXME: Some of the split computations are wrong; unaligned vectors
1558 // shouldn't be passed in registers for example, so there is no chance they
1559 // can straddle an eightbyte. Verify & simplify.
1560
1561 Lo = Hi = NoClass;
1562
1563 Class &Current = OffsetBase < 64 ? Lo : Hi;
1564 Current = Memory;
1565
John McCall9dd450b2009-09-21 23:43:11 +00001566 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001567 BuiltinType::Kind k = BT->getKind();
1568
1569 if (k == BuiltinType::Void) {
1570 Current = NoClass;
1571 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1572 Lo = Integer;
1573 Hi = Integer;
1574 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1575 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001576 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1577 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001578 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001579 Current = SSE;
1580 } else if (k == BuiltinType::LongDouble) {
1581 Lo = X87;
1582 Hi = X87Up;
1583 }
1584 // FIXME: _Decimal32 and _Decimal64 are SSE.
1585 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001586 return;
1587 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001588
Chris Lattnerd776fb12010-06-28 21:43:59 +00001589 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001590 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001591 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001592 return;
1593 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001594
Chris Lattnerd776fb12010-06-28 21:43:59 +00001595 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001596 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001597 return;
1598 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001599
Chris Lattnerd776fb12010-06-28 21:43:59 +00001600 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001601 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001602 Lo = Hi = Integer;
1603 else
1604 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001605 return;
1606 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001607
Chris Lattnerd776fb12010-06-28 21:43:59 +00001608 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001609 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001610 if (Size == 32) {
1611 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1612 // float> as integer.
1613 Current = Integer;
1614
1615 // If this type crosses an eightbyte boundary, it should be
1616 // split.
1617 uint64_t EB_Real = (OffsetBase) / 64;
1618 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1619 if (EB_Real != EB_Imag)
1620 Hi = Lo;
1621 } else if (Size == 64) {
1622 // gcc passes <1 x double> in memory. :(
1623 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1624 return;
1625
1626 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001627 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001628 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1629 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1630 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001631 Current = Integer;
1632 else
1633 Current = SSE;
1634
1635 // If this type crosses an eightbyte boundary, it should be
1636 // split.
1637 if (OffsetBase && OffsetBase != 64)
1638 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001639 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001640 // Arguments of 256-bits are split into four eightbyte chunks. The
1641 // least significant one belongs to class SSE and all the others to class
1642 // SSEUP. The original Lo and Hi design considers that types can't be
1643 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1644 // This design isn't correct for 256-bits, but since there're no cases
1645 // where the upper parts would need to be inspected, avoid adding
1646 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001647 //
1648 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1649 // registers if they are "named", i.e. not part of the "..." of a
1650 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001651 Lo = SSE;
1652 Hi = SSEUp;
1653 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001654 return;
1655 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001656
Chris Lattnerd776fb12010-06-28 21:43:59 +00001657 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001658 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001659
Chris Lattner2b037972010-07-29 02:01:43 +00001660 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001661 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001662 if (Size <= 64)
1663 Current = Integer;
1664 else if (Size <= 128)
1665 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001666 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001667 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001668 else if (ET == getContext().DoubleTy ||
1669 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001670 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001671 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001672 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001673 Current = ComplexX87;
1674
1675 // If this complex type crosses an eightbyte boundary then it
1676 // should be split.
1677 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001678 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001679 if (Hi == NoClass && EB_Real != EB_Imag)
1680 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001681
Chris Lattnerd776fb12010-06-28 21:43:59 +00001682 return;
1683 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001684
Chris Lattner2b037972010-07-29 02:01:43 +00001685 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001686 // Arrays are treated like structures.
1687
Chris Lattner2b037972010-07-29 02:01:43 +00001688 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001689
1690 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001691 // than four eightbytes, ..., it has class MEMORY.
1692 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001693 return;
1694
1695 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1696 // fields, it has class MEMORY.
1697 //
1698 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001699 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001700 return;
1701
1702 // Otherwise implement simplified merge. We could be smarter about
1703 // this, but it isn't worth it and would be harder to verify.
1704 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001705 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001706 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001707
1708 // The only case a 256-bit wide vector could be used is when the array
1709 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1710 // to work for sizes wider than 128, early check and fallback to memory.
1711 if (Size > 128 && EltSize != 256)
1712 return;
1713
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001714 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1715 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001716 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001717 Lo = merge(Lo, FieldLo);
1718 Hi = merge(Hi, FieldHi);
1719 if (Lo == Memory || Hi == Memory)
1720 break;
1721 }
1722
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001723 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001724 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001725 return;
1726 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001727
Chris Lattnerd776fb12010-06-28 21:43:59 +00001728 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001729 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001730
1731 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001732 // than four eightbytes, ..., it has class MEMORY.
1733 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001734 return;
1735
Anders Carlsson20759ad2009-09-16 15:53:40 +00001736 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1737 // copy constructor or a non-trivial destructor, it is passed by invisible
1738 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001739 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001740 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001741
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001742 const RecordDecl *RD = RT->getDecl();
1743
1744 // Assume variable sized types are passed in memory.
1745 if (RD->hasFlexibleArrayMember())
1746 return;
1747
Chris Lattner2b037972010-07-29 02:01:43 +00001748 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001749
1750 // Reset Lo class, this will be recomputed.
1751 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001752
1753 // If this is a C++ record, classify the bases first.
1754 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001755 for (const auto &I : CXXRD->bases()) {
1756 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001757 "Unexpected base class!");
1758 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001759 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001760
1761 // Classify this field.
1762 //
1763 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1764 // single eightbyte, each is classified separately. Each eightbyte gets
1765 // initialized to class NO_CLASS.
1766 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001767 uint64_t Offset =
1768 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001769 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001770 Lo = merge(Lo, FieldLo);
1771 Hi = merge(Hi, FieldHi);
1772 if (Lo == Memory || Hi == Memory)
1773 break;
1774 }
1775 }
1776
1777 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001778 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001779 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001780 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001781 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1782 bool BitField = i->isBitField();
1783
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001784 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1785 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001786 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001787 // The only case a 256-bit wide vector could be used is when the struct
1788 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1789 // to work for sizes wider than 128, early check and fallback to memory.
1790 //
1791 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1792 Lo = Memory;
1793 return;
1794 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001795 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001796 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001797 Lo = Memory;
1798 return;
1799 }
1800
1801 // Classify this field.
1802 //
1803 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1804 // exceeds a single eightbyte, each is classified
1805 // separately. Each eightbyte gets initialized to class
1806 // NO_CLASS.
1807 Class FieldLo, FieldHi;
1808
1809 // Bit-fields require special handling, they do not force the
1810 // structure to be passed in memory even if unaligned, and
1811 // therefore they can straddle an eightbyte.
1812 if (BitField) {
1813 // Ignore padding bit-fields.
1814 if (i->isUnnamedBitfield())
1815 continue;
1816
1817 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001818 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001819
1820 uint64_t EB_Lo = Offset / 64;
1821 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001822
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001823 if (EB_Lo) {
1824 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1825 FieldLo = NoClass;
1826 FieldHi = Integer;
1827 } else {
1828 FieldLo = Integer;
1829 FieldHi = EB_Hi ? Integer : NoClass;
1830 }
1831 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001832 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001833 Lo = merge(Lo, FieldLo);
1834 Hi = merge(Hi, FieldHi);
1835 if (Lo == Memory || Hi == Memory)
1836 break;
1837 }
1838
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001839 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001840 }
1841}
1842
Chris Lattner22a931e2010-06-29 06:01:59 +00001843ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001844 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1845 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001846 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001847 // Treat an enum type as its underlying type.
1848 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1849 Ty = EnumTy->getDecl()->getIntegerType();
1850
1851 return (Ty->isPromotableIntegerType() ?
1852 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1853 }
1854
1855 return ABIArgInfo::getIndirect(0);
1856}
1857
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001858bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1859 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1860 uint64_t Size = getContext().getTypeSize(VecTy);
1861 unsigned LargestVector = HasAVX ? 256 : 128;
1862 if (Size <= 64 || Size > LargestVector)
1863 return true;
1864 }
1865
1866 return false;
1867}
1868
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001869ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1870 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001871 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1872 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001873 //
1874 // This assumption is optimistic, as there could be free registers available
1875 // when we need to pass this argument in memory, and LLVM could try to pass
1876 // the argument in the free register. This does not seem to happen currently,
1877 // but this code would be much safer if we could mark the argument with
1878 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001879 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001880 // Treat an enum type as its underlying type.
1881 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1882 Ty = EnumTy->getDecl()->getIntegerType();
1883
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001884 return (Ty->isPromotableIntegerType() ?
1885 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001886 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001887
Mark Lacey3825e832013-10-06 01:33:34 +00001888 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001889 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001890
Chris Lattner44c2b902011-05-22 23:21:23 +00001891 // Compute the byval alignment. We specify the alignment of the byval in all
1892 // cases so that the mid-level optimizer knows the alignment of the byval.
1893 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001894
1895 // Attempt to avoid passing indirect results using byval when possible. This
1896 // is important for good codegen.
1897 //
1898 // We do this by coercing the value into a scalar type which the backend can
1899 // handle naturally (i.e., without using byval).
1900 //
1901 // For simplicity, we currently only do this when we have exhausted all of the
1902 // free integer registers. Doing this when there are free integer registers
1903 // would require more care, as we would have to ensure that the coerced value
1904 // did not claim the unused register. That would require either reording the
1905 // arguments to the function (so that any subsequent inreg values came first),
1906 // or only doing this optimization when there were no following arguments that
1907 // might be inreg.
1908 //
1909 // We currently expect it to be rare (particularly in well written code) for
1910 // arguments to be passed on the stack when there are still free integer
1911 // registers available (this would typically imply large structs being passed
1912 // by value), so this seems like a fair tradeoff for now.
1913 //
1914 // We can revisit this if the backend grows support for 'onstack' parameter
1915 // attributes. See PR12193.
1916 if (freeIntRegs == 0) {
1917 uint64_t Size = getContext().getTypeSize(Ty);
1918
1919 // If this type fits in an eightbyte, coerce it into the matching integral
1920 // type, which will end up on the stack (with alignment 8).
1921 if (Align == 8 && Size <= 64)
1922 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1923 Size));
1924 }
1925
Chris Lattner44c2b902011-05-22 23:21:23 +00001926 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001927}
1928
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001929/// GetByteVectorType - The ABI specifies that a value should be passed in an
1930/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00001931/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001932llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001933 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001934
Chris Lattner9fa15c32010-07-29 05:02:29 +00001935 // Wrapper structs that just contain vectors are passed just like vectors,
1936 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001937 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00001938 while (STy && STy->getNumElements() == 1) {
1939 IRType = STy->getElementType(0);
1940 STy = dyn_cast<llvm::StructType>(IRType);
1941 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001942
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001943 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001944 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1945 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001946 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001947 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00001948 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1949 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1950 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1951 EltTy->isIntegerTy(128)))
1952 return VT;
1953 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001954
Chris Lattner4200fe42010-07-29 04:56:46 +00001955 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1956}
1957
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001958/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1959/// is known to either be off the end of the specified type or being in
1960/// alignment padding. The user type specified is known to be at most 128 bits
1961/// in size, and have passed through X86_64ABIInfo::classify with a successful
1962/// classification that put one of the two halves in the INTEGER class.
1963///
1964/// It is conservatively correct to return false.
1965static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1966 unsigned EndBit, ASTContext &Context) {
1967 // If the bytes being queried are off the end of the type, there is no user
1968 // data hiding here. This handles analysis of builtins, vectors and other
1969 // types that don't contain interesting padding.
1970 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1971 if (TySize <= StartBit)
1972 return true;
1973
Chris Lattner98076a22010-07-29 07:43:55 +00001974 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1975 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1976 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1977
1978 // Check each element to see if the element overlaps with the queried range.
1979 for (unsigned i = 0; i != NumElts; ++i) {
1980 // If the element is after the span we care about, then we're done..
1981 unsigned EltOffset = i*EltSize;
1982 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001983
Chris Lattner98076a22010-07-29 07:43:55 +00001984 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1985 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1986 EndBit-EltOffset, Context))
1987 return false;
1988 }
1989 // If it overlaps no elements, then it is safe to process as padding.
1990 return true;
1991 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001992
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001993 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1994 const RecordDecl *RD = RT->getDecl();
1995 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001996
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001997 // If this is a C++ record, check the bases first.
1998 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001999 for (const auto &I : CXXRD->bases()) {
2000 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002001 "Unexpected base class!");
2002 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002003 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002004
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002005 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002006 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002007 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002008
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002009 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002010 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002011 EndBit-BaseOffset, Context))
2012 return false;
2013 }
2014 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002015
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002016 // Verify that no field has data that overlaps the region of interest. Yes
2017 // this could be sped up a lot by being smarter about queried fields,
2018 // however we're only looking at structs up to 16 bytes, so we don't care
2019 // much.
2020 unsigned idx = 0;
2021 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2022 i != e; ++i, ++idx) {
2023 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002024
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002025 // If we found a field after the region we care about, then we're done.
2026 if (FieldOffset >= EndBit) break;
2027
2028 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2029 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2030 Context))
2031 return false;
2032 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002033
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002034 // If nothing in this record overlapped the area of interest, then we're
2035 // clean.
2036 return true;
2037 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002038
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002039 return false;
2040}
2041
Chris Lattnere556a712010-07-29 18:39:32 +00002042/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2043/// float member at the specified offset. For example, {int,{float}} has a
2044/// float at offset 4. It is conservatively correct for this routine to return
2045/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002046static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002047 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002048 // Base case if we find a float.
2049 if (IROffset == 0 && IRType->isFloatTy())
2050 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002051
Chris Lattnere556a712010-07-29 18:39:32 +00002052 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002053 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002054 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2055 unsigned Elt = SL->getElementContainingOffset(IROffset);
2056 IROffset -= SL->getElementOffset(Elt);
2057 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2058 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002059
Chris Lattnere556a712010-07-29 18:39:32 +00002060 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002061 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2062 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002063 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2064 IROffset -= IROffset/EltSize*EltSize;
2065 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2066 }
2067
2068 return false;
2069}
2070
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002071
2072/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2073/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002074llvm::Type *X86_64ABIInfo::
2075GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002076 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002077 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002078 // pass as float if the last 4 bytes is just padding. This happens for
2079 // structs that contain 3 floats.
2080 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2081 SourceOffset*8+64, getContext()))
2082 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002083
Chris Lattnere556a712010-07-29 18:39:32 +00002084 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2085 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2086 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002087 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2088 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002089 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002090
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002091 return llvm::Type::getDoubleTy(getVMContext());
2092}
2093
2094
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002095/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2096/// an 8-byte GPR. This means that we either have a scalar or we are talking
2097/// about the high or low part of an up-to-16-byte struct. This routine picks
2098/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002099/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2100/// etc).
2101///
2102/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2103/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2104/// the 8-byte value references. PrefType may be null.
2105///
Alp Toker9907f082014-07-09 14:06:35 +00002106/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002107/// an offset into this that we're processing (which is always either 0 or 8).
2108///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002109llvm::Type *X86_64ABIInfo::
2110GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002111 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002112 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2113 // returning an 8-byte unit starting with it. See if we can safely use it.
2114 if (IROffset == 0) {
2115 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002116 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2117 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002118 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002119
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002120 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2121 // goodness in the source type is just tail padding. This is allowed to
2122 // kick in for struct {double,int} on the int, but not on
2123 // struct{double,int,int} because we wouldn't return the second int. We
2124 // have to do this analysis on the source type because we can't depend on
2125 // unions being lowered a specific way etc.
2126 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002127 IRType->isIntegerTy(32) ||
2128 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2129 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2130 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002131
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002132 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2133 SourceOffset*8+64, getContext()))
2134 return IRType;
2135 }
2136 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002137
Chris Lattner2192fe52011-07-18 04:24:23 +00002138 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002139 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002140 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002141 if (IROffset < SL->getSizeInBytes()) {
2142 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2143 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002144
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002145 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2146 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002147 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002148 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002149
Chris Lattner2192fe52011-07-18 04:24:23 +00002150 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002151 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002152 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002153 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002154 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2155 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002156 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002157
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002158 // Okay, we don't have any better idea of what to pass, so we pass this in an
2159 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002160 unsigned TySizeInBytes =
2161 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002162
Chris Lattner3f763422010-07-29 17:34:39 +00002163 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002164
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002165 // It is always safe to classify this as an integer type up to i64 that
2166 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002167 return llvm::IntegerType::get(getVMContext(),
2168 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002169}
2170
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002171
2172/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2173/// be used as elements of a two register pair to pass or return, return a
2174/// first class aggregate to represent them. For example, if the low part of
2175/// a by-value argument should be passed as i32* and the high part as float,
2176/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002177static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002178GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002179 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002180 // In order to correctly satisfy the ABI, we need to the high part to start
2181 // at offset 8. If the high and low parts we inferred are both 4-byte types
2182 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2183 // the second element at offset 8. Check for this:
2184 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2185 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002186 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002187 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002188
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002189 // To handle this, we have to increase the size of the low part so that the
2190 // second element will start at an 8 byte offset. We can't increase the size
2191 // of the second element because it might make us access off the end of the
2192 // struct.
2193 if (HiStart != 8) {
2194 // There are only two sorts of types the ABI generation code can produce for
2195 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2196 // Promote these to a larger type.
2197 if (Lo->isFloatTy())
2198 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2199 else {
2200 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2201 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2202 }
2203 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002204
Chris Lattnera5f58b02011-07-09 17:41:47 +00002205 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002206
2207
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002208 // Verify that the second element is at an 8-byte offset.
2209 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2210 "Invalid x86-64 argument pair!");
2211 return Result;
2212}
2213
Chris Lattner31faff52010-07-28 23:06:14 +00002214ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002215classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002216 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2217 // classification algorithm.
2218 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002219 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002220
2221 // Check some invariants.
2222 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002223 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2224
Craig Topper8a13c412014-05-21 05:09:00 +00002225 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002226 switch (Lo) {
2227 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002228 if (Hi == NoClass)
2229 return ABIArgInfo::getIgnore();
2230 // If the low part is just padding, it takes no register, leave ResType
2231 // null.
2232 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2233 "Unknown missing lo part");
2234 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002235
2236 case SSEUp:
2237 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002238 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002239
2240 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2241 // hidden argument.
2242 case Memory:
2243 return getIndirectReturnResult(RetTy);
2244
2245 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2246 // available register of the sequence %rax, %rdx is used.
2247 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002248 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002249
Chris Lattner1f3a0632010-07-29 21:42:50 +00002250 // If we have a sign or zero extended integer, make sure to return Extend
2251 // so that the parameter gets the right LLVM IR attributes.
2252 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2253 // Treat an enum type as its underlying type.
2254 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2255 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002256
Chris Lattner1f3a0632010-07-29 21:42:50 +00002257 if (RetTy->isIntegralOrEnumerationType() &&
2258 RetTy->isPromotableIntegerType())
2259 return ABIArgInfo::getExtend();
2260 }
Chris Lattner31faff52010-07-28 23:06:14 +00002261 break;
2262
2263 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2264 // available SSE register of the sequence %xmm0, %xmm1 is used.
2265 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002266 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002267 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002268
2269 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2270 // returned on the X87 stack in %st0 as 80-bit x87 number.
2271 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002272 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002273 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002274
2275 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2276 // part of the value is returned in %st0 and the imaginary part in
2277 // %st1.
2278 case ComplexX87:
2279 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002280 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002281 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002282 NULL);
2283 break;
2284 }
2285
Craig Topper8a13c412014-05-21 05:09:00 +00002286 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002287 switch (Hi) {
2288 // Memory was handled previously and X87 should
2289 // never occur as a hi class.
2290 case Memory:
2291 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002292 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002293
2294 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002295 case NoClass:
2296 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002297
Chris Lattner52b3c132010-09-01 00:20:33 +00002298 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002299 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002300 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2301 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002302 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002303 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002304 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002305 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2306 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002307 break;
2308
2309 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002310 // is passed in the next available eightbyte chunk if the last used
2311 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002312 //
Chris Lattner57540c52011-04-15 05:22:18 +00002313 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002314 case SSEUp:
2315 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002316 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002317 break;
2318
2319 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2320 // returned together with the previous X87 value in %st0.
2321 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002322 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002323 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002324 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002325 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002326 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002327 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002328 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2329 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002330 }
Chris Lattner31faff52010-07-28 23:06:14 +00002331 break;
2332 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002333
Chris Lattner52b3c132010-09-01 00:20:33 +00002334 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002335 // known to pass in the high eightbyte of the result. We do this by forming a
2336 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002337 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002338 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002339
Chris Lattner1f3a0632010-07-29 21:42:50 +00002340 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002341}
2342
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002343ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002344 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2345 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002346 const
2347{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002348 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002349 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002350
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002351 // Check some invariants.
2352 // FIXME: Enforce these by construction.
2353 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002354 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2355
2356 neededInt = 0;
2357 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002358 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002359 switch (Lo) {
2360 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002361 if (Hi == NoClass)
2362 return ABIArgInfo::getIgnore();
2363 // If the low part is just padding, it takes no register, leave ResType
2364 // null.
2365 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2366 "Unknown missing lo part");
2367 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002368
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002369 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2370 // on the stack.
2371 case Memory:
2372
2373 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2374 // COMPLEX_X87, it is passed in memory.
2375 case X87:
2376 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002377 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002378 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002379 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002380
2381 case SSEUp:
2382 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002383 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002384
2385 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2386 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2387 // and %r9 is used.
2388 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002389 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002390
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002391 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002392 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002393
2394 // If we have a sign or zero extended integer, make sure to return Extend
2395 // so that the parameter gets the right LLVM IR attributes.
2396 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2397 // Treat an enum type as its underlying type.
2398 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2399 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002400
Chris Lattner1f3a0632010-07-29 21:42:50 +00002401 if (Ty->isIntegralOrEnumerationType() &&
2402 Ty->isPromotableIntegerType())
2403 return ABIArgInfo::getExtend();
2404 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002405
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002406 break;
2407
2408 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2409 // available SSE register is used, the registers are taken in the
2410 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002411 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002412 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002413 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002414 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002415 break;
2416 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002417 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002418
Craig Topper8a13c412014-05-21 05:09:00 +00002419 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002420 switch (Hi) {
2421 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002422 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002423 // which is passed in memory.
2424 case Memory:
2425 case X87:
2426 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002427 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002428
2429 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002430
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002431 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002432 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002433 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002434 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002435
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002436 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2437 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002438 break;
2439
2440 // X87Up generally doesn't occur here (long double is passed in
2441 // memory), except in situations involving unions.
2442 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002443 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002444 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002445
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002446 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2447 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002448
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002449 ++neededSSE;
2450 break;
2451
2452 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2453 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002454 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002455 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002456 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002457 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002458 break;
2459 }
2460
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002461 // If a high part was specified, merge it together with the low part. It is
2462 // known to pass in the high eightbyte of the result. We do this by forming a
2463 // first class struct aggregate with the high and low part: {low, high}
2464 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002465 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002466
Chris Lattner1f3a0632010-07-29 21:42:50 +00002467 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002468}
2469
Chris Lattner22326a12010-07-29 02:31:05 +00002470void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002471
Reid Kleckner40ca9132014-05-13 22:05:45 +00002472 if (!getCXXABI().classifyReturnType(FI))
2473 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002474
2475 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002476 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002477
2478 // If the return value is indirect, then the hidden argument is consuming one
2479 // integer register.
2480 if (FI.getReturnInfo().isIndirect())
2481 --freeIntRegs;
2482
Eli Friedman96fd2642013-06-12 00:13:45 +00002483 bool isVariadic = FI.isVariadic();
2484 unsigned numRequiredArgs = 0;
2485 if (isVariadic)
2486 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2487
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002488 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2489 // get assigned (in left-to-right order) for passing as follows...
2490 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2491 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002492 bool isNamedArg = true;
2493 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002494 isNamedArg = (it - FI.arg_begin()) <
2495 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002496
Bill Wendling9987c0e2010-10-18 23:51:38 +00002497 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002498 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002499 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002500
2501 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2502 // eightbyte of an argument, the whole argument is passed on the
2503 // stack. If registers have already been assigned for some
2504 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002505 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002506 freeIntRegs -= neededInt;
2507 freeSSERegs -= neededSSE;
2508 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002509 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002510 }
2511 }
2512}
2513
2514static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2515 QualType Ty,
2516 CodeGenFunction &CGF) {
2517 llvm::Value *overflow_arg_area_p =
2518 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2519 llvm::Value *overflow_arg_area =
2520 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2521
2522 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2523 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002524 // It isn't stated explicitly in the standard, but in practice we use
2525 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002526 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2527 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002528 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002529 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002530 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002531 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2532 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002533 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002534 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002535 overflow_arg_area =
2536 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2537 overflow_arg_area->getType(),
2538 "overflow_arg_area.align");
2539 }
2540
2541 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002542 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002543 llvm::Value *Res =
2544 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002545 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002546
2547 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2548 // l->overflow_arg_area + sizeof(type).
2549 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2550 // an 8 byte boundary.
2551
2552 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002553 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002554 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2556 "overflow_arg_area.next");
2557 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2558
2559 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2560 return Res;
2561}
2562
2563llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2564 CodeGenFunction &CGF) const {
2565 // Assume that va_list type is correct; should be pointer to LLVM type:
2566 // struct {
2567 // i32 gp_offset;
2568 // i32 fp_offset;
2569 // i8* overflow_arg_area;
2570 // i8* reg_save_area;
2571 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002572 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002573
Chris Lattner9723d6c2010-03-11 18:19:55 +00002574 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002575 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2576 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002577
2578 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2579 // in the registers. If not go to step 7.
2580 if (!neededInt && !neededSSE)
2581 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2582
2583 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2584 // general purpose registers needed to pass type and num_fp to hold
2585 // the number of floating point registers needed.
2586
2587 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2588 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2589 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2590 //
2591 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2592 // register save space).
2593
Craig Topper8a13c412014-05-21 05:09:00 +00002594 llvm::Value *InRegs = nullptr;
2595 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2596 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002597 if (neededInt) {
2598 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2599 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002600 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2601 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002602 }
2603
2604 if (neededSSE) {
2605 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2606 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2607 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002608 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2609 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002610 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2611 }
2612
2613 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2614 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2615 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2616 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2617
2618 // Emit code to load the value if it was passed in registers.
2619
2620 CGF.EmitBlock(InRegBlock);
2621
2622 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2623 // an offset of l->gp_offset and/or l->fp_offset. This may require
2624 // copying to a temporary location in case the parameter is passed
2625 // in different register classes or requires an alignment greater
2626 // than 8 for general purpose registers and 16 for XMM registers.
2627 //
2628 // FIXME: This really results in shameful code when we end up needing to
2629 // collect arguments from different places; often what should result in a
2630 // simple assembling of a structure from scattered addresses has many more
2631 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002632 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002633 llvm::Value *RegAddr =
2634 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2635 "reg_save_area");
2636 if (neededInt && neededSSE) {
2637 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002638 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002639 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002640 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2641 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002642 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002643 llvm::Type *TyLo = ST->getElementType(0);
2644 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002645 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002646 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002647 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2648 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002649 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2650 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002651 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2652 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002653 llvm::Value *V =
2654 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2655 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2656 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2657 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2658
Owen Anderson170229f2009-07-14 23:10:40 +00002659 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002660 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661 } else if (neededInt) {
2662 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2663 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002664 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002665
2666 // Copy to a temporary if necessary to ensure the appropriate alignment.
2667 std::pair<CharUnits, CharUnits> SizeAlign =
2668 CGF.getContext().getTypeInfoInChars(Ty);
2669 uint64_t TySize = SizeAlign.first.getQuantity();
2670 unsigned TyAlign = SizeAlign.second.getQuantity();
2671 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002672 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2673 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2674 RegAddr = Tmp;
2675 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002676 } else if (neededSSE == 1) {
2677 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2678 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2679 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002680 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002681 assert(neededSSE == 2 && "Invalid number of needed registers!");
2682 // SSE registers are spaced 16 bytes apart in the register save
2683 // area, we need to collect the two eightbytes together.
2684 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002685 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002686 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002687 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002688 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002689 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2690 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2691 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002692 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2693 DblPtrTy));
2694 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2695 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2696 DblPtrTy));
2697 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2698 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2699 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002700 }
2701
2702 // AMD64-ABI 3.5.7p5: Step 5. Set:
2703 // l->gp_offset = l->gp_offset + num_gp * 8
2704 // l->fp_offset = l->fp_offset + num_fp * 16.
2705 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002706 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2708 gp_offset_p);
2709 }
2710 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002711 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002712 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2713 fp_offset_p);
2714 }
2715 CGF.EmitBranch(ContBlock);
2716
2717 // Emit code to load the value if it was passed in memory.
2718
2719 CGF.EmitBlock(InMemBlock);
2720 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2721
2722 // Return the appropriate result.
2723
2724 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002725 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002726 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002727 ResAddr->addIncoming(RegAddr, InRegBlock);
2728 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002729 return ResAddr;
2730}
2731
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002732ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002733
2734 if (Ty->isVoidType())
2735 return ABIArgInfo::getIgnore();
2736
2737 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2738 Ty = EnumTy->getDecl()->getIntegerType();
2739
2740 uint64_t Size = getContext().getTypeSize(Ty);
2741
Reid Kleckner9005f412014-05-02 00:51:20 +00002742 const RecordType *RT = Ty->getAs<RecordType>();
2743 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002744 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002745 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002746 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2747 }
2748
2749 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002750 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2751
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002752 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00002753 if (Size == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002754 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2755 Size));
Reid Kleckner9005f412014-05-02 00:51:20 +00002756 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002757
Reid Klecknerec87fec2014-05-02 01:17:12 +00002758 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00002759 // If the member pointer is represented by an LLVM int or ptr, pass it
2760 // directly.
2761 llvm::Type *LLTy = CGT.ConvertType(Ty);
2762 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2763 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00002764 }
2765
2766 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002767 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2768 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner9005f412014-05-02 00:51:20 +00002769 if (Size > 64 || !llvm::isPowerOf2_64(Size))
2770 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002771
Reid Kleckner9005f412014-05-02 00:51:20 +00002772 // Otherwise, coerce it to a small integer.
2773 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002774 }
2775
Julien Lerouge10dcff82014-08-27 00:36:55 +00002776 // Bool type is always extended to the ABI, other builtin types are not
2777 // extended.
2778 const BuiltinType *BT = Ty->getAs<BuiltinType>();
2779 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00002780 return ABIArgInfo::getExtend();
2781
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002782 return ABIArgInfo::getDirect();
2783}
2784
2785void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002786 if (!getCXXABI().classifyReturnType(FI))
2787 FI.getReturnInfo() = classify(FI.getReturnType(), true);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002788
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002789 for (auto &I : FI.arguments())
2790 I.info = classify(I.type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002791}
2792
Chris Lattner04dc9572010-08-31 16:44:54 +00002793llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2794 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002795 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002796
Chris Lattner04dc9572010-08-31 16:44:54 +00002797 CGBuilderTy &Builder = CGF.Builder;
2798 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2799 "ap");
2800 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2801 llvm::Type *PTy =
2802 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2803 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2804
2805 uint64_t Offset =
2806 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2807 llvm::Value *NextAddr =
2808 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2809 "ap.next");
2810 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2811
2812 return AddrTyped;
2813}
Chris Lattner0cf24192010-06-28 20:05:43 +00002814
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002815namespace {
2816
Derek Schuffa2020962012-10-16 22:30:41 +00002817class NaClX86_64ABIInfo : public ABIInfo {
2818 public:
2819 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2820 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00002821 void computeInfo(CGFunctionInfo &FI) const override;
2822 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2823 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00002824 private:
2825 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2826 X86_64ABIInfo NInfo; // Used for everything else.
2827};
2828
2829class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2830 public:
2831 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2832 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2833};
2834
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002835}
2836
Derek Schuffa2020962012-10-16 22:30:41 +00002837void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2838 if (FI.getASTCallingConvention() == CC_PnaclCall)
2839 PInfo.computeInfo(FI);
2840 else
2841 NInfo.computeInfo(FI);
2842}
2843
2844llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2845 CodeGenFunction &CGF) const {
2846 // Always use the native convention; calling pnacl-style varargs functions
2847 // is unuspported.
2848 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2849}
2850
2851
John McCallea8d8bb2010-03-11 00:10:12 +00002852// PowerPC-32
2853
2854namespace {
2855class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2856public:
Chris Lattner2b037972010-07-29 02:01:43 +00002857 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002858
Craig Topper4f12f102014-03-12 06:41:41 +00002859 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00002860 // This is recovered from gcc output.
2861 return 1; // r1 is the dedicated stack pointer
2862 }
2863
2864 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002865 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00002866};
2867
2868}
2869
2870bool
2871PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2872 llvm::Value *Address) const {
2873 // This is calculated from the LLVM and GCC tables and verified
2874 // against gcc output. AFAIK all ABIs use the same encoding.
2875
2876 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002877
Chris Lattnerece04092012-02-07 00:39:47 +00002878 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002879 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2880 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2881 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2882
2883 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002884 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002885
2886 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002887 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002888
2889 // 64-76 are various 4-byte special-purpose registers:
2890 // 64: mq
2891 // 65: lr
2892 // 66: ctr
2893 // 67: ap
2894 // 68-75 cr0-7
2895 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002896 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002897
2898 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002899 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002900
2901 // 109: vrsave
2902 // 110: vscr
2903 // 111: spe_acc
2904 // 112: spefscr
2905 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002906 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002907
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002908 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002909}
2910
Roman Divackyd966e722012-05-09 18:22:46 +00002911// PowerPC-64
2912
2913namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002914/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2915class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00002916public:
2917 enum ABIKind {
2918 ELFv1 = 0,
2919 ELFv2
2920 };
2921
2922private:
2923 static const unsigned GPRBits = 64;
2924 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002925
2926public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00002927 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
2928 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00002929
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002930 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00002931 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigandb7122372014-07-21 00:48:09 +00002932 bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
2933 uint64_t &Members) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002934
2935 ABIArgInfo classifyReturnType(QualType RetTy) const;
2936 ABIArgInfo classifyArgumentType(QualType Ty) const;
2937
Bill Schmidt84d37792012-10-12 19:26:17 +00002938 // TODO: We can add more logic to computeInfo to improve performance.
2939 // Example: For aggregate arguments that fit in a register, we could
2940 // use getDirectInReg (as is done below for structs containing a single
2941 // floating-point value) to avoid pushing them to memory on function
2942 // entry. This would require changing the logic in PPCISelLowering
2943 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00002944 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002945 if (!getCXXABI().classifyReturnType(FI))
2946 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002947 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002948 // We rely on the default argument classification for the most part.
2949 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00002950 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002951 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00002952 if (T) {
2953 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00002954 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
2955 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002956 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002957 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00002958 continue;
2959 }
2960 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002961 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00002962 }
2963 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002964
Craig Topper4f12f102014-03-12 06:41:41 +00002965 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2966 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002967};
2968
2969class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2970public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00002971 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
2972 PPC64_SVR4_ABIInfo::ABIKind Kind)
2973 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00002974
Craig Topper4f12f102014-03-12 06:41:41 +00002975 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002976 // This is recovered from gcc output.
2977 return 1; // r1 is the dedicated stack pointer
2978 }
2979
2980 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002981 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002982};
2983
Roman Divackyd966e722012-05-09 18:22:46 +00002984class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2985public:
2986 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2987
Craig Topper4f12f102014-03-12 06:41:41 +00002988 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00002989 // This is recovered from gcc output.
2990 return 1; // r1 is the dedicated stack pointer
2991 }
2992
2993 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002994 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00002995};
2996
2997}
2998
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002999// Return true if the ABI requires Ty to be passed sign- or zero-
3000// extended to 64 bits.
3001bool
3002PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3003 // Treat an enum type as its underlying type.
3004 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3005 Ty = EnumTy->getDecl()->getIntegerType();
3006
3007 // Promotable integer types are required to be promoted by the ABI.
3008 if (Ty->isPromotableIntegerType())
3009 return true;
3010
3011 // In addition to the usual promotable integer types, we also need to
3012 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3013 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3014 switch (BT->getKind()) {
3015 case BuiltinType::Int:
3016 case BuiltinType::UInt:
3017 return true;
3018 default:
3019 break;
3020 }
3021
3022 return false;
3023}
3024
Ulrich Weigand581badc2014-07-10 17:20:07 +00003025/// isAlignedParamType - Determine whether a type requires 16-byte
3026/// alignment in the parameter area.
3027bool
3028PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3029 // Complex types are passed just like their elements.
3030 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3031 Ty = CTy->getElementType();
3032
3033 // Only vector types of size 16 bytes need alignment (larger types are
3034 // passed via reference, smaller types are not aligned).
3035 if (Ty->isVectorType())
3036 return getContext().getTypeSize(Ty) == 128;
3037
3038 // For single-element float/vector structs, we consider the whole type
3039 // to have the same alignment requirements as its single element.
3040 const Type *AlignAsType = nullptr;
3041 const Type *EltType = isSingleElementStruct(Ty, getContext());
3042 if (EltType) {
3043 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3044 if ((EltType->isVectorType() &&
3045 getContext().getTypeSize(EltType) == 128) ||
3046 (BT && BT->isFloatingPoint()))
3047 AlignAsType = EltType;
3048 }
3049
Ulrich Weigandb7122372014-07-21 00:48:09 +00003050 // Likewise for ELFv2 homogeneous aggregates.
3051 const Type *Base = nullptr;
3052 uint64_t Members = 0;
3053 if (!AlignAsType && Kind == ELFv2 &&
3054 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3055 AlignAsType = Base;
3056
Ulrich Weigand581badc2014-07-10 17:20:07 +00003057 // With special case aggregates, only vector base types need alignment.
3058 if (AlignAsType)
3059 return AlignAsType->isVectorType();
3060
3061 // Otherwise, we only need alignment for any aggregate type that
3062 // has an alignment requirement of >= 16 bytes.
3063 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3064 return true;
3065
3066 return false;
3067}
3068
Ulrich Weigandb7122372014-07-21 00:48:09 +00003069/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3070/// aggregate. Base is set to the base element type, and Members is set
3071/// to the number of base elements.
3072bool
3073PPC64_SVR4_ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3074 uint64_t &Members) const {
3075 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3076 uint64_t NElements = AT->getSize().getZExtValue();
3077 if (NElements == 0)
3078 return false;
3079 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3080 return false;
3081 Members *= NElements;
3082 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3083 const RecordDecl *RD = RT->getDecl();
3084 if (RD->hasFlexibleArrayMember())
3085 return false;
3086
3087 Members = 0;
3088 for (const auto *FD : RD->fields()) {
3089 // Ignore (non-zero arrays of) empty records.
3090 QualType FT = FD->getType();
3091 while (const ConstantArrayType *AT =
3092 getContext().getAsConstantArrayType(FT)) {
3093 if (AT->getSize().getZExtValue() == 0)
3094 return false;
3095 FT = AT->getElementType();
3096 }
3097 if (isEmptyRecord(getContext(), FT, true))
3098 continue;
3099
3100 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3101 if (getContext().getLangOpts().CPlusPlus &&
3102 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3103 continue;
3104
3105 uint64_t FldMembers;
3106 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3107 return false;
3108
3109 Members = (RD->isUnion() ?
3110 std::max(Members, FldMembers) : Members + FldMembers);
3111 }
3112
3113 if (!Base)
3114 return false;
3115
3116 // Ensure there is no padding.
3117 if (getContext().getTypeSize(Base) * Members !=
3118 getContext().getTypeSize(Ty))
3119 return false;
3120 } else {
3121 Members = 1;
3122 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3123 Members = 2;
3124 Ty = CT->getElementType();
3125 }
3126
3127 // Homogeneous aggregates for ELFv2 must have base types of float,
3128 // double, long double, or 128-bit vectors.
3129 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3130 if (BT->getKind() != BuiltinType::Float &&
3131 BT->getKind() != BuiltinType::Double &&
3132 BT->getKind() != BuiltinType::LongDouble)
3133 return false;
3134 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3135 if (getContext().getTypeSize(VT) != 128)
3136 return false;
3137 } else {
3138 return false;
3139 }
3140
3141 // The base type must be the same for all members. Types that
3142 // agree in both total size and mode (float vs. vector) are
3143 // treated as being equivalent here.
3144 const Type *TyPtr = Ty.getTypePtr();
3145 if (!Base)
3146 Base = TyPtr;
3147
3148 if (Base->isVectorType() != TyPtr->isVectorType() ||
3149 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3150 return false;
3151 }
3152
3153 // Vector types require one register, floating point types require one
3154 // or two registers depending on their size.
3155 uint32_t NumRegs = Base->isVectorType() ? 1 :
3156 (getContext().getTypeSize(Base) + 63) / 64;
3157
3158 // Homogeneous Aggregates may occupy at most 8 registers.
3159 return (Members > 0 && Members * NumRegs <= 8);
3160}
3161
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003162ABIArgInfo
3163PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00003164 if (Ty->isAnyComplexType())
3165 return ABIArgInfo::getDirect();
3166
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003167 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3168 // or via reference (larger than 16 bytes).
3169 if (Ty->isVectorType()) {
3170 uint64_t Size = getContext().getTypeSize(Ty);
3171 if (Size > 128)
3172 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3173 else if (Size < 128) {
3174 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3175 return ABIArgInfo::getDirect(CoerceTy);
3176 }
3177 }
3178
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003179 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003180 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003181 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003182
Ulrich Weigand581badc2014-07-10 17:20:07 +00003183 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3184 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003185
3186 // ELFv2 homogeneous aggregates are passed as array types.
3187 const Type *Base = nullptr;
3188 uint64_t Members = 0;
3189 if (Kind == ELFv2 &&
3190 isHomogeneousAggregate(Ty, Base, Members)) {
3191 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3192 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3193 return ABIArgInfo::getDirect(CoerceTy);
3194 }
3195
Ulrich Weigand601957f2014-07-21 00:56:36 +00003196 // If an aggregate may end up fully in registers, we do not
3197 // use the ByVal method, but pass the aggregate as array.
3198 // This is usually beneficial since we avoid forcing the
3199 // back-end to store the argument to memory.
3200 uint64_t Bits = getContext().getTypeSize(Ty);
3201 if (Bits > 0 && Bits <= 8 * GPRBits) {
3202 llvm::Type *CoerceTy;
3203
3204 // Types up to 8 bytes are passed as integer type (which will be
3205 // properly aligned in the argument save area doubleword).
3206 if (Bits <= GPRBits)
3207 CoerceTy = llvm::IntegerType::get(getVMContext(),
3208 llvm::RoundUpToAlignment(Bits, 8));
3209 // Larger types are passed as arrays, with the base type selected
3210 // according to the required alignment in the save area.
3211 else {
3212 uint64_t RegBits = ABIAlign * 8;
3213 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3214 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3215 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3216 }
3217
3218 return ABIArgInfo::getDirect(CoerceTy);
3219 }
3220
Ulrich Weigandb7122372014-07-21 00:48:09 +00003221 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003222 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3223 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003224 }
3225
3226 return (isPromotableTypeForABI(Ty) ?
3227 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3228}
3229
3230ABIArgInfo
3231PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3232 if (RetTy->isVoidType())
3233 return ABIArgInfo::getIgnore();
3234
Bill Schmidta3d121c2012-12-17 04:20:17 +00003235 if (RetTy->isAnyComplexType())
3236 return ABIArgInfo::getDirect();
3237
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003238 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3239 // or via reference (larger than 16 bytes).
3240 if (RetTy->isVectorType()) {
3241 uint64_t Size = getContext().getTypeSize(RetTy);
3242 if (Size > 128)
3243 return ABIArgInfo::getIndirect(0);
3244 else if (Size < 128) {
3245 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3246 return ABIArgInfo::getDirect(CoerceTy);
3247 }
3248 }
3249
Ulrich Weigandb7122372014-07-21 00:48:09 +00003250 if (isAggregateTypeForABI(RetTy)) {
3251 // ELFv2 homogeneous aggregates are returned as array types.
3252 const Type *Base = nullptr;
3253 uint64_t Members = 0;
3254 if (Kind == ELFv2 &&
3255 isHomogeneousAggregate(RetTy, Base, Members)) {
3256 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3257 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3258 return ABIArgInfo::getDirect(CoerceTy);
3259 }
3260
3261 // ELFv2 small aggregates are returned in up to two registers.
3262 uint64_t Bits = getContext().getTypeSize(RetTy);
3263 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3264 if (Bits == 0)
3265 return ABIArgInfo::getIgnore();
3266
3267 llvm::Type *CoerceTy;
3268 if (Bits > GPRBits) {
3269 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3270 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3271 } else
3272 CoerceTy = llvm::IntegerType::get(getVMContext(),
3273 llvm::RoundUpToAlignment(Bits, 8));
3274 return ABIArgInfo::getDirect(CoerceTy);
3275 }
3276
3277 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003278 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003279 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003280
3281 return (isPromotableTypeForABI(RetTy) ?
3282 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3283}
3284
Bill Schmidt25cb3492012-10-03 19:18:57 +00003285// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3286llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3287 QualType Ty,
3288 CodeGenFunction &CGF) const {
3289 llvm::Type *BP = CGF.Int8PtrTy;
3290 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3291
3292 CGBuilderTy &Builder = CGF.Builder;
3293 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3294 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3295
Ulrich Weigand581badc2014-07-10 17:20:07 +00003296 // Handle types that require 16-byte alignment in the parameter save area.
3297 if (isAlignedParamType(Ty)) {
3298 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3299 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3300 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3301 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3302 }
3303
Bill Schmidt924c4782013-01-14 17:45:36 +00003304 // Update the va_list pointer. The pointer should be bumped by the
3305 // size of the object. We can trust getTypeSize() except for a complex
3306 // type whose base type is smaller than a doubleword. For these, the
3307 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003308 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003309 QualType BaseTy;
3310 unsigned CplxBaseSize = 0;
3311
3312 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3313 BaseTy = CTy->getElementType();
3314 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3315 if (CplxBaseSize < 8)
3316 SizeInBytes = 16;
3317 }
3318
Bill Schmidt25cb3492012-10-03 19:18:57 +00003319 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3320 llvm::Value *NextAddr =
3321 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3322 "ap.next");
3323 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3324
Bill Schmidt924c4782013-01-14 17:45:36 +00003325 // If we have a complex type and the base type is smaller than 8 bytes,
3326 // the ABI calls for the real and imaginary parts to be right-adjusted
3327 // in separate doublewords. However, Clang expects us to produce a
3328 // pointer to a structure with the two parts packed tightly. So generate
3329 // loads of the real and imaginary parts relative to the va_list pointer,
3330 // and store them to a temporary structure.
3331 if (CplxBaseSize && CplxBaseSize < 8) {
3332 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3333 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003334 if (CGF.CGM.getDataLayout().isBigEndian()) {
3335 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3336 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3337 } else {
3338 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3339 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003340 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3341 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3342 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3343 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3344 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3345 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3346 "vacplx");
3347 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3348 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3349 Builder.CreateStore(Real, RealPtr, false);
3350 Builder.CreateStore(Imag, ImagPtr, false);
3351 return Ptr;
3352 }
3353
Bill Schmidt25cb3492012-10-03 19:18:57 +00003354 // If the argument is smaller than 8 bytes, it is right-adjusted in
3355 // its doubleword slot. Adjust the pointer to pick it up from the
3356 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003357 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003358 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3359 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3360 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3361 }
3362
3363 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3364 return Builder.CreateBitCast(Addr, PTy);
3365}
3366
3367static bool
3368PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3369 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003370 // This is calculated from the LLVM and GCC tables and verified
3371 // against gcc output. AFAIK all ABIs use the same encoding.
3372
3373 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3374
3375 llvm::IntegerType *i8 = CGF.Int8Ty;
3376 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3377 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3378 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3379
3380 // 0-31: r0-31, the 8-byte general-purpose registers
3381 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3382
3383 // 32-63: fp0-31, the 8-byte floating-point registers
3384 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3385
3386 // 64-76 are various 4-byte special-purpose registers:
3387 // 64: mq
3388 // 65: lr
3389 // 66: ctr
3390 // 67: ap
3391 // 68-75 cr0-7
3392 // 76: xer
3393 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3394
3395 // 77-108: v0-31, the 16-byte vector registers
3396 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3397
3398 // 109: vrsave
3399 // 110: vscr
3400 // 111: spe_acc
3401 // 112: spefscr
3402 // 113: sfp
3403 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3404
3405 return false;
3406}
John McCallea8d8bb2010-03-11 00:10:12 +00003407
Bill Schmidt25cb3492012-10-03 19:18:57 +00003408bool
3409PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3410 CodeGen::CodeGenFunction &CGF,
3411 llvm::Value *Address) const {
3412
3413 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3414}
3415
3416bool
3417PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3418 llvm::Value *Address) const {
3419
3420 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3421}
3422
Chris Lattner0cf24192010-06-28 20:05:43 +00003423//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003424// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003425//===----------------------------------------------------------------------===//
3426
3427namespace {
3428
Tim Northover573cbee2014-05-24 12:52:07 +00003429class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003430public:
3431 enum ABIKind {
3432 AAPCS = 0,
3433 DarwinPCS
3434 };
3435
3436private:
3437 ABIKind Kind;
3438
3439public:
Tim Northover573cbee2014-05-24 12:52:07 +00003440 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003441
3442private:
3443 ABIKind getABIKind() const { return Kind; }
3444 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3445
3446 ABIArgInfo classifyReturnType(QualType RetTy) const;
3447 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3448 bool &IsHA, unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003449 bool &IsSmallAggr, bool IsNamedArg) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00003450 bool isIllegalVectorType(QualType Ty) const;
3451
3452 virtual void computeInfo(CGFunctionInfo &FI) const {
3453 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3454 // number of SIMD and Floating-point registers allocated so far.
3455 // If the argument is an HFA or an HVA and there are sufficient unallocated
3456 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3457 // and Floating-point Registers (with one register per member of the HFA or
3458 // HVA). Otherwise, the NSRN is set to 8.
3459 unsigned AllocatedVFP = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003460
Tim Northovera2ee4332014-03-29 15:09:45 +00003461 // To correctly handle small aggregates, we need to keep track of the number
3462 // of GPRs allocated so far. If the small aggregate can't all fit into
3463 // registers, it will be on stack. We don't allow the aggregate to be
3464 // partially in registers.
3465 unsigned AllocatedGPR = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003466
3467 // Find the number of named arguments. Variadic arguments get special
3468 // treatment with the Darwin ABI.
3469 unsigned NumRequiredArgs = (FI.isVariadic() ?
3470 FI.getRequiredArgs().getNumRequiredArgs() :
3471 FI.arg_size());
3472
Reid Kleckner40ca9132014-05-13 22:05:45 +00003473 if (!getCXXABI().classifyReturnType(FI))
3474 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northovera2ee4332014-03-29 15:09:45 +00003475 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3476 it != ie; ++it) {
3477 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3478 bool IsHA = false, IsSmallAggr = false;
3479 const unsigned NumVFPs = 8;
3480 const unsigned NumGPRs = 8;
Bob Wilson373af732014-04-21 01:23:39 +00003481 bool IsNamedArg = ((it - FI.arg_begin()) <
3482 static_cast<signed>(NumRequiredArgs));
Tim Northovera2ee4332014-03-29 15:09:45 +00003483 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Bob Wilson373af732014-04-21 01:23:39 +00003484 AllocatedGPR, IsSmallAggr, IsNamedArg);
Tim Northover5ffc0922014-04-17 10:20:38 +00003485
3486 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3487 // as sequences of floats since they'll get "holes" inserted as
3488 // padding by the back end.
Tim Northover07f16242014-04-18 10:47:44 +00003489 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3490 getContext().getTypeAlign(it->type) < 64) {
3491 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3492 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
Tim Northover5ffc0922014-04-17 10:20:38 +00003493
Tim Northover07f16242014-04-18 10:47:44 +00003494 llvm::Type *CoerceTy = llvm::ArrayType::get(
3495 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3496 it->info = ABIArgInfo::getDirect(CoerceTy);
Tim Northover5ffc0922014-04-17 10:20:38 +00003497 }
3498
Tim Northovera2ee4332014-03-29 15:09:45 +00003499 // If we do not have enough VFP registers for the HA, any VFP registers
3500 // that are unallocated are marked as unavailable. To achieve this, we add
3501 // padding of (NumVFPs - PreAllocation) floats.
3502 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3503 llvm::Type *PaddingTy = llvm::ArrayType::get(
3504 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Tim Northover5ffc0922014-04-17 10:20:38 +00003505 it->info.setPaddingType(PaddingTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00003506 }
Tim Northover5ffc0922014-04-17 10:20:38 +00003507
Tim Northovera2ee4332014-03-29 15:09:45 +00003508 // If we do not have enough GPRs for the small aggregate, any GPR regs
3509 // that are unallocated are marked as unavailable.
3510 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3511 llvm::Type *PaddingTy = llvm::ArrayType::get(
3512 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3513 it->info =
3514 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3515 }
3516 }
3517 }
3518
3519 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3520 CodeGenFunction &CGF) const;
3521
3522 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3523 CodeGenFunction &CGF) const;
3524
3525 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3526 CodeGenFunction &CGF) const {
3527 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3528 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3529 }
3530};
3531
Tim Northover573cbee2014-05-24 12:52:07 +00003532class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003533public:
Tim Northover573cbee2014-05-24 12:52:07 +00003534 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3535 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003536
3537 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3538 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3539 }
3540
3541 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3542
3543 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3544};
3545}
3546
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003547static bool isARMHomogeneousAggregate(QualType Ty, const Type *&Base,
Tim Northovera2ee4332014-03-29 15:09:45 +00003548 ASTContext &Context,
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003549 bool isAArch64,
Craig Topper8a13c412014-05-21 05:09:00 +00003550 uint64_t *HAMembers = nullptr);
Tim Northovera2ee4332014-03-29 15:09:45 +00003551
Tim Northover573cbee2014-05-24 12:52:07 +00003552ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3553 unsigned &AllocatedVFP,
3554 bool &IsHA,
3555 unsigned &AllocatedGPR,
3556 bool &IsSmallAggr,
3557 bool IsNamedArg) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003558 // Handle illegal vector types here.
3559 if (isIllegalVectorType(Ty)) {
3560 uint64_t Size = getContext().getTypeSize(Ty);
3561 if (Size <= 32) {
3562 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3563 AllocatedGPR++;
3564 return ABIArgInfo::getDirect(ResType);
3565 }
3566 if (Size == 64) {
3567 llvm::Type *ResType =
3568 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3569 AllocatedVFP++;
3570 return ABIArgInfo::getDirect(ResType);
3571 }
3572 if (Size == 128) {
3573 llvm::Type *ResType =
3574 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3575 AllocatedVFP++;
3576 return ABIArgInfo::getDirect(ResType);
3577 }
3578 AllocatedGPR++;
3579 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3580 }
3581 if (Ty->isVectorType())
3582 // Size of a legal vector should be either 64 or 128.
3583 AllocatedVFP++;
3584 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3585 if (BT->getKind() == BuiltinType::Half ||
3586 BT->getKind() == BuiltinType::Float ||
3587 BT->getKind() == BuiltinType::Double ||
3588 BT->getKind() == BuiltinType::LongDouble)
3589 AllocatedVFP++;
3590 }
3591
3592 if (!isAggregateTypeForABI(Ty)) {
3593 // Treat an enum type as its underlying type.
3594 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3595 Ty = EnumTy->getDecl()->getIntegerType();
3596
3597 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003598 unsigned Alignment = getContext().getTypeAlign(Ty);
3599 if (!isDarwinPCS() && Alignment > 64)
3600 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3601
Tim Northovera2ee4332014-03-29 15:09:45 +00003602 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3603 AllocatedGPR += RegsNeeded;
3604 }
3605 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3606 ? ABIArgInfo::getExtend()
3607 : ABIArgInfo::getDirect());
3608 }
3609
3610 // Structures with either a non-trivial destructor or a non-trivial
3611 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003612 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003613 AllocatedGPR++;
Reid Kleckner40ca9132014-05-13 22:05:45 +00003614 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3615 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003616 }
3617
3618 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3619 // elsewhere for GNU compatibility.
3620 if (isEmptyRecord(getContext(), Ty, true)) {
3621 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3622 return ABIArgInfo::getIgnore();
3623
3624 ++AllocatedGPR;
3625 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3626 }
3627
3628 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003629 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003630 uint64_t Members = 0;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003631 if (isARMHomogeneousAggregate(Ty, Base, getContext(), true, &Members)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003632 IsHA = true;
Bob Wilson373af732014-04-21 01:23:39 +00003633 if (!IsNamedArg && isDarwinPCS()) {
3634 // With the Darwin ABI, variadic arguments are always passed on the stack
3635 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3636 uint64_t Size = getContext().getTypeSize(Ty);
3637 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3638 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3639 }
3640 AllocatedVFP += Members;
Tim Northovera2ee4332014-03-29 15:09:45 +00003641 return ABIArgInfo::getExpand();
3642 }
3643
3644 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3645 uint64_t Size = getContext().getTypeSize(Ty);
3646 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003647 unsigned Alignment = getContext().getTypeAlign(Ty);
3648 if (!isDarwinPCS() && Alignment > 64)
3649 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3650
Tim Northovera2ee4332014-03-29 15:09:45 +00003651 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3652 AllocatedGPR += Size / 64;
3653 IsSmallAggr = true;
3654 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3655 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003656 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003657 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3658 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3659 }
3660 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3661 }
3662
3663 AllocatedGPR++;
3664 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3665}
3666
Tim Northover573cbee2014-05-24 12:52:07 +00003667ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003668 if (RetTy->isVoidType())
3669 return ABIArgInfo::getIgnore();
3670
3671 // Large vector types should be returned via memory.
3672 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3673 return ABIArgInfo::getIndirect(0);
3674
3675 if (!isAggregateTypeForABI(RetTy)) {
3676 // Treat an enum type as its underlying type.
3677 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3678 RetTy = EnumTy->getDecl()->getIntegerType();
3679
Tim Northover4dab6982014-04-18 13:46:08 +00003680 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3681 ? ABIArgInfo::getExtend()
3682 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003683 }
3684
Tim Northovera2ee4332014-03-29 15:09:45 +00003685 if (isEmptyRecord(getContext(), RetTy, true))
3686 return ABIArgInfo::getIgnore();
3687
Craig Topper8a13c412014-05-21 05:09:00 +00003688 const Type *Base = nullptr;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003689 if (isARMHomogeneousAggregate(RetTy, Base, getContext(), true))
Tim Northovera2ee4332014-03-29 15:09:45 +00003690 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3691 return ABIArgInfo::getDirect();
3692
3693 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3694 uint64_t Size = getContext().getTypeSize(RetTy);
3695 if (Size <= 128) {
3696 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3697 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3698 }
3699
3700 return ABIArgInfo::getIndirect(0);
3701}
3702
Tim Northover573cbee2014-05-24 12:52:07 +00003703/// isIllegalVectorType - check whether the vector type is legal for AArch64.
3704bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003705 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3706 // Check whether VT is legal.
3707 unsigned NumElements = VT->getNumElements();
3708 uint64_t Size = getContext().getTypeSize(VT);
3709 // NumElements should be power of 2 between 1 and 16.
3710 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3711 return true;
3712 return Size != 64 && (Size != 128 || NumElements == 1);
3713 }
3714 return false;
3715}
3716
3717static llvm::Value *EmitAArch64VAArg(llvm::Value *VAListAddr, QualType Ty,
3718 int AllocatedGPR, int AllocatedVFP,
3719 bool IsIndirect, CodeGenFunction &CGF) {
3720 // The AArch64 va_list type and handling is specified in the Procedure Call
3721 // Standard, section B.4:
3722 //
3723 // struct {
3724 // void *__stack;
3725 // void *__gr_top;
3726 // void *__vr_top;
3727 // int __gr_offs;
3728 // int __vr_offs;
3729 // };
3730
3731 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3732 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3733 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3734 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3735 auto &Ctx = CGF.getContext();
3736
Craig Topper8a13c412014-05-21 05:09:00 +00003737 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003738 int reg_top_index;
3739 int RegSize;
3740 if (AllocatedGPR) {
3741 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
3742 // 3 is the field number of __gr_offs
3743 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3744 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3745 reg_top_index = 1; // field number for __gr_top
3746 RegSize = 8 * AllocatedGPR;
3747 } else {
3748 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
3749 // 4 is the field number of __vr_offs.
3750 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3751 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3752 reg_top_index = 2; // field number for __vr_top
3753 RegSize = 16 * AllocatedVFP;
3754 }
3755
3756 //=======================================
3757 // Find out where argument was passed
3758 //=======================================
3759
3760 // If reg_offs >= 0 we're already using the stack for this type of
3761 // argument. We don't want to keep updating reg_offs (in case it overflows,
3762 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3763 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00003764 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003765 UsingStack = CGF.Builder.CreateICmpSGE(
3766 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
3767
3768 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3769
3770 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00003771 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00003772 CGF.EmitBlock(MaybeRegBlock);
3773
3774 // Integer arguments may need to correct register alignment (for example a
3775 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3776 // align __gr_offs to calculate the potential address.
3777 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3778 int Align = Ctx.getTypeAlign(Ty) / 8;
3779
3780 reg_offs = CGF.Builder.CreateAdd(
3781 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3782 "align_regoffs");
3783 reg_offs = CGF.Builder.CreateAnd(
3784 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3785 "aligned_regoffs");
3786 }
3787
3788 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00003789 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003790 NewOffset = CGF.Builder.CreateAdd(
3791 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
3792 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3793
3794 // Now we're in a position to decide whether this argument really was in
3795 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00003796 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003797 InRegs = CGF.Builder.CreateICmpSLE(
3798 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
3799
3800 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3801
3802 //=======================================
3803 // Argument was in registers
3804 //=======================================
3805
3806 // Now we emit the code for if the argument was originally passed in
3807 // registers. First start the appropriate block:
3808 CGF.EmitBlock(InRegBlock);
3809
Craig Topper8a13c412014-05-21 05:09:00 +00003810 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003811 reg_top_p =
3812 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3813 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3814 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00003815 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003816 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
3817
3818 if (IsIndirect) {
3819 // If it's been passed indirectly (actually a struct), whatever we find from
3820 // stored registers or on the stack will actually be a struct **.
3821 MemTy = llvm::PointerType::getUnqual(MemTy);
3822 }
3823
Craig Topper8a13c412014-05-21 05:09:00 +00003824 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003825 uint64_t NumMembers;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003826 bool IsHFA = isARMHomogeneousAggregate(Ty, Base, Ctx, true, &NumMembers);
James Molloy467be602014-05-07 14:45:55 +00003827 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003828 // Homogeneous aggregates passed in registers will have their elements split
3829 // and stored 16-bytes apart regardless of size (they're notionally in qN,
3830 // qN+1, ...). We reload and store into a temporary local variable
3831 // contiguously.
3832 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
3833 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
3834 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
3835 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
3836 int Offset = 0;
3837
3838 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
3839 Offset = 16 - Ctx.getTypeSize(Base) / 8;
3840 for (unsigned i = 0; i < NumMembers; ++i) {
3841 llvm::Value *BaseOffset =
3842 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
3843 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
3844 LoadAddr = CGF.Builder.CreateBitCast(
3845 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
3846 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
3847
3848 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
3849 CGF.Builder.CreateStore(Elem, StoreAddr);
3850 }
3851
3852 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
3853 } else {
3854 // Otherwise the object is contiguous in memory
3855 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00003856 if (CGF.CGM.getDataLayout().isBigEndian() &&
3857 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00003858 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
3859 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
3860 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
3861
3862 BaseAddr = CGF.Builder.CreateAdd(
3863 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3864
3865 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
3866 }
3867
3868 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
3869 }
3870
3871 CGF.EmitBranch(ContBlock);
3872
3873 //=======================================
3874 // Argument was on the stack
3875 //=======================================
3876 CGF.EmitBlock(OnStackBlock);
3877
Craig Topper8a13c412014-05-21 05:09:00 +00003878 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003879 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
3880 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
3881
3882 // Again, stack arguments may need realigmnent. In this case both integer and
3883 // floating-point ones might be affected.
3884 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3885 int Align = Ctx.getTypeAlign(Ty) / 8;
3886
3887 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3888
3889 OnStackAddr = CGF.Builder.CreateAdd(
3890 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
3891 "align_stack");
3892 OnStackAddr = CGF.Builder.CreateAnd(
3893 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
3894 "align_stack");
3895
3896 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3897 }
3898
3899 uint64_t StackSize;
3900 if (IsIndirect)
3901 StackSize = 8;
3902 else
3903 StackSize = Ctx.getTypeSize(Ty) / 8;
3904
3905 // All stack slots are 8 bytes
3906 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
3907
3908 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
3909 llvm::Value *NewStack =
3910 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
3911
3912 // Write the new value of __stack for the next call to va_arg
3913 CGF.Builder.CreateStore(NewStack, stack_p);
3914
3915 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
3916 Ctx.getTypeSize(Ty) < 64) {
3917 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
3918 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3919
3920 OnStackAddr = CGF.Builder.CreateAdd(
3921 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3922
3923 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3924 }
3925
3926 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
3927
3928 CGF.EmitBranch(ContBlock);
3929
3930 //=======================================
3931 // Tidy up
3932 //=======================================
3933 CGF.EmitBlock(ContBlock);
3934
3935 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
3936 ResAddr->addIncoming(RegAddr, InRegBlock);
3937 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
3938
3939 if (IsIndirect)
3940 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
3941
3942 return ResAddr;
3943}
3944
Tim Northover573cbee2014-05-24 12:52:07 +00003945llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00003946 CodeGenFunction &CGF) const {
3947
3948 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
3949 bool IsHA = false, IsSmallAggr = false;
Bob Wilson373af732014-04-21 01:23:39 +00003950 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
3951 IsSmallAggr, false /*IsNamedArg*/);
Tim Northovera2ee4332014-03-29 15:09:45 +00003952
3953 return EmitAArch64VAArg(VAListAddr, Ty, AllocatedGPR, AllocatedVFP,
3954 AI.isIndirect(), CGF);
3955}
3956
Tim Northover573cbee2014-05-24 12:52:07 +00003957llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00003958 CodeGenFunction &CGF) const {
3959 // We do not support va_arg for aggregates or illegal vector types.
3960 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
3961 // other cases.
3962 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00003963 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003964
3965 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
3966 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
3967
Craig Topper8a13c412014-05-21 05:09:00 +00003968 const Type *Base = nullptr;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003969 bool isHA = isARMHomogeneousAggregate(Ty, Base, getContext(), true);
Tim Northovera2ee4332014-03-29 15:09:45 +00003970
3971 bool isIndirect = false;
3972 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
3973 // be passed indirectly.
3974 if (Size > 16 && !isHA) {
3975 isIndirect = true;
3976 Size = 8;
3977 Align = 8;
3978 }
3979
3980 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
3981 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
3982
3983 CGBuilderTy &Builder = CGF.Builder;
3984 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3985 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3986
3987 if (isEmptyRecord(getContext(), Ty, true)) {
3988 // These are ignored for parameter passing purposes.
3989 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3990 return Builder.CreateBitCast(Addr, PTy);
3991 }
3992
3993 const uint64_t MinABIAlign = 8;
3994 if (Align > MinABIAlign) {
3995 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
3996 Addr = Builder.CreateGEP(Addr, Offset);
3997 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3998 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
3999 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4000 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4001 }
4002
4003 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4004 llvm::Value *NextAddr = Builder.CreateGEP(
4005 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4006 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4007
4008 if (isIndirect)
4009 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4010 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4011 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4012
4013 return AddrTyped;
4014}
4015
4016//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004017// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004018//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004019
4020namespace {
4021
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004022class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004023public:
4024 enum ABIKind {
4025 APCS = 0,
4026 AAPCS = 1,
4027 AAPCS_VFP
4028 };
4029
4030private:
4031 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00004032 mutable int VFPRegs[16];
4033 const unsigned NumVFPs;
4034 const unsigned NumGPRs;
4035 mutable unsigned AllocatedGPRs;
4036 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004037
4038public:
Oliver Stannard405bded2014-02-11 09:25:50 +00004039 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4040 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00004041 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004042 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00004043 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004044
John McCall3480ef22011-08-30 01:42:09 +00004045 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004046 switch (getTarget().getTriple().getEnvironment()) {
4047 case llvm::Triple::Android:
4048 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004049 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004050 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004051 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004052 return true;
4053 default:
4054 return false;
4055 }
John McCall3480ef22011-08-30 01:42:09 +00004056 }
4057
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004058 bool isEABIHF() const {
4059 switch (getTarget().getTriple().getEnvironment()) {
4060 case llvm::Triple::EABIHF:
4061 case llvm::Triple::GNUEABIHF:
4062 return true;
4063 default:
4064 return false;
4065 }
4066 }
4067
Daniel Dunbar020daa92009-09-12 01:00:39 +00004068 ABIKind getABIKind() const { return Kind; }
4069
Tim Northovera484bc02013-10-01 14:34:25 +00004070private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004071 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00004072 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004073 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00004074 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004075
Craig Topper4f12f102014-03-12 06:41:41 +00004076 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004077
Craig Topper4f12f102014-03-12 06:41:41 +00004078 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4079 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004080
4081 llvm::CallingConv::ID getLLVMDefaultCC() const;
4082 llvm::CallingConv::ID getABIDefaultCC() const;
4083 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004084
4085 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4086 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4087 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004088};
4089
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004090class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4091public:
Chris Lattner2b037972010-07-29 02:01:43 +00004092 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4093 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004094
John McCall3480ef22011-08-30 01:42:09 +00004095 const ARMABIInfo &getABIInfo() const {
4096 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4097 }
4098
Craig Topper4f12f102014-03-12 06:41:41 +00004099 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004100 return 13;
4101 }
Roman Divackyc1617352011-05-18 19:36:54 +00004102
Craig Topper4f12f102014-03-12 06:41:41 +00004103 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004104 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4105 }
4106
Roman Divackyc1617352011-05-18 19:36:54 +00004107 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004108 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004109 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004110
4111 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004112 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004113 return false;
4114 }
John McCall3480ef22011-08-30 01:42:09 +00004115
Craig Topper4f12f102014-03-12 06:41:41 +00004116 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004117 if (getABIInfo().isEABI()) return 88;
4118 return TargetCodeGenInfo::getSizeOfUnwindException();
4119 }
Tim Northovera484bc02013-10-01 14:34:25 +00004120
4121 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004122 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004123 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4124 if (!FD)
4125 return;
4126
4127 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4128 if (!Attr)
4129 return;
4130
4131 const char *Kind;
4132 switch (Attr->getInterrupt()) {
4133 case ARMInterruptAttr::Generic: Kind = ""; break;
4134 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4135 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4136 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4137 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4138 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4139 }
4140
4141 llvm::Function *Fn = cast<llvm::Function>(GV);
4142
4143 Fn->addFnAttr("interrupt", Kind);
4144
4145 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4146 return;
4147
4148 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4149 // however this is not necessarily true on taking any interrupt. Instruct
4150 // the backend to perform a realignment as part of the function prologue.
4151 llvm::AttrBuilder B;
4152 B.addStackAlignmentAttr(8);
4153 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4154 llvm::AttributeSet::get(CGM.getLLVMContext(),
4155 llvm::AttributeSet::FunctionIndex,
4156 B));
4157 }
4158
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004159};
4160
Daniel Dunbard59655c2009-09-12 00:59:49 +00004161}
4162
Chris Lattner22326a12010-07-29 02:31:05 +00004163void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004164 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00004165 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00004166 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4167 // VFP registers of the appropriate type unallocated then the argument is
4168 // allocated to the lowest-numbered sequence of such registers.
4169 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4170 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00004171 resetAllocatedRegs();
4172
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004173 const bool isAAPCS_VFP =
4174 getABIKind() == ARMABIInfo::AAPCS_VFP && !FI.isVariadic();
4175
Reid Kleckner40ca9132014-05-13 22:05:45 +00004176 if (getCXXABI().classifyReturnType(FI)) {
4177 if (FI.getReturnInfo().isIndirect())
4178 markAllocatedGPRs(1, 1);
4179 } else {
4180 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4181 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004182 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004183 unsigned PreAllocationVFPs = AllocatedVFPs;
4184 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00004185 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00004186 // 6.1.2.3 There is one VFP co-processor register class using registers
4187 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00004188 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00004189
4190 // If we have allocated some arguments onto the stack (due to running
4191 // out of VFP registers), we cannot split an argument between GPRs and
4192 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00004193 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00004194 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4195 // unusable anyway.
Oliver Stannarde0228512014-07-18 09:09:31 +00004196 // We do not have to do this if the argument is being passed ByVal, as the
4197 // backend can handle that situation correctly.
Oliver Stannard405bded2014-02-11 09:25:50 +00004198 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Oliver Stannarde0228512014-07-18 09:09:31 +00004199 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4200 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4201 StackUsed && !IsByVal) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004202 llvm::Type *PaddingTy = llvm::ArrayType::get(
4203 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004204 if (I.info.canHaveCoerceToType()) {
4205 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004206 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004207 } else {
4208 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004209 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004210 }
Manman Ren2a523d82012-10-30 23:21:41 +00004211 }
4212 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004213
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004214 // Always honor user-specified calling convention.
4215 if (FI.getCallingConvention() != llvm::CallingConv::C)
4216 return;
4217
John McCall882987f2013-02-28 19:01:20 +00004218 llvm::CallingConv::ID cc = getRuntimeCC();
4219 if (cc != llvm::CallingConv::C)
4220 FI.setEffectiveCallingConvention(cc);
4221}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004222
John McCall882987f2013-02-28 19:01:20 +00004223/// Return the default calling convention that LLVM will use.
4224llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4225 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004226 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004227 return llvm::CallingConv::ARM_AAPCS_VFP;
4228 else if (isEABI())
4229 return llvm::CallingConv::ARM_AAPCS;
4230 else
4231 return llvm::CallingConv::ARM_APCS;
4232}
4233
4234/// Return the calling convention that our ABI would like us to use
4235/// as the C calling convention.
4236llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004237 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004238 case APCS: return llvm::CallingConv::ARM_APCS;
4239 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4240 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004241 }
John McCall882987f2013-02-28 19:01:20 +00004242 llvm_unreachable("bad ABI kind");
4243}
4244
4245void ARMABIInfo::setRuntimeCC() {
4246 assert(getRuntimeCC() == llvm::CallingConv::C);
4247
4248 // Don't muddy up the IR with a ton of explicit annotations if
4249 // they'd just match what LLVM will infer from the triple.
4250 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4251 if (abiCC != getLLVMDefaultCC())
4252 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004253}
4254
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004255/// isARMHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
Bob Wilsone826a2a2011-08-03 05:58:22 +00004256/// aggregate. If HAMembers is non-null, the number of base elements
4257/// contained in the type is returned through it; this is used for the
4258/// recursive calls that check aggregate component types.
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004259static bool isARMHomogeneousAggregate(QualType Ty, const Type *&Base,
4260 ASTContext &Context, bool isAArch64,
4261 uint64_t *HAMembers) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004262 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00004263 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004264 if (!isARMHomogeneousAggregate(AT->getElementType(), Base, Context, isAArch64, &Members))
Bob Wilsone826a2a2011-08-03 05:58:22 +00004265 return false;
4266 Members *= AT->getSize().getZExtValue();
4267 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4268 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004269 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00004270 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004271
Bob Wilsone826a2a2011-08-03 05:58:22 +00004272 Members = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004273 for (const auto *FD : RD->fields()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00004274 uint64_t FldMembers;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004275 if (!isARMHomogeneousAggregate(FD->getType(), Base, Context, isAArch64, &FldMembers))
Bob Wilsone826a2a2011-08-03 05:58:22 +00004276 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004277
4278 Members = (RD->isUnion() ?
4279 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00004280 }
4281 } else {
4282 Members = 1;
4283 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4284 Members = 2;
4285 Ty = CT->getElementType();
4286 }
4287
4288 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004289 // double, or 64-bit or 128-bit vectors. "long double" has the same machine
4290 // type as double, so it is also allowed as a base type.
4291 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4292 // point type or a short-vector type. This is the same as the 32-bit ABI,
4293 // but with the difference that any floating-point type is allowed,
4294 // including __fp16.
Bob Wilsone826a2a2011-08-03 05:58:22 +00004295 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004296 if (isAArch64) {
4297 if (!BT->isFloatingPoint())
4298 return false;
4299 } else {
4300 if (BT->getKind() != BuiltinType::Float &&
4301 BT->getKind() != BuiltinType::Double &&
4302 BT->getKind() != BuiltinType::LongDouble)
4303 return false;
4304 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004305 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4306 unsigned VecSize = Context.getTypeSize(VT);
4307 if (VecSize != 64 && VecSize != 128)
4308 return false;
4309 } else {
4310 return false;
4311 }
4312
4313 // The base type must be the same for all members. Vector types of the
4314 // same total size are treated as being equivalent here.
4315 const Type *TyPtr = Ty.getTypePtr();
4316 if (!Base)
4317 Base = TyPtr;
Oliver Stannard5e8558f2014-02-07 11:25:57 +00004318
4319 if (Base != TyPtr) {
4320 // Homogeneous aggregates are defined as containing members with the
4321 // same machine type. There are two cases in which two members have
4322 // different TypePtrs but the same machine type:
4323
4324 // 1) Vectors of the same length, regardless of the type and number
4325 // of their members.
4326 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
4327 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4328
4329 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
4330 // machine type. This is not the case for the 64-bit AAPCS.
4331 const bool SameSizeDoubles =
4332 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
4333 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
4334 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
4335 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
4336 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4337
4338 if (!SameLengthVectors && !SameSizeDoubles)
4339 return false;
4340 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004341 }
4342
4343 // Homogeneous Aggregates can have at most 4 members of the base type.
4344 if (HAMembers)
4345 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004346
4347 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00004348}
4349
Manman Renb505d332012-10-31 19:02:26 +00004350/// markAllocatedVFPs - update VFPRegs according to the alignment and
4351/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004352void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4353 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004354 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004355 if (AllocatedVFPs >= 16) {
4356 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4357 // the stack.
4358 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004359 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004360 }
Manman Renb505d332012-10-31 19:02:26 +00004361 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4362 // VFP registers of the appropriate type unallocated then the argument is
4363 // allocated to the lowest-numbered sequence of such registers.
4364 for (unsigned I = 0; I < 16; I += Alignment) {
4365 bool FoundSlot = true;
4366 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4367 if (J >= 16 || VFPRegs[J]) {
4368 FoundSlot = false;
4369 break;
4370 }
4371 if (FoundSlot) {
4372 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4373 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004374 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004375 return;
4376 }
4377 }
4378 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4379 // unallocated are marked as unavailable.
4380 for (unsigned I = 0; I < 16; I++)
4381 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004382 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004383}
4384
Oliver Stannard405bded2014-02-11 09:25:50 +00004385/// Update AllocatedGPRs to record the number of general purpose registers
4386/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4387/// this represents arguments being stored on the stack.
4388void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004389 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004390 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4391
4392 if (Alignment == 2 && AllocatedGPRs & 0x1)
4393 AllocatedGPRs += 1;
4394
4395 AllocatedGPRs += NumRequired;
4396}
4397
4398void ARMABIInfo::resetAllocatedRegs(void) const {
4399 AllocatedGPRs = 0;
4400 AllocatedVFPs = 0;
4401 for (unsigned i = 0; i < NumVFPs; ++i)
4402 VFPRegs[i] = 0;
4403}
4404
James Molloy6f244b62014-05-09 16:21:39 +00004405ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004406 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004407 // We update number of allocated VFPs according to
4408 // 6.1.2.1 The following argument types are VFP CPRCs:
4409 // A single-precision floating-point type (including promoted
4410 // half-precision types); A double-precision floating-point type;
4411 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4412 // with a Base Type of a single- or double-precision floating-point type,
4413 // 64-bit containerized vectors or 128-bit containerized vectors with one
4414 // to four Elements.
4415
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004416 const bool isAAPCS_VFP =
4417 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4418
Manman Renfef9e312012-10-16 19:18:39 +00004419 // Handle illegal vector types here.
4420 if (isIllegalVectorType(Ty)) {
4421 uint64_t Size = getContext().getTypeSize(Ty);
4422 if (Size <= 32) {
4423 llvm::Type *ResType =
4424 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004425 markAllocatedGPRs(1, 1);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004426 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004427 }
4428 if (Size == 64) {
4429 llvm::Type *ResType = llvm::VectorType::get(
4430 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004431 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4432 markAllocatedGPRs(2, 2);
4433 } else {
4434 markAllocatedVFPs(2, 2);
4435 IsCPRC = true;
4436 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004437 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004438 }
4439 if (Size == 128) {
4440 llvm::Type *ResType = llvm::VectorType::get(
4441 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004442 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4443 markAllocatedGPRs(2, 4);
4444 } else {
4445 markAllocatedVFPs(4, 4);
4446 IsCPRC = true;
4447 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004448 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004449 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004450 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004451 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4452 }
Manman Renb505d332012-10-31 19:02:26 +00004453 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004454 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4455 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4456 uint64_t Size = getContext().getTypeSize(VT);
4457 // Size of a legal vector should be power of 2 and above 64.
4458 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4459 IsCPRC = true;
4460 }
Manman Ren2a523d82012-10-30 23:21:41 +00004461 }
Manman Renb505d332012-10-31 19:02:26 +00004462 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004463 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4464 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4465 if (BT->getKind() == BuiltinType::Half ||
4466 BT->getKind() == BuiltinType::Float) {
4467 markAllocatedVFPs(1, 1);
4468 IsCPRC = true;
4469 }
4470 if (BT->getKind() == BuiltinType::Double ||
4471 BT->getKind() == BuiltinType::LongDouble) {
4472 markAllocatedVFPs(2, 2);
4473 IsCPRC = true;
4474 }
4475 }
Manman Ren2a523d82012-10-30 23:21:41 +00004476 }
Manman Renfef9e312012-10-16 19:18:39 +00004477
John McCalla1dee5302010-08-22 10:59:02 +00004478 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004479 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004480 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004481 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004482 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004483
Oliver Stannard405bded2014-02-11 09:25:50 +00004484 unsigned Size = getContext().getTypeSize(Ty);
4485 if (!IsCPRC)
4486 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004487 return (Ty->isPromotableIntegerType()
4488 ? ABIArgInfo::getExtend()
4489 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004490 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004491
Oliver Stannard405bded2014-02-11 09:25:50 +00004492 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4493 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004494 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004495 }
Tim Northover1060eae2013-06-21 22:49:34 +00004496
Daniel Dunbar09d33622009-09-14 21:54:03 +00004497 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004498 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004499 return ABIArgInfo::getIgnore();
4500
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004501 if (isAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004502 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4503 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004504 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004505 uint64_t Members = 0;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004506 if (isARMHomogeneousAggregate(Ty, Base, getContext(), false, &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004507 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004508 // Base can be a floating-point or a vector.
4509 if (Base->isVectorType()) {
4510 // ElementSize is in number of floats.
4511 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004512 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004513 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004514 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004515 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004516 else {
4517 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4518 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004519 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004520 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004521 IsCPRC = true;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004522 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004523 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004524 }
4525
Manman Ren6c30e132012-08-13 21:23:55 +00004526 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004527 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4528 // most 8-byte. We realign the indirect argument if type alignment is bigger
4529 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004530 uint64_t ABIAlign = 4;
4531 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4532 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4533 getABIKind() == ARMABIInfo::AAPCS)
4534 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004535 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004536 // Update Allocated GPRs. Since this is only used when the size of the
4537 // argument is greater than 64 bytes, this will always use up any available
4538 // registers (of which there are 4). We also don't care about getting the
4539 // alignment right, because general-purpose registers cannot be back-filled.
4540 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004541 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004542 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004543 }
4544
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004545 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004546 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004547 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004548 // FIXME: Try to match the types of the arguments more accurately where
4549 // we can.
4550 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004551 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4552 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004553 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004554 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004555 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4556 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004557 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004558 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004559
Chris Lattnera5f58b02011-07-09 17:41:47 +00004560 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00004561 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004562 return ABIArgInfo::getDirect(STy, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004563}
4564
Chris Lattner458b2aa2010-07-29 02:16:43 +00004565static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004566 llvm::LLVMContext &VMContext) {
4567 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4568 // is called integer-like if its size is less than or equal to one word, and
4569 // the offset of each of its addressable sub-fields is zero.
4570
4571 uint64_t Size = Context.getTypeSize(Ty);
4572
4573 // Check that the type fits in a word.
4574 if (Size > 32)
4575 return false;
4576
4577 // FIXME: Handle vector types!
4578 if (Ty->isVectorType())
4579 return false;
4580
Daniel Dunbard53bac72009-09-14 02:20:34 +00004581 // Float types are never treated as "integer like".
4582 if (Ty->isRealFloatingType())
4583 return false;
4584
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004585 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004586 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004587 return true;
4588
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004589 // Small complex integer types are "integer like".
4590 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4591 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004592
4593 // Single element and zero sized arrays should be allowed, by the definition
4594 // above, but they are not.
4595
4596 // Otherwise, it must be a record type.
4597 const RecordType *RT = Ty->getAs<RecordType>();
4598 if (!RT) return false;
4599
4600 // Ignore records with flexible arrays.
4601 const RecordDecl *RD = RT->getDecl();
4602 if (RD->hasFlexibleArrayMember())
4603 return false;
4604
4605 // Check that all sub-fields are at offset 0, and are themselves "integer
4606 // like".
4607 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4608
4609 bool HadField = false;
4610 unsigned idx = 0;
4611 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4612 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004613 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004614
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004615 // Bit-fields are not addressable, we only need to verify they are "integer
4616 // like". We still have to disallow a subsequent non-bitfield, for example:
4617 // struct { int : 0; int x }
4618 // is non-integer like according to gcc.
4619 if (FD->isBitField()) {
4620 if (!RD->isUnion())
4621 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004622
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004623 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4624 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004625
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004626 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004627 }
4628
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004629 // Check if this field is at offset 0.
4630 if (Layout.getFieldOffset(idx) != 0)
4631 return false;
4632
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004633 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4634 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004635
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004636 // Only allow at most one field in a structure. This doesn't match the
4637 // wording above, but follows gcc in situations with a field following an
4638 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004639 if (!RD->isUnion()) {
4640 if (HadField)
4641 return false;
4642
4643 HadField = true;
4644 }
4645 }
4646
4647 return true;
4648}
4649
Oliver Stannard405bded2014-02-11 09:25:50 +00004650ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4651 bool isVariadic) const {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004652 const bool isAAPCS_VFP =
4653 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4654
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004655 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004656 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004657
Daniel Dunbar19964db2010-09-23 01:54:32 +00004658 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004659 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4660 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004661 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004662 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004663
John McCalla1dee5302010-08-22 10:59:02 +00004664 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004665 // Treat an enum type as its underlying type.
4666 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4667 RetTy = EnumTy->getDecl()->getIntegerType();
4668
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004669 return (RetTy->isPromotableIntegerType()
4670 ? ABIArgInfo::getExtend()
4671 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004672 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004673
4674 // Are we following APCS?
4675 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004676 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004677 return ABIArgInfo::getIgnore();
4678
Daniel Dunbareedf1512010-02-01 23:31:19 +00004679 // Complex types are all returned as packed integers.
4680 //
4681 // FIXME: Consider using 2 x vector types if the back end handles them
4682 // correctly.
4683 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004684 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4685 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004686
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004687 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004688 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004689 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004690 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004691 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004692 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004693 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004694 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4695 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004696 }
4697
4698 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004699 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004700 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004701 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004702
4703 // Otherwise this is an AAPCS variant.
4704
Chris Lattner458b2aa2010-07-29 02:16:43 +00004705 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004706 return ABIArgInfo::getIgnore();
4707
Bob Wilson1d9269a2011-11-02 04:51:36 +00004708 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00004709 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Craig Topper8a13c412014-05-21 05:09:00 +00004710 const Type *Base = nullptr;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004711 if (isARMHomogeneousAggregate(RetTy, Base, getContext(), false)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004712 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004713 // Homogeneous Aggregates are returned directly.
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004714 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004715 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004716 }
4717
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004718 // Aggregates <= 4 bytes are returned in r0; other aggregates
4719 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004720 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004721 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004722 if (getDataLayout().isBigEndian())
4723 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004724 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4725 nullptr, !isAAPCS_VFP);
Christian Pirkerc3d32172014-07-03 09:28:12 +00004726
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004727 // Return in the smallest viable integer type.
4728 if (Size <= 8)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004729 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()), 0,
4730 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004731 if (Size <= 16)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004732 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()), 0,
4733 nullptr, !isAAPCS_VFP);
4734 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4735 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004736 }
4737
Oliver Stannard405bded2014-02-11 09:25:50 +00004738 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004739 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004740}
4741
Manman Renfef9e312012-10-16 19:18:39 +00004742/// isIllegalVector - check whether Ty is an illegal vector type.
4743bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4744 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4745 // Check whether VT is legal.
4746 unsigned NumElements = VT->getNumElements();
4747 uint64_t Size = getContext().getTypeSize(VT);
4748 // NumElements should be power of 2.
4749 if ((NumElements & (NumElements - 1)) != 0)
4750 return true;
4751 // Size should be greater than 32 bits.
4752 return Size <= 32;
4753 }
4754 return false;
4755}
4756
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004757llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004758 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004759 llvm::Type *BP = CGF.Int8PtrTy;
4760 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004761
4762 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004763 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004764 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004765
Tim Northover1711cc92013-06-21 23:05:33 +00004766 if (isEmptyRecord(getContext(), Ty, true)) {
4767 // These are ignored for parameter passing purposes.
4768 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4769 return Builder.CreateBitCast(Addr, PTy);
4770 }
4771
Manman Rencca54d02012-10-16 19:01:37 +00004772 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004773 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004774 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004775
4776 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4777 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004778 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4779 getABIKind() == ARMABIInfo::AAPCS)
4780 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4781 else
4782 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004783 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4784 if (isIllegalVectorType(Ty) && Size > 16) {
4785 IsIndirect = true;
4786 Size = 4;
4787 TyAlign = 4;
4788 }
Manman Rencca54d02012-10-16 19:01:37 +00004789
4790 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004791 if (TyAlign > 4) {
4792 assert((TyAlign & (TyAlign - 1)) == 0 &&
4793 "Alignment is not power of 2!");
4794 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4795 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4796 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004797 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004798 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004799
4800 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004801 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004802 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004803 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004804 "ap.next");
4805 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4806
Manman Renfef9e312012-10-16 19:18:39 +00004807 if (IsIndirect)
4808 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004809 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004810 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4811 // may not be correctly aligned for the vector type. We create an aligned
4812 // temporary space and copy the content over from ap.cur to the temporary
4813 // space. This is necessary if the natural alignment of the type is greater
4814 // than the ABI alignment.
4815 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4816 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4817 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4818 "var.align");
4819 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4820 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4821 Builder.CreateMemCpy(Dst, Src,
4822 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4823 TyAlign, false);
4824 Addr = AlignedTemp; //The content is in aligned location.
4825 }
4826 llvm::Type *PTy =
4827 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4828 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4829
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004830 return AddrTyped;
4831}
4832
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004833namespace {
4834
Derek Schuffa2020962012-10-16 22:30:41 +00004835class NaClARMABIInfo : public ABIInfo {
4836 public:
4837 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4838 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004839 void computeInfo(CGFunctionInfo &FI) const override;
4840 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4841 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00004842 private:
4843 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
4844 ARMABIInfo NInfo; // Used for everything else.
4845};
4846
4847class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
4848 public:
4849 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4850 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
4851};
4852
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004853}
4854
Derek Schuffa2020962012-10-16 22:30:41 +00004855void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4856 if (FI.getASTCallingConvention() == CC_PnaclCall)
4857 PInfo.computeInfo(FI);
4858 else
4859 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
4860}
4861
4862llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4863 CodeGenFunction &CGF) const {
4864 // Always use the native convention; calling pnacl-style varargs functions
4865 // is unsupported.
4866 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
4867}
4868
Chris Lattner0cf24192010-06-28 20:05:43 +00004869//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004870// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004871//===----------------------------------------------------------------------===//
4872
4873namespace {
4874
Justin Holewinski83e96682012-05-24 17:43:12 +00004875class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004876public:
Justin Holewinski36837432013-03-30 14:38:24 +00004877 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004878
4879 ABIArgInfo classifyReturnType(QualType RetTy) const;
4880 ABIArgInfo classifyArgumentType(QualType Ty) const;
4881
Craig Topper4f12f102014-03-12 06:41:41 +00004882 void computeInfo(CGFunctionInfo &FI) const override;
4883 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4884 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004885};
4886
Justin Holewinski83e96682012-05-24 17:43:12 +00004887class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004888public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004889 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4890 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004891
4892 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4893 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00004894private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00004895 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
4896 // resulting MDNode to the nvvm.annotations MDNode.
4897 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004898};
4899
Justin Holewinski83e96682012-05-24 17:43:12 +00004900ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004901 if (RetTy->isVoidType())
4902 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004903
4904 // note: this is different from default ABI
4905 if (!RetTy->isScalarType())
4906 return ABIArgInfo::getDirect();
4907
4908 // Treat an enum type as its underlying type.
4909 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4910 RetTy = EnumTy->getDecl()->getIntegerType();
4911
4912 return (RetTy->isPromotableIntegerType() ?
4913 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004914}
4915
Justin Holewinski83e96682012-05-24 17:43:12 +00004916ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004917 // Treat an enum type as its underlying type.
4918 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4919 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004920
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004921 return (Ty->isPromotableIntegerType() ?
4922 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004923}
4924
Justin Holewinski83e96682012-05-24 17:43:12 +00004925void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004926 if (!getCXXABI().classifyReturnType(FI))
4927 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004928 for (auto &I : FI.arguments())
4929 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004930
4931 // Always honor user-specified calling convention.
4932 if (FI.getCallingConvention() != llvm::CallingConv::C)
4933 return;
4934
John McCall882987f2013-02-28 19:01:20 +00004935 FI.setEffectiveCallingConvention(getRuntimeCC());
4936}
4937
Justin Holewinski83e96682012-05-24 17:43:12 +00004938llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4939 CodeGenFunction &CFG) const {
4940 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004941}
4942
Justin Holewinski83e96682012-05-24 17:43:12 +00004943void NVPTXTargetCodeGenInfo::
4944SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4945 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004946 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4947 if (!FD) return;
4948
4949 llvm::Function *F = cast<llvm::Function>(GV);
4950
4951 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004952 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004953 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004954 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004955 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004956 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00004957 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4958 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00004959 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004960 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004961 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004962 }
Justin Holewinski38031972011-10-05 17:58:44 +00004963
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004964 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004965 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004966 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004967 // __global__ functions cannot be called from the device, we do not
4968 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00004969 if (FD->hasAttr<CUDAGlobalAttr>()) {
4970 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4971 addNVVMMetadata(F, "kernel", 1);
4972 }
4973 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
4974 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
4975 addNVVMMetadata(F, "maxntidx",
4976 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
4977 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
4978 // zero value from getMinBlocks either means it was not specified in
4979 // __launch_bounds__ or the user specified a 0 value. In both cases, we
4980 // don't have to add a PTX directive.
4981 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
4982 if (MinCTASM > 0) {
4983 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
4984 addNVVMMetadata(F, "minctasm", MinCTASM);
4985 }
4986 }
Justin Holewinski38031972011-10-05 17:58:44 +00004987 }
4988}
4989
Eli Benderskye06a2c42014-04-15 16:57:05 +00004990void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
4991 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00004992 llvm::Module *M = F->getParent();
4993 llvm::LLVMContext &Ctx = M->getContext();
4994
4995 // Get "nvvm.annotations" metadata node
4996 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4997
Eli Benderskye1627b42014-04-15 17:19:26 +00004998 llvm::Value *MDVals[] = {
4999 F, llvm::MDString::get(Ctx, Name),
5000 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinski36837432013-03-30 14:38:24 +00005001 // Append metadata to nvvm.annotations
5002 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5003}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005004}
5005
5006//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005007// SystemZ ABI Implementation
5008//===----------------------------------------------------------------------===//
5009
5010namespace {
5011
5012class SystemZABIInfo : public ABIInfo {
5013public:
5014 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5015
5016 bool isPromotableIntegerType(QualType Ty) const;
5017 bool isCompoundType(QualType Ty) const;
5018 bool isFPArgumentType(QualType Ty) const;
5019
5020 ABIArgInfo classifyReturnType(QualType RetTy) const;
5021 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5022
Craig Topper4f12f102014-03-12 06:41:41 +00005023 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005024 if (!getCXXABI().classifyReturnType(FI))
5025 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005026 for (auto &I : FI.arguments())
5027 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005028 }
5029
Craig Topper4f12f102014-03-12 06:41:41 +00005030 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5031 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005032};
5033
5034class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5035public:
5036 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5037 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5038};
5039
5040}
5041
5042bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5043 // Treat an enum type as its underlying type.
5044 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5045 Ty = EnumTy->getDecl()->getIntegerType();
5046
5047 // Promotable integer types are required to be promoted by the ABI.
5048 if (Ty->isPromotableIntegerType())
5049 return true;
5050
5051 // 32-bit values must also be promoted.
5052 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5053 switch (BT->getKind()) {
5054 case BuiltinType::Int:
5055 case BuiltinType::UInt:
5056 return true;
5057 default:
5058 return false;
5059 }
5060 return false;
5061}
5062
5063bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5064 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5065}
5066
5067bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5068 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5069 switch (BT->getKind()) {
5070 case BuiltinType::Float:
5071 case BuiltinType::Double:
5072 return true;
5073 default:
5074 return false;
5075 }
5076
5077 if (const RecordType *RT = Ty->getAsStructureType()) {
5078 const RecordDecl *RD = RT->getDecl();
5079 bool Found = false;
5080
5081 // If this is a C++ record, check the bases first.
5082 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005083 for (const auto &I : CXXRD->bases()) {
5084 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005085
5086 // Empty bases don't affect things either way.
5087 if (isEmptyRecord(getContext(), Base, true))
5088 continue;
5089
5090 if (Found)
5091 return false;
5092 Found = isFPArgumentType(Base);
5093 if (!Found)
5094 return false;
5095 }
5096
5097 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005098 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005099 // Empty bitfields don't affect things either way.
5100 // Unlike isSingleElementStruct(), empty structure and array fields
5101 // do count. So do anonymous bitfields that aren't zero-sized.
5102 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5103 return true;
5104
5105 // Unlike isSingleElementStruct(), arrays do not count.
5106 // Nested isFPArgumentType structures still do though.
5107 if (Found)
5108 return false;
5109 Found = isFPArgumentType(FD->getType());
5110 if (!Found)
5111 return false;
5112 }
5113
5114 // Unlike isSingleElementStruct(), trailing padding is allowed.
5115 // An 8-byte aligned struct s { float f; } is passed as a double.
5116 return Found;
5117 }
5118
5119 return false;
5120}
5121
5122llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5123 CodeGenFunction &CGF) const {
5124 // Assume that va_list type is correct; should be pointer to LLVM type:
5125 // struct {
5126 // i64 __gpr;
5127 // i64 __fpr;
5128 // i8 *__overflow_arg_area;
5129 // i8 *__reg_save_area;
5130 // };
5131
5132 // Every argument occupies 8 bytes and is passed by preference in either
5133 // GPRs or FPRs.
5134 Ty = CGF.getContext().getCanonicalType(Ty);
5135 ABIArgInfo AI = classifyArgumentType(Ty);
5136 bool InFPRs = isFPArgumentType(Ty);
5137
5138 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5139 bool IsIndirect = AI.isIndirect();
5140 unsigned UnpaddedBitSize;
5141 if (IsIndirect) {
5142 APTy = llvm::PointerType::getUnqual(APTy);
5143 UnpaddedBitSize = 64;
5144 } else
5145 UnpaddedBitSize = getContext().getTypeSize(Ty);
5146 unsigned PaddedBitSize = 64;
5147 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5148
5149 unsigned PaddedSize = PaddedBitSize / 8;
5150 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5151
5152 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5153 if (InFPRs) {
5154 MaxRegs = 4; // Maximum of 4 FPR arguments
5155 RegCountField = 1; // __fpr
5156 RegSaveIndex = 16; // save offset for f0
5157 RegPadding = 0; // floats are passed in the high bits of an FPR
5158 } else {
5159 MaxRegs = 5; // Maximum of 5 GPR arguments
5160 RegCountField = 0; // __gpr
5161 RegSaveIndex = 2; // save offset for r2
5162 RegPadding = Padding; // values are passed in the low bits of a GPR
5163 }
5164
5165 llvm::Value *RegCountPtr =
5166 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5167 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5168 llvm::Type *IndexTy = RegCount->getType();
5169 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5170 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005171 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005172
5173 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5174 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5175 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5176 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5177
5178 // Emit code to load the value if it was passed in registers.
5179 CGF.EmitBlock(InRegBlock);
5180
5181 // Work out the address of an argument register.
5182 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5183 llvm::Value *ScaledRegCount =
5184 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5185 llvm::Value *RegBase =
5186 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5187 llvm::Value *RegOffset =
5188 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5189 llvm::Value *RegSaveAreaPtr =
5190 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5191 llvm::Value *RegSaveArea =
5192 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5193 llvm::Value *RawRegAddr =
5194 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5195 llvm::Value *RegAddr =
5196 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5197
5198 // Update the register count
5199 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5200 llvm::Value *NewRegCount =
5201 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5202 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5203 CGF.EmitBranch(ContBlock);
5204
5205 // Emit code to load the value if it was passed in memory.
5206 CGF.EmitBlock(InMemBlock);
5207
5208 // Work out the address of a stack argument.
5209 llvm::Value *OverflowArgAreaPtr =
5210 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5211 llvm::Value *OverflowArgArea =
5212 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5213 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5214 llvm::Value *RawMemAddr =
5215 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5216 llvm::Value *MemAddr =
5217 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5218
5219 // Update overflow_arg_area_ptr pointer
5220 llvm::Value *NewOverflowArgArea =
5221 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5222 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5223 CGF.EmitBranch(ContBlock);
5224
5225 // Return the appropriate result.
5226 CGF.EmitBlock(ContBlock);
5227 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5228 ResAddr->addIncoming(RegAddr, InRegBlock);
5229 ResAddr->addIncoming(MemAddr, InMemBlock);
5230
5231 if (IsIndirect)
5232 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5233
5234 return ResAddr;
5235}
5236
Ulrich Weigand47445072013-05-06 16:26:41 +00005237ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5238 if (RetTy->isVoidType())
5239 return ABIArgInfo::getIgnore();
5240 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5241 return ABIArgInfo::getIndirect(0);
5242 return (isPromotableIntegerType(RetTy) ?
5243 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5244}
5245
5246ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5247 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005248 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005249 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5250
5251 // Integers and enums are extended to full register width.
5252 if (isPromotableIntegerType(Ty))
5253 return ABIArgInfo::getExtend();
5254
5255 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5256 uint64_t Size = getContext().getTypeSize(Ty);
5257 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005258 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005259
5260 // Handle small structures.
5261 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5262 // Structures with flexible arrays have variable length, so really
5263 // fail the size test above.
5264 const RecordDecl *RD = RT->getDecl();
5265 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005266 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005267
5268 // The structure is passed as an unextended integer, a float, or a double.
5269 llvm::Type *PassTy;
5270 if (isFPArgumentType(Ty)) {
5271 assert(Size == 32 || Size == 64);
5272 if (Size == 32)
5273 PassTy = llvm::Type::getFloatTy(getVMContext());
5274 else
5275 PassTy = llvm::Type::getDoubleTy(getVMContext());
5276 } else
5277 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5278 return ABIArgInfo::getDirect(PassTy);
5279 }
5280
5281 // Non-structure compounds are passed indirectly.
5282 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005283 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005284
Craig Topper8a13c412014-05-21 05:09:00 +00005285 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005286}
5287
5288//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005289// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005290//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005291
5292namespace {
5293
5294class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5295public:
Chris Lattner2b037972010-07-29 02:01:43 +00005296 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5297 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005298 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005299 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005300};
5301
5302}
5303
5304void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5305 llvm::GlobalValue *GV,
5306 CodeGen::CodeGenModule &M) const {
5307 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5308 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5309 // Handle 'interrupt' attribute:
5310 llvm::Function *F = cast<llvm::Function>(GV);
5311
5312 // Step 1: Set ISR calling convention.
5313 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5314
5315 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005316 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005317
5318 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005319 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005320 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5321 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005322 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005323 }
5324}
5325
Chris Lattner0cf24192010-06-28 20:05:43 +00005326//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005327// MIPS ABI Implementation. This works for both little-endian and
5328// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005329//===----------------------------------------------------------------------===//
5330
John McCall943fae92010-05-27 06:19:26 +00005331namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005332class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005333 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005334 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5335 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005336 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005337 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005338 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005339 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005340public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005341 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005342 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005343 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005344
5345 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005346 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005347 void computeInfo(CGFunctionInfo &FI) const override;
5348 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5349 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005350};
5351
John McCall943fae92010-05-27 06:19:26 +00005352class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005353 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005354public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005355 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5356 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005357 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005358
Craig Topper4f12f102014-03-12 06:41:41 +00005359 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005360 return 29;
5361 }
5362
Reed Kotler373feca2013-01-16 17:10:28 +00005363 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005364 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005365 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5366 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005367 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005368 if (FD->hasAttr<Mips16Attr>()) {
5369 Fn->addFnAttr("mips16");
5370 }
5371 else if (FD->hasAttr<NoMips16Attr>()) {
5372 Fn->addFnAttr("nomips16");
5373 }
Reed Kotler373feca2013-01-16 17:10:28 +00005374 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005375
John McCall943fae92010-05-27 06:19:26 +00005376 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005377 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005378
Craig Topper4f12f102014-03-12 06:41:41 +00005379 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005380 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005381 }
John McCall943fae92010-05-27 06:19:26 +00005382};
5383}
5384
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005385void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005386 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005387 llvm::IntegerType *IntTy =
5388 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005389
5390 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5391 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5392 ArgList.push_back(IntTy);
5393
5394 // If necessary, add one more integer type to ArgList.
5395 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5396
5397 if (R)
5398 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005399}
5400
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005401// In N32/64, an aligned double precision floating point field is passed in
5402// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005403llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005404 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5405
5406 if (IsO32) {
5407 CoerceToIntArgs(TySize, ArgList);
5408 return llvm::StructType::get(getVMContext(), ArgList);
5409 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005410
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005411 if (Ty->isComplexType())
5412 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005413
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005414 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005415
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005416 // Unions/vectors are passed in integer registers.
5417 if (!RT || !RT->isStructureOrClassType()) {
5418 CoerceToIntArgs(TySize, ArgList);
5419 return llvm::StructType::get(getVMContext(), ArgList);
5420 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005421
5422 const RecordDecl *RD = RT->getDecl();
5423 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005424 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005425
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005426 uint64_t LastOffset = 0;
5427 unsigned idx = 0;
5428 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5429
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005430 // Iterate over fields in the struct/class and check if there are any aligned
5431 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005432 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5433 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005434 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005435 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5436
5437 if (!BT || BT->getKind() != BuiltinType::Double)
5438 continue;
5439
5440 uint64_t Offset = Layout.getFieldOffset(idx);
5441 if (Offset % 64) // Ignore doubles that are not aligned.
5442 continue;
5443
5444 // Add ((Offset - LastOffset) / 64) args of type i64.
5445 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5446 ArgList.push_back(I64);
5447
5448 // Add double type.
5449 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5450 LastOffset = Offset + 64;
5451 }
5452
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005453 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5454 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005455
5456 return llvm::StructType::get(getVMContext(), ArgList);
5457}
5458
Akira Hatanakaddd66342013-10-29 18:41:15 +00005459llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5460 uint64_t Offset) const {
5461 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005462 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005463
Akira Hatanakaddd66342013-10-29 18:41:15 +00005464 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005465}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005466
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005467ABIArgInfo
5468MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005469 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005470 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005471 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005472
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005473 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5474 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005475 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5476 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005477
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005478 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005479 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005480 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005481 return ABIArgInfo::getIgnore();
5482
Mark Lacey3825e832013-10-06 01:33:34 +00005483 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005484 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005485 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005486 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005487
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005488 // If we have reached here, aggregates are passed directly by coercing to
5489 // another structure type. Padding is inserted if the offset of the
5490 // aggregate is unaligned.
5491 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00005492 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005493 }
5494
5495 // Treat an enum type as its underlying type.
5496 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5497 Ty = EnumTy->getDecl()->getIntegerType();
5498
Akira Hatanaka1632af62012-01-09 19:31:25 +00005499 if (Ty->isPromotableIntegerType())
5500 return ABIArgInfo::getExtend();
5501
Akira Hatanakaddd66342013-10-29 18:41:15 +00005502 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005503 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005504}
5505
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005506llvm::Type*
5507MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005508 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005509 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005510
Akira Hatanakab6f74432012-02-09 18:49:26 +00005511 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005512 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005513 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5514 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005515
Akira Hatanakab6f74432012-02-09 18:49:26 +00005516 // N32/64 returns struct/classes in floating point registers if the
5517 // following conditions are met:
5518 // 1. The size of the struct/class is no larger than 128-bit.
5519 // 2. The struct/class has one or two fields all of which are floating
5520 // point types.
5521 // 3. The offset of the first field is zero (this follows what gcc does).
5522 //
5523 // Any other composite results are returned in integer registers.
5524 //
5525 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5526 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5527 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005528 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005529
Akira Hatanakab6f74432012-02-09 18:49:26 +00005530 if (!BT || !BT->isFloatingPoint())
5531 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005532
David Blaikie2d7c57e2012-04-30 02:36:29 +00005533 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005534 }
5535
5536 if (b == e)
5537 return llvm::StructType::get(getVMContext(), RTList,
5538 RD->hasAttr<PackedAttr>());
5539
5540 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005541 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005542 }
5543
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005544 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005545 return llvm::StructType::get(getVMContext(), RTList);
5546}
5547
Akira Hatanakab579fe52011-06-02 00:09:17 +00005548ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005549 uint64_t Size = getContext().getTypeSize(RetTy);
5550
Daniel Sandersed39f582014-09-04 13:28:14 +00005551 if (RetTy->isVoidType())
5552 return ABIArgInfo::getIgnore();
5553
5554 // O32 doesn't treat zero-sized structs differently from other structs.
5555 // However, N32/N64 ignores zero sized return values.
5556 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005557 return ABIArgInfo::getIgnore();
5558
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005559 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005560 if (Size <= 128) {
5561 if (RetTy->isAnyComplexType())
5562 return ABIArgInfo::getDirect();
5563
Daniel Sanderse5018b62014-09-04 15:05:39 +00005564 // O32 returns integer vectors in registers and N32/N64 returns all small
5565 // aggregates in registers..
5566 if (!IsO32 ||
5567 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5568 ABIArgInfo ArgInfo =
5569 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5570 ArgInfo.setInReg(true);
5571 return ArgInfo;
5572 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005573 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005574
5575 return ABIArgInfo::getIndirect(0);
5576 }
5577
5578 // Treat an enum type as its underlying type.
5579 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5580 RetTy = EnumTy->getDecl()->getIntegerType();
5581
5582 return (RetTy->isPromotableIntegerType() ?
5583 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5584}
5585
5586void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005587 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005588 if (!getCXXABI().classifyReturnType(FI))
5589 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005590
5591 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005592 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005593
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005594 for (auto &I : FI.arguments())
5595 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005596}
5597
5598llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5599 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005600 llvm::Type *BP = CGF.Int8PtrTy;
5601 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5602
5603 CGBuilderTy &Builder = CGF.Builder;
5604 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5605 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5606 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
5607 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5608 llvm::Value *AddrTyped;
5609 unsigned PtrWidth = getTarget().getPointerWidth(0);
5610 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5611
5612 if (TypeAlign > MinABIStackAlignInBytes) {
5613 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5614 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5615 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5616 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5617 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5618 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5619 }
5620 else
5621 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5622
5623 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5624 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
5625 uint64_t Offset =
5626 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5627 llvm::Value *NextAddr =
5628 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5629 "ap.next");
5630 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5631
5632 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005633}
5634
John McCall943fae92010-05-27 06:19:26 +00005635bool
5636MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5637 llvm::Value *Address) const {
5638 // This information comes from gcc's implementation, which seems to
5639 // as canonical as it gets.
5640
John McCall943fae92010-05-27 06:19:26 +00005641 // Everything on MIPS is 4 bytes. Double-precision FP registers
5642 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005643 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005644
5645 // 0-31 are the general purpose registers, $0 - $31.
5646 // 32-63 are the floating-point registers, $f0 - $f31.
5647 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5648 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005649 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005650
5651 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5652 // They are one bit wide and ignored here.
5653
5654 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5655 // (coprocessor 1 is the FP unit)
5656 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5657 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5658 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005659 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005660 return false;
5661}
5662
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005663//===----------------------------------------------------------------------===//
5664// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5665// Currently subclassed only to implement custom OpenCL C function attribute
5666// handling.
5667//===----------------------------------------------------------------------===//
5668
5669namespace {
5670
5671class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5672public:
5673 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5674 : DefaultTargetCodeGenInfo(CGT) {}
5675
Craig Topper4f12f102014-03-12 06:41:41 +00005676 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5677 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005678};
5679
5680void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5681 llvm::GlobalValue *GV,
5682 CodeGen::CodeGenModule &M) const {
5683 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5684 if (!FD) return;
5685
5686 llvm::Function *F = cast<llvm::Function>(GV);
5687
David Blaikiebbafb8a2012-03-11 07:00:24 +00005688 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005689 if (FD->hasAttr<OpenCLKernelAttr>()) {
5690 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005691 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005692 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5693 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005694 // Convert the reqd_work_group_size() attributes to metadata.
5695 llvm::LLVMContext &Context = F->getContext();
5696 llvm::NamedMDNode *OpenCLMetadata =
5697 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5698
5699 SmallVector<llvm::Value*, 5> Operands;
5700 Operands.push_back(F);
5701
Chris Lattnerece04092012-02-07 00:39:47 +00005702 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005703 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005704 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005705 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005706 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005707 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005708
5709 // Add a boolean constant operand for "required" (true) or "hint" (false)
5710 // for implementing the work_group_size_hint attr later. Currently
5711 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005712 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005713 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5714 }
5715 }
5716 }
5717}
5718
5719}
John McCall943fae92010-05-27 06:19:26 +00005720
Tony Linthicum76329bf2011-12-12 21:14:55 +00005721//===----------------------------------------------------------------------===//
5722// Hexagon ABI Implementation
5723//===----------------------------------------------------------------------===//
5724
5725namespace {
5726
5727class HexagonABIInfo : public ABIInfo {
5728
5729
5730public:
5731 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5732
5733private:
5734
5735 ABIArgInfo classifyReturnType(QualType RetTy) const;
5736 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5737
Craig Topper4f12f102014-03-12 06:41:41 +00005738 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005739
Craig Topper4f12f102014-03-12 06:41:41 +00005740 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5741 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005742};
5743
5744class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5745public:
5746 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5747 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5748
Craig Topper4f12f102014-03-12 06:41:41 +00005749 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005750 return 29;
5751 }
5752};
5753
5754}
5755
5756void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005757 if (!getCXXABI().classifyReturnType(FI))
5758 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005759 for (auto &I : FI.arguments())
5760 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005761}
5762
5763ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5764 if (!isAggregateTypeForABI(Ty)) {
5765 // Treat an enum type as its underlying type.
5766 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5767 Ty = EnumTy->getDecl()->getIntegerType();
5768
5769 return (Ty->isPromotableIntegerType() ?
5770 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5771 }
5772
5773 // Ignore empty records.
5774 if (isEmptyRecord(getContext(), Ty, true))
5775 return ABIArgInfo::getIgnore();
5776
Mark Lacey3825e832013-10-06 01:33:34 +00005777 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005778 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005779
5780 uint64_t Size = getContext().getTypeSize(Ty);
5781 if (Size > 64)
5782 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5783 // Pass in the smallest viable integer type.
5784 else if (Size > 32)
5785 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5786 else if (Size > 16)
5787 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5788 else if (Size > 8)
5789 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5790 else
5791 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5792}
5793
5794ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5795 if (RetTy->isVoidType())
5796 return ABIArgInfo::getIgnore();
5797
5798 // Large vector types should be returned via memory.
5799 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5800 return ABIArgInfo::getIndirect(0);
5801
5802 if (!isAggregateTypeForABI(RetTy)) {
5803 // Treat an enum type as its underlying type.
5804 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5805 RetTy = EnumTy->getDecl()->getIntegerType();
5806
5807 return (RetTy->isPromotableIntegerType() ?
5808 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5809 }
5810
Tony Linthicum76329bf2011-12-12 21:14:55 +00005811 if (isEmptyRecord(getContext(), RetTy, true))
5812 return ABIArgInfo::getIgnore();
5813
5814 // Aggregates <= 8 bytes are returned in r0; other aggregates
5815 // are returned indirectly.
5816 uint64_t Size = getContext().getTypeSize(RetTy);
5817 if (Size <= 64) {
5818 // Return in the smallest viable integer type.
5819 if (Size <= 8)
5820 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5821 if (Size <= 16)
5822 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5823 if (Size <= 32)
5824 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5825 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5826 }
5827
5828 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5829}
5830
5831llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005832 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005833 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005834 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005835
5836 CGBuilderTy &Builder = CGF.Builder;
5837 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5838 "ap");
5839 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5840 llvm::Type *PTy =
5841 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5842 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5843
5844 uint64_t Offset =
5845 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5846 llvm::Value *NextAddr =
5847 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5848 "ap.next");
5849 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5850
5851 return AddrTyped;
5852}
5853
5854
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005855//===----------------------------------------------------------------------===//
5856// SPARC v9 ABI Implementation.
5857// Based on the SPARC Compliance Definition version 2.4.1.
5858//
5859// Function arguments a mapped to a nominal "parameter array" and promoted to
5860// registers depending on their type. Each argument occupies 8 or 16 bytes in
5861// the array, structs larger than 16 bytes are passed indirectly.
5862//
5863// One case requires special care:
5864//
5865// struct mixed {
5866// int i;
5867// float f;
5868// };
5869//
5870// When a struct mixed is passed by value, it only occupies 8 bytes in the
5871// parameter array, but the int is passed in an integer register, and the float
5872// is passed in a floating point register. This is represented as two arguments
5873// with the LLVM IR inreg attribute:
5874//
5875// declare void f(i32 inreg %i, float inreg %f)
5876//
5877// The code generator will only allocate 4 bytes from the parameter array for
5878// the inreg arguments. All other arguments are allocated a multiple of 8
5879// bytes.
5880//
5881namespace {
5882class SparcV9ABIInfo : public ABIInfo {
5883public:
5884 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5885
5886private:
5887 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005888 void computeInfo(CGFunctionInfo &FI) const override;
5889 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5890 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005891
5892 // Coercion type builder for structs passed in registers. The coercion type
5893 // serves two purposes:
5894 //
5895 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5896 // in registers.
5897 // 2. Expose aligned floating point elements as first-level elements, so the
5898 // code generator knows to pass them in floating point registers.
5899 //
5900 // We also compute the InReg flag which indicates that the struct contains
5901 // aligned 32-bit floats.
5902 //
5903 struct CoerceBuilder {
5904 llvm::LLVMContext &Context;
5905 const llvm::DataLayout &DL;
5906 SmallVector<llvm::Type*, 8> Elems;
5907 uint64_t Size;
5908 bool InReg;
5909
5910 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5911 : Context(c), DL(dl), Size(0), InReg(false) {}
5912
5913 // Pad Elems with integers until Size is ToSize.
5914 void pad(uint64_t ToSize) {
5915 assert(ToSize >= Size && "Cannot remove elements");
5916 if (ToSize == Size)
5917 return;
5918
5919 // Finish the current 64-bit word.
5920 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5921 if (Aligned > Size && Aligned <= ToSize) {
5922 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5923 Size = Aligned;
5924 }
5925
5926 // Add whole 64-bit words.
5927 while (Size + 64 <= ToSize) {
5928 Elems.push_back(llvm::Type::getInt64Ty(Context));
5929 Size += 64;
5930 }
5931
5932 // Final in-word padding.
5933 if (Size < ToSize) {
5934 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5935 Size = ToSize;
5936 }
5937 }
5938
5939 // Add a floating point element at Offset.
5940 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5941 // Unaligned floats are treated as integers.
5942 if (Offset % Bits)
5943 return;
5944 // The InReg flag is only required if there are any floats < 64 bits.
5945 if (Bits < 64)
5946 InReg = true;
5947 pad(Offset);
5948 Elems.push_back(Ty);
5949 Size = Offset + Bits;
5950 }
5951
5952 // Add a struct type to the coercion type, starting at Offset (in bits).
5953 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5954 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5955 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5956 llvm::Type *ElemTy = StrTy->getElementType(i);
5957 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5958 switch (ElemTy->getTypeID()) {
5959 case llvm::Type::StructTyID:
5960 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5961 break;
5962 case llvm::Type::FloatTyID:
5963 addFloat(ElemOffset, ElemTy, 32);
5964 break;
5965 case llvm::Type::DoubleTyID:
5966 addFloat(ElemOffset, ElemTy, 64);
5967 break;
5968 case llvm::Type::FP128TyID:
5969 addFloat(ElemOffset, ElemTy, 128);
5970 break;
5971 case llvm::Type::PointerTyID:
5972 if (ElemOffset % 64 == 0) {
5973 pad(ElemOffset);
5974 Elems.push_back(ElemTy);
5975 Size += 64;
5976 }
5977 break;
5978 default:
5979 break;
5980 }
5981 }
5982 }
5983
5984 // Check if Ty is a usable substitute for the coercion type.
5985 bool isUsableType(llvm::StructType *Ty) const {
5986 if (Ty->getNumElements() != Elems.size())
5987 return false;
5988 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5989 if (Elems[i] != Ty->getElementType(i))
5990 return false;
5991 return true;
5992 }
5993
5994 // Get the coercion type as a literal struct type.
5995 llvm::Type *getType() const {
5996 if (Elems.size() == 1)
5997 return Elems.front();
5998 else
5999 return llvm::StructType::get(Context, Elems);
6000 }
6001 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006002};
6003} // end anonymous namespace
6004
6005ABIArgInfo
6006SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6007 if (Ty->isVoidType())
6008 return ABIArgInfo::getIgnore();
6009
6010 uint64_t Size = getContext().getTypeSize(Ty);
6011
6012 // Anything too big to fit in registers is passed with an explicit indirect
6013 // pointer / sret pointer.
6014 if (Size > SizeLimit)
6015 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6016
6017 // Treat an enum type as its underlying type.
6018 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6019 Ty = EnumTy->getDecl()->getIntegerType();
6020
6021 // Integer types smaller than a register are extended.
6022 if (Size < 64 && Ty->isIntegerType())
6023 return ABIArgInfo::getExtend();
6024
6025 // Other non-aggregates go in registers.
6026 if (!isAggregateTypeForABI(Ty))
6027 return ABIArgInfo::getDirect();
6028
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006029 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6030 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6031 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6032 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6033
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006034 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006035 // Build a coercion type from the LLVM struct type.
6036 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6037 if (!StrTy)
6038 return ABIArgInfo::getDirect();
6039
6040 CoerceBuilder CB(getVMContext(), getDataLayout());
6041 CB.addStruct(0, StrTy);
6042 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6043
6044 // Try to use the original type for coercion.
6045 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6046
6047 if (CB.InReg)
6048 return ABIArgInfo::getDirectInReg(CoerceTy);
6049 else
6050 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006051}
6052
6053llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6054 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006055 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6056 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6057 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6058 AI.setCoerceToType(ArgTy);
6059
6060 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6061 CGBuilderTy &Builder = CGF.Builder;
6062 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6063 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6064 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6065 llvm::Value *ArgAddr;
6066 unsigned Stride;
6067
6068 switch (AI.getKind()) {
6069 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006070 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006071 llvm_unreachable("Unsupported ABI kind for va_arg");
6072
6073 case ABIArgInfo::Extend:
6074 Stride = 8;
6075 ArgAddr = Builder
6076 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6077 "extend");
6078 break;
6079
6080 case ABIArgInfo::Direct:
6081 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6082 ArgAddr = Addr;
6083 break;
6084
6085 case ABIArgInfo::Indirect:
6086 Stride = 8;
6087 ArgAddr = Builder.CreateBitCast(Addr,
6088 llvm::PointerType::getUnqual(ArgPtrTy),
6089 "indirect");
6090 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6091 break;
6092
6093 case ABIArgInfo::Ignore:
6094 return llvm::UndefValue::get(ArgPtrTy);
6095 }
6096
6097 // Update VAList.
6098 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6099 Builder.CreateStore(Addr, VAListAddrAsBPP);
6100
6101 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006102}
6103
6104void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6105 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006106 for (auto &I : FI.arguments())
6107 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006108}
6109
6110namespace {
6111class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6112public:
6113 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6114 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006115
Craig Topper4f12f102014-03-12 06:41:41 +00006116 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006117 return 14;
6118 }
6119
6120 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006121 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006122};
6123} // end anonymous namespace
6124
Roman Divackyf02c9942014-02-24 18:46:27 +00006125bool
6126SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6127 llvm::Value *Address) const {
6128 // This is calculated from the LLVM and GCC tables and verified
6129 // against gcc output. AFAIK all ABIs use the same encoding.
6130
6131 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6132
6133 llvm::IntegerType *i8 = CGF.Int8Ty;
6134 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6135 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6136
6137 // 0-31: the 8-byte general-purpose registers
6138 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6139
6140 // 32-63: f0-31, the 4-byte floating-point registers
6141 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6142
6143 // Y = 64
6144 // PSR = 65
6145 // WIM = 66
6146 // TBR = 67
6147 // PC = 68
6148 // NPC = 69
6149 // FSR = 70
6150 // CSR = 71
6151 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6152
6153 // 72-87: d0-15, the 8-byte floating-point registers
6154 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6155
6156 return false;
6157}
6158
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006159
Robert Lytton0e076492013-08-13 09:43:10 +00006160//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006161// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006162//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006163
Robert Lytton0e076492013-08-13 09:43:10 +00006164namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006165
6166/// A SmallStringEnc instance is used to build up the TypeString by passing
6167/// it by reference between functions that append to it.
6168typedef llvm::SmallString<128> SmallStringEnc;
6169
6170/// TypeStringCache caches the meta encodings of Types.
6171///
6172/// The reason for caching TypeStrings is two fold:
6173/// 1. To cache a type's encoding for later uses;
6174/// 2. As a means to break recursive member type inclusion.
6175///
6176/// A cache Entry can have a Status of:
6177/// NonRecursive: The type encoding is not recursive;
6178/// Recursive: The type encoding is recursive;
6179/// Incomplete: An incomplete TypeString;
6180/// IncompleteUsed: An incomplete TypeString that has been used in a
6181/// Recursive type encoding.
6182///
6183/// A NonRecursive entry will have all of its sub-members expanded as fully
6184/// as possible. Whilst it may contain types which are recursive, the type
6185/// itself is not recursive and thus its encoding may be safely used whenever
6186/// the type is encountered.
6187///
6188/// A Recursive entry will have all of its sub-members expanded as fully as
6189/// possible. The type itself is recursive and it may contain other types which
6190/// are recursive. The Recursive encoding must not be used during the expansion
6191/// of a recursive type's recursive branch. For simplicity the code uses
6192/// IncompleteCount to reject all usage of Recursive encodings for member types.
6193///
6194/// An Incomplete entry is always a RecordType and only encodes its
6195/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6196/// are placed into the cache during type expansion as a means to identify and
6197/// handle recursive inclusion of types as sub-members. If there is recursion
6198/// the entry becomes IncompleteUsed.
6199///
6200/// During the expansion of a RecordType's members:
6201///
6202/// If the cache contains a NonRecursive encoding for the member type, the
6203/// cached encoding is used;
6204///
6205/// If the cache contains a Recursive encoding for the member type, the
6206/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6207///
6208/// If the member is a RecordType, an Incomplete encoding is placed into the
6209/// cache to break potential recursive inclusion of itself as a sub-member;
6210///
6211/// Once a member RecordType has been expanded, its temporary incomplete
6212/// entry is removed from the cache. If a Recursive encoding was swapped out
6213/// it is swapped back in;
6214///
6215/// If an incomplete entry is used to expand a sub-member, the incomplete
6216/// entry is marked as IncompleteUsed. The cache keeps count of how many
6217/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6218///
6219/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6220/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6221/// Else the member is part of a recursive type and thus the recursion has
6222/// been exited too soon for the encoding to be correct for the member.
6223///
6224class TypeStringCache {
6225 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6226 struct Entry {
6227 std::string Str; // The encoded TypeString for the type.
6228 enum Status State; // Information about the encoding in 'Str'.
6229 std::string Swapped; // A temporary place holder for a Recursive encoding
6230 // during the expansion of RecordType's members.
6231 };
6232 std::map<const IdentifierInfo *, struct Entry> Map;
6233 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6234 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6235public:
Robert Lyttond263f142014-05-06 09:38:54 +00006236 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006237 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6238 bool removeIncomplete(const IdentifierInfo *ID);
6239 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6240 bool IsRecursive);
6241 StringRef lookupStr(const IdentifierInfo *ID);
6242};
6243
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006244/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006245/// FieldEncoding is a helper for this ordering process.
6246class FieldEncoding {
6247 bool HasName;
6248 std::string Enc;
6249public:
6250 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6251 StringRef str() {return Enc.c_str();};
6252 bool operator<(const FieldEncoding &rhs) const {
6253 if (HasName != rhs.HasName) return HasName;
6254 return Enc < rhs.Enc;
6255 }
6256};
6257
Robert Lytton7d1db152013-08-19 09:46:39 +00006258class XCoreABIInfo : public DefaultABIInfo {
6259public:
6260 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006261 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6262 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006263};
6264
Robert Lyttond21e2d72014-03-03 13:45:29 +00006265class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006266 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006267public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006268 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006269 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006270 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6271 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006272};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006273
Robert Lytton2d196952013-10-11 10:29:34 +00006274} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006275
Robert Lytton7d1db152013-08-19 09:46:39 +00006276llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6277 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006278 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006279
Robert Lytton2d196952013-10-11 10:29:34 +00006280 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006281 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6282 CGF.Int8PtrPtrTy);
6283 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006284
Robert Lytton2d196952013-10-11 10:29:34 +00006285 // Handle the argument.
6286 ABIArgInfo AI = classifyArgumentType(Ty);
6287 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6288 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6289 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006290 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006291 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006292 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006293 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006294 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006295 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006296 llvm_unreachable("Unsupported ABI kind for va_arg");
6297 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006298 Val = llvm::UndefValue::get(ArgPtrTy);
6299 ArgSize = 0;
6300 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006301 case ABIArgInfo::Extend:
6302 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006303 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6304 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6305 if (ArgSize < 4)
6306 ArgSize = 4;
6307 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006308 case ABIArgInfo::Indirect:
6309 llvm::Value *ArgAddr;
6310 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6311 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006312 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6313 ArgSize = 4;
6314 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006315 }
Robert Lytton2d196952013-10-11 10:29:34 +00006316
6317 // Increment the VAList.
6318 if (ArgSize) {
6319 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6320 Builder.CreateStore(APN, VAListAddrAsBPP);
6321 }
6322 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006323}
Robert Lytton0e076492013-08-13 09:43:10 +00006324
Robert Lytton844aeeb2014-05-02 09:33:20 +00006325/// During the expansion of a RecordType, an incomplete TypeString is placed
6326/// into the cache as a means to identify and break recursion.
6327/// If there is a Recursive encoding in the cache, it is swapped out and will
6328/// be reinserted by removeIncomplete().
6329/// All other types of encoding should have been used rather than arriving here.
6330void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6331 std::string StubEnc) {
6332 if (!ID)
6333 return;
6334 Entry &E = Map[ID];
6335 assert( (E.Str.empty() || E.State == Recursive) &&
6336 "Incorrectly use of addIncomplete");
6337 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6338 E.Swapped.swap(E.Str); // swap out the Recursive
6339 E.Str.swap(StubEnc);
6340 E.State = Incomplete;
6341 ++IncompleteCount;
6342}
6343
6344/// Once the RecordType has been expanded, the temporary incomplete TypeString
6345/// must be removed from the cache.
6346/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6347/// Returns true if the RecordType was defined recursively.
6348bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6349 if (!ID)
6350 return false;
6351 auto I = Map.find(ID);
6352 assert(I != Map.end() && "Entry not present");
6353 Entry &E = I->second;
6354 assert( (E.State == Incomplete ||
6355 E.State == IncompleteUsed) &&
6356 "Entry must be an incomplete type");
6357 bool IsRecursive = false;
6358 if (E.State == IncompleteUsed) {
6359 // We made use of our Incomplete encoding, thus we are recursive.
6360 IsRecursive = true;
6361 --IncompleteUsedCount;
6362 }
6363 if (E.Swapped.empty())
6364 Map.erase(I);
6365 else {
6366 // Swap the Recursive back.
6367 E.Swapped.swap(E.Str);
6368 E.Swapped.clear();
6369 E.State = Recursive;
6370 }
6371 --IncompleteCount;
6372 return IsRecursive;
6373}
6374
6375/// Add the encoded TypeString to the cache only if it is NonRecursive or
6376/// Recursive (viz: all sub-members were expanded as fully as possible).
6377void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6378 bool IsRecursive) {
6379 if (!ID || IncompleteUsedCount)
6380 return; // No key or it is is an incomplete sub-type so don't add.
6381 Entry &E = Map[ID];
6382 if (IsRecursive && !E.Str.empty()) {
6383 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6384 "This is not the same Recursive entry");
6385 // The parent container was not recursive after all, so we could have used
6386 // this Recursive sub-member entry after all, but we assumed the worse when
6387 // we started viz: IncompleteCount!=0.
6388 return;
6389 }
6390 assert(E.Str.empty() && "Entry already present");
6391 E.Str = Str.str();
6392 E.State = IsRecursive? Recursive : NonRecursive;
6393}
6394
6395/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6396/// are recursively expanding a type (IncompleteCount != 0) and the cached
6397/// encoding is Recursive, return an empty StringRef.
6398StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6399 if (!ID)
6400 return StringRef(); // We have no key.
6401 auto I = Map.find(ID);
6402 if (I == Map.end())
6403 return StringRef(); // We have no encoding.
6404 Entry &E = I->second;
6405 if (E.State == Recursive && IncompleteCount)
6406 return StringRef(); // We don't use Recursive encodings for member types.
6407
6408 if (E.State == Incomplete) {
6409 // The incomplete type is being used to break out of recursion.
6410 E.State = IncompleteUsed;
6411 ++IncompleteUsedCount;
6412 }
6413 return E.Str.c_str();
6414}
6415
6416/// The XCore ABI includes a type information section that communicates symbol
6417/// type information to the linker. The linker uses this information to verify
6418/// safety/correctness of things such as array bound and pointers et al.
6419/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6420/// This type information (TypeString) is emitted into meta data for all global
6421/// symbols: definitions, declarations, functions & variables.
6422///
6423/// The TypeString carries type, qualifier, name, size & value details.
6424/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6425/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6426/// The output is tested by test/CodeGen/xcore-stringtype.c.
6427///
6428static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6429 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6430
6431/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6432void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6433 CodeGen::CodeGenModule &CGM) const {
6434 SmallStringEnc Enc;
6435 if (getTypeString(Enc, D, CGM, TSC)) {
6436 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6437 llvm::SmallVector<llvm::Value *, 2> MDVals;
6438 MDVals.push_back(GV);
6439 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6440 llvm::NamedMDNode *MD =
6441 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6442 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6443 }
6444}
6445
6446static bool appendType(SmallStringEnc &Enc, QualType QType,
6447 const CodeGen::CodeGenModule &CGM,
6448 TypeStringCache &TSC);
6449
6450/// Helper function for appendRecordType().
6451/// Builds a SmallVector containing the encoded field types in declaration order.
6452static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6453 const RecordDecl *RD,
6454 const CodeGen::CodeGenModule &CGM,
6455 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006456 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006457 SmallStringEnc Enc;
6458 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006459 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006460 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006461 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006462 Enc += "b(";
6463 llvm::raw_svector_ostream OS(Enc);
6464 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006465 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006466 OS.flush();
6467 Enc += ':';
6468 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006469 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006470 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006471 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006472 Enc += ')';
6473 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006474 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006475 }
6476 return true;
6477}
6478
6479/// Appends structure and union types to Enc and adds encoding to cache.
6480/// Recursively calls appendType (via extractFieldType) for each field.
6481/// Union types have their fields ordered according to the ABI.
6482static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6483 const CodeGen::CodeGenModule &CGM,
6484 TypeStringCache &TSC, const IdentifierInfo *ID) {
6485 // Append the cached TypeString if we have one.
6486 StringRef TypeString = TSC.lookupStr(ID);
6487 if (!TypeString.empty()) {
6488 Enc += TypeString;
6489 return true;
6490 }
6491
6492 // Start to emit an incomplete TypeString.
6493 size_t Start = Enc.size();
6494 Enc += (RT->isUnionType()? 'u' : 's');
6495 Enc += '(';
6496 if (ID)
6497 Enc += ID->getName();
6498 Enc += "){";
6499
6500 // We collect all encoded fields and order as necessary.
6501 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006502 const RecordDecl *RD = RT->getDecl()->getDefinition();
6503 if (RD && !RD->field_empty()) {
6504 // An incomplete TypeString stub is placed in the cache for this RecordType
6505 // so that recursive calls to this RecordType will use it whilst building a
6506 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006507 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006508 std::string StubEnc(Enc.substr(Start).str());
6509 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6510 TSC.addIncomplete(ID, std::move(StubEnc));
6511 if (!extractFieldType(FE, RD, CGM, TSC)) {
6512 (void) TSC.removeIncomplete(ID);
6513 return false;
6514 }
6515 IsRecursive = TSC.removeIncomplete(ID);
6516 // The ABI requires unions to be sorted but not structures.
6517 // See FieldEncoding::operator< for sort algorithm.
6518 if (RT->isUnionType())
6519 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006520 // We can now complete the TypeString.
6521 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006522 for (unsigned I = 0; I != E; ++I) {
6523 if (I)
6524 Enc += ',';
6525 Enc += FE[I].str();
6526 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006527 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006528 Enc += '}';
6529 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6530 return true;
6531}
6532
6533/// Appends enum types to Enc and adds the encoding to the cache.
6534static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6535 TypeStringCache &TSC,
6536 const IdentifierInfo *ID) {
6537 // Append the cached TypeString if we have one.
6538 StringRef TypeString = TSC.lookupStr(ID);
6539 if (!TypeString.empty()) {
6540 Enc += TypeString;
6541 return true;
6542 }
6543
6544 size_t Start = Enc.size();
6545 Enc += "e(";
6546 if (ID)
6547 Enc += ID->getName();
6548 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006549
6550 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006551 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006552 SmallVector<FieldEncoding, 16> FE;
6553 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6554 ++I) {
6555 SmallStringEnc EnumEnc;
6556 EnumEnc += "m(";
6557 EnumEnc += I->getName();
6558 EnumEnc += "){";
6559 I->getInitVal().toString(EnumEnc);
6560 EnumEnc += '}';
6561 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6562 }
6563 std::sort(FE.begin(), FE.end());
6564 unsigned E = FE.size();
6565 for (unsigned I = 0; I != E; ++I) {
6566 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006567 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006568 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006569 }
6570 }
6571 Enc += '}';
6572 TSC.addIfComplete(ID, Enc.substr(Start), false);
6573 return true;
6574}
6575
6576/// Appends type's qualifier to Enc.
6577/// This is done prior to appending the type's encoding.
6578static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6579 // Qualifiers are emitted in alphabetical order.
6580 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6581 int Lookup = 0;
6582 if (QT.isConstQualified())
6583 Lookup += 1<<0;
6584 if (QT.isRestrictQualified())
6585 Lookup += 1<<1;
6586 if (QT.isVolatileQualified())
6587 Lookup += 1<<2;
6588 Enc += Table[Lookup];
6589}
6590
6591/// Appends built-in types to Enc.
6592static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6593 const char *EncType;
6594 switch (BT->getKind()) {
6595 case BuiltinType::Void:
6596 EncType = "0";
6597 break;
6598 case BuiltinType::Bool:
6599 EncType = "b";
6600 break;
6601 case BuiltinType::Char_U:
6602 EncType = "uc";
6603 break;
6604 case BuiltinType::UChar:
6605 EncType = "uc";
6606 break;
6607 case BuiltinType::SChar:
6608 EncType = "sc";
6609 break;
6610 case BuiltinType::UShort:
6611 EncType = "us";
6612 break;
6613 case BuiltinType::Short:
6614 EncType = "ss";
6615 break;
6616 case BuiltinType::UInt:
6617 EncType = "ui";
6618 break;
6619 case BuiltinType::Int:
6620 EncType = "si";
6621 break;
6622 case BuiltinType::ULong:
6623 EncType = "ul";
6624 break;
6625 case BuiltinType::Long:
6626 EncType = "sl";
6627 break;
6628 case BuiltinType::ULongLong:
6629 EncType = "ull";
6630 break;
6631 case BuiltinType::LongLong:
6632 EncType = "sll";
6633 break;
6634 case BuiltinType::Float:
6635 EncType = "ft";
6636 break;
6637 case BuiltinType::Double:
6638 EncType = "d";
6639 break;
6640 case BuiltinType::LongDouble:
6641 EncType = "ld";
6642 break;
6643 default:
6644 return false;
6645 }
6646 Enc += EncType;
6647 return true;
6648}
6649
6650/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6651static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6652 const CodeGen::CodeGenModule &CGM,
6653 TypeStringCache &TSC) {
6654 Enc += "p(";
6655 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6656 return false;
6657 Enc += ')';
6658 return true;
6659}
6660
6661/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006662static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6663 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006664 const CodeGen::CodeGenModule &CGM,
6665 TypeStringCache &TSC, StringRef NoSizeEnc) {
6666 if (AT->getSizeModifier() != ArrayType::Normal)
6667 return false;
6668 Enc += "a(";
6669 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6670 CAT->getSize().toStringUnsigned(Enc);
6671 else
6672 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6673 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006674 // The Qualifiers should be attached to the type rather than the array.
6675 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006676 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6677 return false;
6678 Enc += ')';
6679 return true;
6680}
6681
6682/// Appends a function encoding to Enc, calling appendType for the return type
6683/// and the arguments.
6684static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6685 const CodeGen::CodeGenModule &CGM,
6686 TypeStringCache &TSC) {
6687 Enc += "f{";
6688 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6689 return false;
6690 Enc += "}(";
6691 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6692 // N.B. we are only interested in the adjusted param types.
6693 auto I = FPT->param_type_begin();
6694 auto E = FPT->param_type_end();
6695 if (I != E) {
6696 do {
6697 if (!appendType(Enc, *I, CGM, TSC))
6698 return false;
6699 ++I;
6700 if (I != E)
6701 Enc += ',';
6702 } while (I != E);
6703 if (FPT->isVariadic())
6704 Enc += ",va";
6705 } else {
6706 if (FPT->isVariadic())
6707 Enc += "va";
6708 else
6709 Enc += '0';
6710 }
6711 }
6712 Enc += ')';
6713 return true;
6714}
6715
6716/// Handles the type's qualifier before dispatching a call to handle specific
6717/// type encodings.
6718static bool appendType(SmallStringEnc &Enc, QualType QType,
6719 const CodeGen::CodeGenModule &CGM,
6720 TypeStringCache &TSC) {
6721
6722 QualType QT = QType.getCanonicalType();
6723
Robert Lytton6adb20f2014-06-05 09:06:21 +00006724 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6725 // The Qualifiers should be attached to the type rather than the array.
6726 // Thus we don't call appendQualifier() here.
6727 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6728
Robert Lytton844aeeb2014-05-02 09:33:20 +00006729 appendQualifier(Enc, QT);
6730
6731 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6732 return appendBuiltinType(Enc, BT);
6733
Robert Lytton844aeeb2014-05-02 09:33:20 +00006734 if (const PointerType *PT = QT->getAs<PointerType>())
6735 return appendPointerType(Enc, PT, CGM, TSC);
6736
6737 if (const EnumType *ET = QT->getAs<EnumType>())
6738 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6739
6740 if (const RecordType *RT = QT->getAsStructureType())
6741 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6742
6743 if (const RecordType *RT = QT->getAsUnionType())
6744 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6745
6746 if (const FunctionType *FT = QT->getAs<FunctionType>())
6747 return appendFunctionType(Enc, FT, CGM, TSC);
6748
6749 return false;
6750}
6751
6752static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6753 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6754 if (!D)
6755 return false;
6756
6757 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6758 if (FD->getLanguageLinkage() != CLanguageLinkage)
6759 return false;
6760 return appendType(Enc, FD->getType(), CGM, TSC);
6761 }
6762
6763 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6764 if (VD->getLanguageLinkage() != CLanguageLinkage)
6765 return false;
6766 QualType QT = VD->getType().getCanonicalType();
6767 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6768 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006769 // The Qualifiers should be attached to the type rather than the array.
6770 // Thus we don't call appendQualifier() here.
6771 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00006772 }
6773 return appendType(Enc, QT, CGM, TSC);
6774 }
6775 return false;
6776}
6777
6778
Robert Lytton0e076492013-08-13 09:43:10 +00006779//===----------------------------------------------------------------------===//
6780// Driver code
6781//===----------------------------------------------------------------------===//
6782
Chris Lattner2b037972010-07-29 02:01:43 +00006783const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006784 if (TheTargetCodeGenInfo)
6785 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006786
John McCallc8e01702013-04-16 22:48:15 +00006787 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00006788 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00006789 default:
Chris Lattner2b037972010-07-29 02:01:43 +00006790 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00006791
Derek Schuff09338a22012-09-06 17:37:28 +00006792 case llvm::Triple::le32:
6793 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00006794 case llvm::Triple::mips:
6795 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006796 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
6797
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00006798 case llvm::Triple::mips64:
6799 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006800 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
6801
Tim Northover25e8a672014-05-24 12:51:25 +00006802 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00006803 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00006804 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006805 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00006806 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00006807
Tim Northover573cbee2014-05-24 12:52:07 +00006808 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00006809 }
6810
Daniel Dunbard59655c2009-09-12 00:59:49 +00006811 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006812 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00006813 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006814 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006815 {
6816 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006817 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006818 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00006819 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00006820 (CodeGenOpts.FloatABI != "soft" &&
6821 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006822 Kind = ARMABIInfo::AAPCS_VFP;
6823
Derek Schuffa2020962012-10-16 22:30:41 +00006824 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00006825 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00006826 return *(TheTargetCodeGenInfo =
6827 new NaClARMTargetCodeGenInfo(Types, Kind));
6828 default:
6829 return *(TheTargetCodeGenInfo =
6830 new ARMTargetCodeGenInfo(Types, Kind));
6831 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006832 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00006833
John McCallea8d8bb2010-03-11 00:10:12 +00006834 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00006835 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00006836 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00006837 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00006838 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00006839 if (getTarget().getABI() == "elfv2")
6840 Kind = PPC64_SVR4_ABIInfo::ELFv2;
6841
Ulrich Weigandb7122372014-07-21 00:48:09 +00006842 return *(TheTargetCodeGenInfo =
6843 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6844 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00006845 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00006846 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00006847 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00006848 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00006849 if (getTarget().getABI() == "elfv1")
6850 Kind = PPC64_SVR4_ABIInfo::ELFv1;
6851
Ulrich Weigandb7122372014-07-21 00:48:09 +00006852 return *(TheTargetCodeGenInfo =
6853 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6854 }
John McCallea8d8bb2010-03-11 00:10:12 +00006855
Peter Collingbournec947aae2012-05-20 23:28:41 +00006856 case llvm::Triple::nvptx:
6857 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00006858 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006859
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006860 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00006861 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00006862
Ulrich Weigand47445072013-05-06 16:26:41 +00006863 case llvm::Triple::systemz:
6864 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
6865
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006866 case llvm::Triple::tce:
6867 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
6868
Eli Friedman33465822011-07-08 23:31:17 +00006869 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00006870 bool IsDarwinVectorABI = Triple.isOSDarwin();
6871 bool IsSmallStructInRegABI =
6872 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00006873 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00006874
John McCall1fe2a8c2013-06-18 02:46:29 +00006875 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00006876 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00006877 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00006878 IsDarwinVectorABI, IsSmallStructInRegABI,
6879 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00006880 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00006881 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006882 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00006883 new X86_32TargetCodeGenInfo(Types,
6884 IsDarwinVectorABI, IsSmallStructInRegABI,
6885 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00006886 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006887 }
Eli Friedman33465822011-07-08 23:31:17 +00006888 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006889
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006890 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00006891 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006892
Chris Lattner04dc9572010-08-31 16:44:54 +00006893 switch (Triple.getOS()) {
6894 case llvm::Triple::Win32:
Chris Lattner04dc9572010-08-31 16:44:54 +00006895 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00006896 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00006897 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
6898 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00006899 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006900 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
6901 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00006902 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00006903 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00006904 case llvm::Triple::hexagon:
6905 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006906 case llvm::Triple::sparcv9:
6907 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00006908 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006909 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006910 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006911}