blob: b9a7d315891ab4bfdd03b3944d4eb52aad60dda5 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000022#include "clang/CodeGen/SwiftCallingConv.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000023#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000024#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000025#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000028#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000029#include <algorithm> // std::sort
30
Anton Korobeynikov244360d2009-06-05 22:08:42 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall943fae92010-05-27 06:19:26 +000034static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
35 llvm::Value *Array,
36 llvm::Value *Value,
37 unsigned FirstIndex,
38 unsigned LastIndex) {
39 // Alternatively, we could emit this as a loop in the source.
40 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000041 llvm::Value *Cell =
42 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000043 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000044 }
45}
46
John McCalla1dee5302010-08-22 10:59:02 +000047static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000048 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000049 T->isMemberFunctionPointerType();
50}
51
John McCall7f416cc2015-09-08 08:05:57 +000052ABIArgInfo
53ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
54 llvm::Type *Padding) const {
55 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
56 ByRef, Realign, Padding);
57}
58
59ABIArgInfo
60ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
61 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
62 /*ByRef*/ false, Realign);
63}
64
Charles Davisc7d5c942015-09-17 20:55:33 +000065Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
66 QualType Ty) const {
67 return Address::invalid();
68}
69
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000070ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000071
John McCall12f23522016-04-04 18:33:08 +000072/// Does the given lowering require more than the given number of
73/// registers when expanded?
74///
75/// This is intended to be the basis of a reasonable basic implementation
76/// of should{Pass,Return}IndirectlyForSwift.
77///
78/// For most targets, a limit of four total registers is reasonable; this
79/// limits the amount of code required in order to move around the value
80/// in case it wasn't produced immediately prior to the call by the caller
81/// (or wasn't produced in exactly the right registers) or isn't used
82/// immediately within the callee. But some targets may need to further
83/// limit the register count due to an inability to support that many
84/// return registers.
85static bool occupiesMoreThan(CodeGenTypes &cgt,
86 ArrayRef<llvm::Type*> scalarTypes,
87 unsigned maxAllRegisters) {
88 unsigned intCount = 0, fpCount = 0;
89 for (llvm::Type *type : scalarTypes) {
90 if (type->isPointerTy()) {
91 intCount++;
92 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
93 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
94 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
95 } else {
96 assert(type->isVectorTy() || type->isFloatingPointTy());
97 fpCount++;
98 }
99 }
100
101 return (intCount + fpCount > maxAllRegisters);
102}
103
104bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
105 llvm::Type *eltTy,
106 unsigned numElts) const {
107 // The default implementation of this assumes that the target guarantees
108 // 128-bit SIMD support but nothing more.
109 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
110}
111
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000112static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000113 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000114 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
115 if (!RD)
116 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000117 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000118}
119
120static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000121 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000122 const RecordType *RT = T->getAs<RecordType>();
123 if (!RT)
124 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000125 return getRecordArgABI(RT, CXXABI);
126}
127
Reid Klecknerb1be6832014-11-15 01:41:41 +0000128/// Pass transparent unions as if they were the type of the first element. Sema
129/// should ensure that all elements of the union have the same "machine type".
130static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
131 if (const RecordType *UT = Ty->getAsUnionType()) {
132 const RecordDecl *UD = UT->getDecl();
133 if (UD->hasAttr<TransparentUnionAttr>()) {
134 assert(!UD->field_empty() && "sema created an empty transparent union");
135 return UD->field_begin()->getType();
136 }
137 }
138 return Ty;
139}
140
Mark Lacey3825e832013-10-06 01:33:34 +0000141CGCXXABI &ABIInfo::getCXXABI() const {
142 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000143}
144
Chris Lattner2b037972010-07-29 02:01:43 +0000145ASTContext &ABIInfo::getContext() const {
146 return CGT.getContext();
147}
148
149llvm::LLVMContext &ABIInfo::getVMContext() const {
150 return CGT.getLLVMContext();
151}
152
Micah Villmowdd31ca12012-10-08 16:25:52 +0000153const llvm::DataLayout &ABIInfo::getDataLayout() const {
154 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000155}
156
John McCallc8e01702013-04-16 22:48:15 +0000157const TargetInfo &ABIInfo::getTarget() const {
158 return CGT.getTarget();
159}
Chris Lattner2b037972010-07-29 02:01:43 +0000160
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000161bool ABIInfo:: isAndroid() const { return getTarget().getTriple().isAndroid(); }
162
Reid Klecknere9f6a712014-10-31 17:10:41 +0000163bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
164 return false;
165}
166
167bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
168 uint64_t Members) const {
169 return false;
170}
171
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000172bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
173 return false;
174}
175
Yaron Kerencdae9412016-01-29 19:38:18 +0000176LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000177 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000178 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000179 switch (TheKind) {
180 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000181 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000182 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000183 Ty->print(OS);
184 else
185 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000186 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000187 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000188 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000189 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000190 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000191 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000192 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000193 case InAlloca:
194 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
195 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000196 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000197 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000198 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000199 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000200 break;
201 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000202 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000203 break;
John McCallf26e73d2016-03-11 04:30:43 +0000204 case CoerceAndExpand:
205 OS << "CoerceAndExpand Type=";
206 getCoerceAndExpandType()->print(OS);
207 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000208 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000209 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000210}
211
Petar Jovanovic402257b2015-12-04 00:26:47 +0000212// Dynamically round a pointer up to a multiple of the given alignment.
213static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
214 llvm::Value *Ptr,
215 CharUnits Align) {
216 llvm::Value *PtrAsInt = Ptr;
217 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
218 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
219 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
220 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
221 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
222 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
223 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
224 Ptr->getType(),
225 Ptr->getName() + ".aligned");
226 return PtrAsInt;
227}
228
John McCall7f416cc2015-09-08 08:05:57 +0000229/// Emit va_arg for a platform using the common void* representation,
230/// where arguments are simply emitted in an array of slots on the stack.
231///
232/// This version implements the core direct-value passing rules.
233///
234/// \param SlotSize - The size and alignment of a stack slot.
235/// Each argument will be allocated to a multiple of this number of
236/// slots, and all the slots will be aligned to this value.
237/// \param AllowHigherAlign - The slot alignment is not a cap;
238/// an argument type with an alignment greater than the slot size
239/// will be emitted on a higher-alignment address, potentially
240/// leaving one or more empty slots behind as padding. If this
241/// is false, the returned address might be less-aligned than
242/// DirectAlign.
243static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
244 Address VAListAddr,
245 llvm::Type *DirectTy,
246 CharUnits DirectSize,
247 CharUnits DirectAlign,
248 CharUnits SlotSize,
249 bool AllowHigherAlign) {
250 // Cast the element type to i8* if necessary. Some platforms define
251 // va_list as a struct containing an i8* instead of just an i8*.
252 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
253 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
254
255 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
256
257 // If the CC aligns values higher than the slot size, do so if needed.
258 Address Addr = Address::invalid();
259 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000260 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
261 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000262 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000263 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000264 }
265
266 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000267 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000268 llvm::Value *NextPtr =
269 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
270 "argp.next");
271 CGF.Builder.CreateStore(NextPtr, VAListAddr);
272
273 // If the argument is smaller than a slot, and this is a big-endian
274 // target, the argument will be right-adjusted in its slot.
275 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian()) {
276 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
277 }
278
279 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
280 return Addr;
281}
282
283/// Emit va_arg for a platform using the common void* representation,
284/// where arguments are simply emitted in an array of slots on the stack.
285///
286/// \param IsIndirect - Values of this type are passed indirectly.
287/// \param ValueInfo - The size and alignment of this type, generally
288/// computed with getContext().getTypeInfoInChars(ValueTy).
289/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
290/// Each argument will be allocated to a multiple of this number of
291/// slots, and all the slots will be aligned to this value.
292/// \param AllowHigherAlign - The slot alignment is not a cap;
293/// an argument type with an alignment greater than the slot size
294/// will be emitted on a higher-alignment address, potentially
295/// leaving one or more empty slots behind as padding.
296static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
297 QualType ValueTy, bool IsIndirect,
298 std::pair<CharUnits, CharUnits> ValueInfo,
299 CharUnits SlotSizeAndAlign,
300 bool AllowHigherAlign) {
301 // The size and alignment of the value that was passed directly.
302 CharUnits DirectSize, DirectAlign;
303 if (IsIndirect) {
304 DirectSize = CGF.getPointerSize();
305 DirectAlign = CGF.getPointerAlign();
306 } else {
307 DirectSize = ValueInfo.first;
308 DirectAlign = ValueInfo.second;
309 }
310
311 // Cast the address we've calculated to the right type.
312 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
313 if (IsIndirect)
314 DirectTy = DirectTy->getPointerTo(0);
315
316 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
317 DirectSize, DirectAlign,
318 SlotSizeAndAlign,
319 AllowHigherAlign);
320
321 if (IsIndirect) {
322 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
323 }
324
325 return Addr;
326
327}
328
329static Address emitMergePHI(CodeGenFunction &CGF,
330 Address Addr1, llvm::BasicBlock *Block1,
331 Address Addr2, llvm::BasicBlock *Block2,
332 const llvm::Twine &Name = "") {
333 assert(Addr1.getType() == Addr2.getType());
334 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
335 PHI->addIncoming(Addr1.getPointer(), Block1);
336 PHI->addIncoming(Addr2.getPointer(), Block2);
337 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
338 return Address(PHI, Align);
339}
340
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000341TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
342
John McCall3480ef22011-08-30 01:42:09 +0000343// If someone can figure out a general rule for this, that would be great.
344// It's probably just doomed to be platform-dependent, though.
345unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
346 // Verified for:
347 // x86-64 FreeBSD, Linux, Darwin
348 // x86-32 FreeBSD, Linux, Darwin
349 // PowerPC Linux, Darwin
350 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000351 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000352 return 32;
353}
354
John McCalla729c622012-02-17 03:33:10 +0000355bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
356 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000357 // The following conventions are known to require this to be false:
358 // x86_stdcall
359 // MIPS
360 // For everything else, we just prefer false unless we opt out.
361 return false;
362}
363
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000364void
365TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
366 llvm::SmallString<24> &Opt) const {
367 // This assumes the user is passing a library name like "rt" instead of a
368 // filename like "librt.a/so", and that they don't care whether it's static or
369 // dynamic.
370 Opt = "-l";
371 Opt += Lib;
372}
373
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000374static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000375
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000376/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000377/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000378static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
379 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000380 if (FD->isUnnamedBitfield())
381 return true;
382
383 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000384
Eli Friedman0b3f2012011-11-18 03:47:20 +0000385 // Constant arrays of empty records count as empty, strip them off.
386 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000387 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000388 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
389 if (AT->getSize() == 0)
390 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000391 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000392 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000393
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000394 const RecordType *RT = FT->getAs<RecordType>();
395 if (!RT)
396 return false;
397
398 // C++ record fields are never empty, at least in the Itanium ABI.
399 //
400 // FIXME: We should use a predicate for whether this behavior is true in the
401 // current ABI.
402 if (isa<CXXRecordDecl>(RT->getDecl()))
403 return false;
404
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000405 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000406}
407
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000408/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000409/// fields. Note that a structure with a flexible array member is not
410/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000411static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000412 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000413 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000414 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000415 const RecordDecl *RD = RT->getDecl();
416 if (RD->hasFlexibleArrayMember())
417 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000418
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000419 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000420 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000421 for (const auto &I : CXXRD->bases())
422 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000423 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000424
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000425 for (const auto *I : RD->fields())
426 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000427 return false;
428 return true;
429}
430
431/// isSingleElementStruct - Determine if a structure is a "single
432/// element struct", i.e. it has exactly one non-empty field or
433/// exactly one field which is itself a single element
434/// struct. Structures with flexible array members are never
435/// considered single element structs.
436///
437/// \return The field declaration for the single non-empty field, if
438/// it exists.
439static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000440 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000441 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000442 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000443
444 const RecordDecl *RD = RT->getDecl();
445 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000446 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000447
Craig Topper8a13c412014-05-21 05:09:00 +0000448 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000449
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000450 // If this is a C++ record, check the bases first.
451 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000452 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000453 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000454 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000455 continue;
456
457 // If we already found an element then this isn't a single-element struct.
458 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000459 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000460
461 // If this is non-empty and not a single element struct, the composite
462 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000463 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000464 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000465 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000466 }
467 }
468
469 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000470 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000471 QualType FT = FD->getType();
472
473 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000474 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000475 continue;
476
477 // If we already found an element then this isn't a single-element
478 // struct.
479 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000480 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000481
482 // Treat single element arrays as the element.
483 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
484 if (AT->getSize().getZExtValue() != 1)
485 break;
486 FT = AT->getElementType();
487 }
488
John McCalla1dee5302010-08-22 10:59:02 +0000489 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000490 Found = FT.getTypePtr();
491 } else {
492 Found = isSingleElementStruct(FT, Context);
493 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000494 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000495 }
496 }
497
Eli Friedmanee945342011-11-18 01:25:50 +0000498 // We don't consider a struct a single-element struct if it has
499 // padding beyond the element type.
500 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000501 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000502
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000503 return Found;
504}
505
506static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000507 // Treat complex types as the element type.
508 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
509 Ty = CTy->getElementType();
510
511 // Check for a type which we know has a simple scalar argument-passing
512 // convention without any padding. (We're specifically looking for 32
513 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000514 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000515 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000516 return false;
517
518 uint64_t Size = Context.getTypeSize(Ty);
519 return Size == 32 || Size == 64;
520}
521
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000522/// canExpandIndirectArgument - Test whether an argument type which is to be
523/// passed indirectly (on the stack) would have the equivalent layout if it was
524/// expanded into separate arguments. If so, we prefer to do the latter to avoid
525/// inhibiting optimizations.
526///
527// FIXME: This predicate is missing many cases, currently it just follows
528// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
529// should probably make this smarter, or better yet make the LLVM backend
530// capable of handling it.
531static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
532 // We can only expand structure types.
533 const RecordType *RT = Ty->getAs<RecordType>();
534 if (!RT)
535 return false;
536
537 // We can only expand (C) structures.
538 //
539 // FIXME: This needs to be generalized to handle classes as well.
540 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000541 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000542 return false;
543
Manman Ren27382782015-04-03 18:10:29 +0000544 // We try to expand CLike CXXRecordDecl.
545 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
546 if (!CXXRD->isCLike())
547 return false;
548 }
549
Eli Friedmane5c85622011-11-18 01:32:26 +0000550 uint64_t Size = 0;
551
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000552 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000553 if (!is32Or64BitBasicType(FD->getType(), Context))
554 return false;
555
556 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
557 // how to expand them yet, and the predicate for telling if a bitfield still
558 // counts as "basic" is more complicated than what we were doing previously.
559 if (FD->isBitField())
560 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000561
562 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000563 }
564
Eli Friedmane5c85622011-11-18 01:32:26 +0000565 // Make sure there are not any holes in the struct.
566 if (Size != Context.getTypeSize(Ty))
567 return false;
568
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000569 return true;
570}
571
572namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000573Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
574 const ABIArgInfo &AI) {
575 // This default implementation defers to the llvm backend's va_arg
576 // instruction. It can handle only passing arguments directly
577 // (typically only handled in the backend for primitive types), or
578 // aggregates passed indirectly by pointer (NOTE: if the "byval"
579 // flag has ABI impact in the callee, this implementation cannot
580 // work.)
581
582 // Only a few cases are covered here at the moment -- those needed
583 // by the default abi.
584 llvm::Value *Val;
585
586 if (AI.isIndirect()) {
587 assert(!AI.getPaddingType() &&
588 "Unepxected PaddingType seen in arginfo in generic VAArg emitter!");
589 assert(
590 !AI.getIndirectRealign() &&
591 "Unepxected IndirectRealign seen in arginfo in generic VAArg emitter!");
592
593 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
594 CharUnits TyAlignForABI = TyInfo.second;
595
596 llvm::Type *BaseTy =
597 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
598 llvm::Value *Addr =
599 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
600 return Address(Addr, TyAlignForABI);
601 } else {
602 assert((AI.isDirect() || AI.isExtend()) &&
603 "Unexpected ArgInfo Kind in generic VAArg emitter!");
604
605 assert(!AI.getInReg() &&
606 "Unepxected InReg seen in arginfo in generic VAArg emitter!");
607 assert(!AI.getPaddingType() &&
608 "Unepxected PaddingType seen in arginfo in generic VAArg emitter!");
609 assert(!AI.getDirectOffset() &&
610 "Unepxected DirectOffset seen in arginfo in generic VAArg emitter!");
611 assert(!AI.getCoerceToType() &&
612 "Unepxected CoerceToType seen in arginfo in generic VAArg emitter!");
613
614 Address Temp = CGF.CreateMemTemp(Ty, "varet");
615 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
616 CGF.Builder.CreateStore(Val, Temp);
617 return Temp;
618 }
619}
620
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000621/// DefaultABIInfo - The default implementation for ABI specific
622/// details. This implementation provides information which results in
623/// self-consistent and sensible LLVM IR generation, but does not
624/// conform to any particular ABI.
625class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000626public:
627 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000628
Chris Lattner458b2aa2010-07-29 02:16:43 +0000629 ABIArgInfo classifyReturnType(QualType RetTy) const;
630 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000631
Craig Topper4f12f102014-03-12 06:41:41 +0000632 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000633 if (!getCXXABI().classifyReturnType(FI))
634 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000635 for (auto &I : FI.arguments())
636 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000637 }
638
John McCall7f416cc2015-09-08 08:05:57 +0000639 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000640 QualType Ty) const override {
641 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
642 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000643};
644
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000645class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
646public:
Chris Lattner2b037972010-07-29 02:01:43 +0000647 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
648 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000649};
650
Chris Lattner458b2aa2010-07-29 02:16:43 +0000651ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000652 Ty = useFirstFieldIfTransparentUnion(Ty);
653
654 if (isAggregateTypeForABI(Ty)) {
655 // Records with non-trivial destructors/copy-constructors should not be
656 // passed by value.
657 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000658 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000659
John McCall7f416cc2015-09-08 08:05:57 +0000660 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000661 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000662
Chris Lattner9723d6c2010-03-11 18:19:55 +0000663 // Treat an enum type as its underlying type.
664 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
665 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000666
Chris Lattner9723d6c2010-03-11 18:19:55 +0000667 return (Ty->isPromotableIntegerType() ?
668 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000669}
670
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000671ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
672 if (RetTy->isVoidType())
673 return ABIArgInfo::getIgnore();
674
675 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000676 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000677
678 // Treat an enum type as its underlying type.
679 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
680 RetTy = EnumTy->getDecl()->getIntegerType();
681
682 return (RetTy->isPromotableIntegerType() ?
683 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
684}
685
Derek Schuff09338a22012-09-06 17:37:28 +0000686//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000687// WebAssembly ABI Implementation
688//
689// This is a very simple ABI that relies a lot on DefaultABIInfo.
690//===----------------------------------------------------------------------===//
691
692class WebAssemblyABIInfo final : public DefaultABIInfo {
693public:
694 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
695 : DefaultABIInfo(CGT) {}
696
697private:
698 ABIArgInfo classifyReturnType(QualType RetTy) const;
699 ABIArgInfo classifyArgumentType(QualType Ty) const;
700
701 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
James Y Knight29b5f082016-02-24 02:59:33 +0000702 // non-virtual, but computeInfo and EmitVAArg is virtual, so we
703 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000704 void computeInfo(CGFunctionInfo &FI) const override {
705 if (!getCXXABI().classifyReturnType(FI))
706 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
707 for (auto &Arg : FI.arguments())
708 Arg.info = classifyArgumentType(Arg.type);
709 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000710
711 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
712 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000713};
714
715class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
716public:
717 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
718 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
719};
720
721/// \brief Classify argument of given type \p Ty.
722ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
723 Ty = useFirstFieldIfTransparentUnion(Ty);
724
725 if (isAggregateTypeForABI(Ty)) {
726 // Records with non-trivial destructors/copy-constructors should not be
727 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000728 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000729 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000730 // Ignore empty structs/unions.
731 if (isEmptyRecord(getContext(), Ty, true))
732 return ABIArgInfo::getIgnore();
733 // Lower single-element structs to just pass a regular value. TODO: We
734 // could do reasonable-size multiple-element structs too, using getExpand(),
735 // though watch out for things like bitfields.
736 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
737 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000738 }
739
740 // Otherwise just do the default thing.
741 return DefaultABIInfo::classifyArgumentType(Ty);
742}
743
744ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
745 if (isAggregateTypeForABI(RetTy)) {
746 // Records with non-trivial destructors/copy-constructors should not be
747 // returned by value.
748 if (!getRecordArgABI(RetTy, getCXXABI())) {
749 // Ignore empty structs/unions.
750 if (isEmptyRecord(getContext(), RetTy, true))
751 return ABIArgInfo::getIgnore();
752 // Lower single-element structs to just return a regular value. TODO: We
753 // could do reasonable-size multiple-element structs too, using
754 // ABIArgInfo::getDirect().
755 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
756 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
757 }
758 }
759
760 // Otherwise just do the default thing.
761 return DefaultABIInfo::classifyReturnType(RetTy);
762}
763
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000764Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
765 QualType Ty) const {
766 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
767 getContext().getTypeInfoInChars(Ty),
768 CharUnits::fromQuantity(4),
769 /*AllowHigherAlign=*/ true);
770}
771
Dan Gohmanc2853072015-09-03 22:51:53 +0000772//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000773// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000774//
775// This is a simplified version of the x86_32 ABI. Arguments and return values
776// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000777//===----------------------------------------------------------------------===//
778
779class PNaClABIInfo : public ABIInfo {
780 public:
781 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
782
783 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000784 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000785
Craig Topper4f12f102014-03-12 06:41:41 +0000786 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000787 Address EmitVAArg(CodeGenFunction &CGF,
788 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000789};
790
791class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
792 public:
793 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
794 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
795};
796
797void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000798 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000799 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
800
Reid Kleckner40ca9132014-05-13 22:05:45 +0000801 for (auto &I : FI.arguments())
802 I.info = classifyArgumentType(I.type);
803}
Derek Schuff09338a22012-09-06 17:37:28 +0000804
John McCall7f416cc2015-09-08 08:05:57 +0000805Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
806 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000807 // The PNaCL ABI is a bit odd, in that varargs don't use normal
808 // function classification. Structs get passed directly for varargs
809 // functions, through a rewriting transform in
810 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
811 // this target to actually support a va_arg instructions with an
812 // aggregate type, unlike other targets.
813 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000814}
815
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000816/// \brief Classify argument of given type \p Ty.
817ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000818 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000819 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000820 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
821 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000822 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
823 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000824 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000825 } else if (Ty->isFloatingType()) {
826 // Floating-point types don't go inreg.
827 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000828 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000829
830 return (Ty->isPromotableIntegerType() ?
831 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000832}
833
834ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
835 if (RetTy->isVoidType())
836 return ABIArgInfo::getIgnore();
837
Eli Benderskye20dad62013-04-04 22:49:35 +0000838 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000839 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000840 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000841
842 // Treat an enum type as its underlying type.
843 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
844 RetTy = EnumTy->getDecl()->getIntegerType();
845
846 return (RetTy->isPromotableIntegerType() ?
847 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
848}
849
Chad Rosier651c1832013-03-25 21:00:27 +0000850/// IsX86_MMXType - Return true if this is an MMX type.
851bool IsX86_MMXType(llvm::Type *IRType) {
852 // 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 +0000853 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
854 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
855 IRType->getScalarSizeInBits() != 64;
856}
857
Jay Foad7c57be32011-07-11 09:56:20 +0000858static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000859 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000860 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000861 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
862 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
863 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000864 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000865 }
866
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000867 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000868 }
869
870 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000871 return Ty;
872}
873
Reid Kleckner80944df2014-10-31 22:00:51 +0000874/// Returns true if this type can be passed in SSE registers with the
875/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
876static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
877 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
878 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
879 return true;
880 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
881 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
882 // registers specially.
883 unsigned VecSize = Context.getTypeSize(VT);
884 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
885 return true;
886 }
887 return false;
888}
889
890/// Returns true if this aggregate is small enough to be passed in SSE registers
891/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
892static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
893 return NumMembers <= 4;
894}
895
Chris Lattner0cf24192010-06-28 20:05:43 +0000896//===----------------------------------------------------------------------===//
897// X86-32 ABI Implementation
898//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000899
Reid Kleckner661f35b2014-01-18 01:12:41 +0000900/// \brief Similar to llvm::CCState, but for Clang.
901struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000902 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000903
904 unsigned CC;
905 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000906 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000907};
908
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000909/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000910class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000911 enum Class {
912 Integer,
913 Float
914 };
915
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000916 static const unsigned MinABIStackAlignInBytes = 4;
917
David Chisnallde3a0692009-08-17 23:08:21 +0000918 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000919 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000920 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000921 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000922 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000923 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000924
925 static bool isRegisterSize(unsigned Size) {
926 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
927 }
928
Reid Kleckner80944df2014-10-31 22:00:51 +0000929 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
930 // FIXME: Assumes vectorcall is in use.
931 return isX86VectorTypeForVectorCall(getContext(), Ty);
932 }
933
934 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
935 uint64_t NumMembers) const override {
936 // FIXME: Assumes vectorcall is in use.
937 return isX86VectorCallAggregateSmallEnough(NumMembers);
938 }
939
Reid Kleckner40ca9132014-05-13 22:05:45 +0000940 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000941
Daniel Dunbar557893d2010-04-21 19:10:51 +0000942 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
943 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000944 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
945
John McCall7f416cc2015-09-08 08:05:57 +0000946 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000947
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000948 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000949 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000950
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000951 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000952 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000953 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000954 /// \brief Updates the number of available free registers, returns
955 /// true if any registers were allocated.
956 bool updateFreeRegs(QualType Ty, CCState &State) const;
957
958 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
959 bool &NeedsPadding) const;
960 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000961
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000962 /// \brief Rewrite the function info so that all memory arguments use
963 /// inalloca.
964 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
965
966 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000967 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000968 QualType Type) const;
969
Rafael Espindola75419dc2012-07-23 23:30:29 +0000970public:
971
Craig Topper4f12f102014-03-12 06:41:41 +0000972 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000973 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
974 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000975
Michael Kupersteindc745202015-10-19 07:52:25 +0000976 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
977 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000978 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000979 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000980 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
981 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000982 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000983 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000984 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000985
986 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
987 ArrayRef<llvm::Type*> scalars,
988 bool asReturnValue) const override {
989 // LLVM's x86-32 lowering currently only assigns up to three
990 // integer registers and three fp registers. Oddly, it'll use up to
991 // four vector registers for vectors, but those can overlap with the
992 // scalar registers.
993 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
994 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000995};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000996
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000997class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
998public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000999 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1000 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001001 unsigned NumRegisterParameters, bool SoftFloatABI)
1002 : TargetCodeGenInfo(new X86_32ABIInfo(
1003 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1004 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001005
John McCall1fe2a8c2013-06-18 02:46:29 +00001006 static bool isStructReturnInRegABI(
1007 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1008
Eric Christopher162c91c2015-06-05 22:03:00 +00001009 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00001010 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001011
Craig Topper4f12f102014-03-12 06:41:41 +00001012 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001013 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001014 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001015 return 4;
1016 }
1017
1018 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001019 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001020
Jay Foad7c57be32011-07-11 09:56:20 +00001021 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001022 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001023 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001024 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1025 }
1026
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001027 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1028 std::string &Constraints,
1029 std::vector<llvm::Type *> &ResultRegTypes,
1030 std::vector<llvm::Type *> &ResultTruncRegTypes,
1031 std::vector<LValue> &ResultRegDests,
1032 std::string &AsmString,
1033 unsigned NumOutputs) const override;
1034
Craig Topper4f12f102014-03-12 06:41:41 +00001035 llvm::Constant *
1036 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001037 unsigned Sig = (0xeb << 0) | // jmp rel8
1038 (0x06 << 8) | // .+0x08
1039 ('F' << 16) |
1040 ('T' << 24);
1041 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1042 }
John McCall01391782016-02-05 21:37:38 +00001043
1044 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1045 return "movl\t%ebp, %ebp"
1046 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1047 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001048};
1049
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001050}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001051
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001052/// Rewrite input constraint references after adding some output constraints.
1053/// In the case where there is one output and one input and we add one output,
1054/// we need to replace all operand references greater than or equal to 1:
1055/// mov $0, $1
1056/// mov eax, $1
1057/// The result will be:
1058/// mov $0, $2
1059/// mov eax, $2
1060static void rewriteInputConstraintReferences(unsigned FirstIn,
1061 unsigned NumNewOuts,
1062 std::string &AsmString) {
1063 std::string Buf;
1064 llvm::raw_string_ostream OS(Buf);
1065 size_t Pos = 0;
1066 while (Pos < AsmString.size()) {
1067 size_t DollarStart = AsmString.find('$', Pos);
1068 if (DollarStart == std::string::npos)
1069 DollarStart = AsmString.size();
1070 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1071 if (DollarEnd == std::string::npos)
1072 DollarEnd = AsmString.size();
1073 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1074 Pos = DollarEnd;
1075 size_t NumDollars = DollarEnd - DollarStart;
1076 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1077 // We have an operand reference.
1078 size_t DigitStart = Pos;
1079 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1080 if (DigitEnd == std::string::npos)
1081 DigitEnd = AsmString.size();
1082 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1083 unsigned OperandIndex;
1084 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1085 if (OperandIndex >= FirstIn)
1086 OperandIndex += NumNewOuts;
1087 OS << OperandIndex;
1088 } else {
1089 OS << OperandStr;
1090 }
1091 Pos = DigitEnd;
1092 }
1093 }
1094 AsmString = std::move(OS.str());
1095}
1096
1097/// Add output constraints for EAX:EDX because they are return registers.
1098void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1099 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1100 std::vector<llvm::Type *> &ResultRegTypes,
1101 std::vector<llvm::Type *> &ResultTruncRegTypes,
1102 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1103 unsigned NumOutputs) const {
1104 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1105
1106 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1107 // larger.
1108 if (!Constraints.empty())
1109 Constraints += ',';
1110 if (RetWidth <= 32) {
1111 Constraints += "={eax}";
1112 ResultRegTypes.push_back(CGF.Int32Ty);
1113 } else {
1114 // Use the 'A' constraint for EAX:EDX.
1115 Constraints += "=A";
1116 ResultRegTypes.push_back(CGF.Int64Ty);
1117 }
1118
1119 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1120 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1121 ResultTruncRegTypes.push_back(CoerceTy);
1122
1123 // Coerce the integer by bitcasting the return slot pointer.
1124 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1125 CoerceTy->getPointerTo()));
1126 ResultRegDests.push_back(ReturnSlot);
1127
1128 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1129}
1130
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001131/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001132/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001133bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1134 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001135 uint64_t Size = Context.getTypeSize(Ty);
1136
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001137 // For i386, type must be register sized.
1138 // For the MCU ABI, it only needs to be <= 8-byte
1139 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1140 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001141
1142 if (Ty->isVectorType()) {
1143 // 64- and 128- bit vectors inside structures are not returned in
1144 // registers.
1145 if (Size == 64 || Size == 128)
1146 return false;
1147
1148 return true;
1149 }
1150
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001151 // If this is a builtin, pointer, enum, complex type, member pointer, or
1152 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001153 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001154 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001155 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001156 return true;
1157
1158 // Arrays are treated like records.
1159 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001160 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001161
1162 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001163 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001164 if (!RT) return false;
1165
Anders Carlsson40446e82010-01-27 03:25:19 +00001166 // FIXME: Traverse bases here too.
1167
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001168 // Structure types are passed in register if all fields would be
1169 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001170 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001171 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001172 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001173 continue;
1174
1175 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001176 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001177 return false;
1178 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001179 return true;
1180}
1181
John McCall7f416cc2015-09-08 08:05:57 +00001182ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001183 // If the return value is indirect, then the hidden argument is consuming one
1184 // integer register.
1185 if (State.FreeRegs) {
1186 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001187 if (!IsMCUABI)
1188 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001189 }
John McCall7f416cc2015-09-08 08:05:57 +00001190 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001191}
1192
Eric Christopher7565e0d2015-05-29 23:09:49 +00001193ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1194 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001195 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001196 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001197
Reid Kleckner80944df2014-10-31 22:00:51 +00001198 const Type *Base = nullptr;
1199 uint64_t NumElts = 0;
1200 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1201 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1202 // The LLVM struct type for such an aggregate should lower properly.
1203 return ABIArgInfo::getDirect();
1204 }
1205
Chris Lattner458b2aa2010-07-29 02:16:43 +00001206 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001207 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001208 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001209 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001210
1211 // 128-bit vectors are a special case; they are returned in
1212 // registers and we need to make sure to pick a type the LLVM
1213 // backend will like.
1214 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001215 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001216 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001217
1218 // Always return in register if it fits in a general purpose
1219 // register, or if it is 64 bits and has a single element.
1220 if ((Size == 8 || Size == 16 || Size == 32) ||
1221 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001222 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001223 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001224
John McCall7f416cc2015-09-08 08:05:57 +00001225 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001226 }
1227
1228 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001229 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001230
John McCalla1dee5302010-08-22 10:59:02 +00001231 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001232 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001233 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001234 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001235 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001236 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001237
David Chisnallde3a0692009-08-17 23:08:21 +00001238 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001239 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001240 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001241
Denis Zobnin380b2242016-02-11 11:26:03 +00001242 // Ignore empty structs/unions.
1243 if (isEmptyRecord(getContext(), RetTy, true))
1244 return ABIArgInfo::getIgnore();
1245
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001246 // Small structures which are register sized are generally returned
1247 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001248 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001249 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001250
1251 // As a special-case, if the struct is a "single-element" struct, and
1252 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001253 // floating-point register. (MSVC does not apply this special case.)
1254 // We apply a similar transformation for pointer types to improve the
1255 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001256 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001257 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001258 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001259 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1260
1261 // FIXME: We should be able to narrow this integer in cases with dead
1262 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001263 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001264 }
1265
John McCall7f416cc2015-09-08 08:05:57 +00001266 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001267 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001268
Chris Lattner458b2aa2010-07-29 02:16:43 +00001269 // Treat an enum type as its underlying type.
1270 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1271 RetTy = EnumTy->getDecl()->getIntegerType();
1272
1273 return (RetTy->isPromotableIntegerType() ?
1274 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001275}
1276
Eli Friedman7919bea2012-06-05 19:40:46 +00001277static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1278 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1279}
1280
Daniel Dunbared23de32010-09-16 20:42:00 +00001281static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1282 const RecordType *RT = Ty->getAs<RecordType>();
1283 if (!RT)
1284 return 0;
1285 const RecordDecl *RD = RT->getDecl();
1286
1287 // If this is a C++ record, check the bases first.
1288 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001289 for (const auto &I : CXXRD->bases())
1290 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001291 return false;
1292
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001293 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001294 QualType FT = i->getType();
1295
Eli Friedman7919bea2012-06-05 19:40:46 +00001296 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001297 return true;
1298
1299 if (isRecordWithSSEVectorType(Context, FT))
1300 return true;
1301 }
1302
1303 return false;
1304}
1305
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001306unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1307 unsigned Align) const {
1308 // Otherwise, if the alignment is less than or equal to the minimum ABI
1309 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001310 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001311 return 0; // Use default alignment.
1312
1313 // On non-Darwin, the stack type alignment is always 4.
1314 if (!IsDarwinVectorABI) {
1315 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001316 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001317 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001318
Daniel Dunbared23de32010-09-16 20:42:00 +00001319 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001320 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1321 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001322 return 16;
1323
1324 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001325}
1326
Rafael Espindola703c47f2012-10-19 05:04:37 +00001327ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001328 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001329 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001330 if (State.FreeRegs) {
1331 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001332 if (!IsMCUABI)
1333 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001334 }
John McCall7f416cc2015-09-08 08:05:57 +00001335 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001336 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001337
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001338 // Compute the byval alignment.
1339 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1340 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1341 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001342 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001343
1344 // If the stack alignment is less than the type alignment, realign the
1345 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001346 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001347 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1348 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001349}
1350
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001351X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1352 const Type *T = isSingleElementStruct(Ty, getContext());
1353 if (!T)
1354 T = Ty.getTypePtr();
1355
1356 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1357 BuiltinType::Kind K = BT->getKind();
1358 if (K == BuiltinType::Float || K == BuiltinType::Double)
1359 return Float;
1360 }
1361 return Integer;
1362}
1363
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001364bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001365 if (!IsSoftFloatABI) {
1366 Class C = classify(Ty);
1367 if (C == Float)
1368 return false;
1369 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001370
Rafael Espindola077dd592012-10-24 01:58:58 +00001371 unsigned Size = getContext().getTypeSize(Ty);
1372 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001373
1374 if (SizeInRegs == 0)
1375 return false;
1376
Michael Kuperstein68901882015-10-25 08:18:20 +00001377 if (!IsMCUABI) {
1378 if (SizeInRegs > State.FreeRegs) {
1379 State.FreeRegs = 0;
1380 return false;
1381 }
1382 } else {
1383 // The MCU psABI allows passing parameters in-reg even if there are
1384 // earlier parameters that are passed on the stack. Also,
1385 // it does not allow passing >8-byte structs in-register,
1386 // even if there are 3 free registers available.
1387 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1388 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001389 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001390
Reid Kleckner661f35b2014-01-18 01:12:41 +00001391 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001392 return true;
1393}
1394
1395bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1396 bool &InReg,
1397 bool &NeedsPadding) const {
1398 NeedsPadding = false;
1399 InReg = !IsMCUABI;
1400
1401 if (!updateFreeRegs(Ty, State))
1402 return false;
1403
1404 if (IsMCUABI)
1405 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001406
Reid Kleckner80944df2014-10-31 22:00:51 +00001407 if (State.CC == llvm::CallingConv::X86_FastCall ||
1408 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001409 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001410 NeedsPadding = true;
1411
Rafael Espindola077dd592012-10-24 01:58:58 +00001412 return false;
1413 }
1414
Rafael Espindola703c47f2012-10-19 05:04:37 +00001415 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001416}
1417
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001418bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1419 if (!updateFreeRegs(Ty, State))
1420 return false;
1421
1422 if (IsMCUABI)
1423 return false;
1424
1425 if (State.CC == llvm::CallingConv::X86_FastCall ||
1426 State.CC == llvm::CallingConv::X86_VectorCall) {
1427 if (getContext().getTypeSize(Ty) > 32)
1428 return false;
1429
1430 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1431 Ty->isReferenceType());
1432 }
1433
1434 return true;
1435}
1436
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001437ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1438 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001439 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001440
Reid Klecknerb1be6832014-11-15 01:41:41 +00001441 Ty = useFirstFieldIfTransparentUnion(Ty);
1442
Reid Kleckner80944df2014-10-31 22:00:51 +00001443 // Check with the C++ ABI first.
1444 const RecordType *RT = Ty->getAs<RecordType>();
1445 if (RT) {
1446 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1447 if (RAA == CGCXXABI::RAA_Indirect) {
1448 return getIndirectResult(Ty, false, State);
1449 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1450 // The field index doesn't matter, we'll fix it up later.
1451 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1452 }
1453 }
1454
1455 // vectorcall adds the concept of a homogenous vector aggregate, similar
1456 // to other targets.
1457 const Type *Base = nullptr;
1458 uint64_t NumElts = 0;
1459 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1460 isHomogeneousAggregate(Ty, Base, NumElts)) {
1461 if (State.FreeSSERegs >= NumElts) {
1462 State.FreeSSERegs -= NumElts;
1463 if (Ty->isBuiltinType() || Ty->isVectorType())
1464 return ABIArgInfo::getDirect();
1465 return ABIArgInfo::getExpand();
1466 }
1467 return getIndirectResult(Ty, /*ByVal=*/false, State);
1468 }
1469
1470 if (isAggregateTypeForABI(Ty)) {
1471 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001472 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001473 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001474 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001475
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001476 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001477 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001478 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001479 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001480
Eli Friedman9f061a32011-11-18 00:28:11 +00001481 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001482 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001483 return ABIArgInfo::getIgnore();
1484
Rafael Espindolafad28de2012-10-24 01:59:00 +00001485 llvm::LLVMContext &LLVMContext = getVMContext();
1486 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001487 bool NeedsPadding, InReg;
1488 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001489 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001490 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001491 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001492 if (InReg)
1493 return ABIArgInfo::getDirectInReg(Result);
1494 else
1495 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001496 }
Craig Topper8a13c412014-05-21 05:09:00 +00001497 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001498
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001499 // Expand small (<= 128-bit) record types when we know that the stack layout
1500 // of those arguments will match the struct. This is important because the
1501 // LLVM backend isn't smart enough to remove byval, which inhibits many
1502 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001503 // Don't do this for the MCU if there are still free integer registers
1504 // (see X86_64 ABI for full explanation).
Chris Lattner458b2aa2010-07-29 02:16:43 +00001505 if (getContext().getTypeSize(Ty) <= 4*32 &&
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001506 canExpandIndirectArgument(Ty, getContext()) &&
1507 (!IsMCUABI || State.FreeRegs == 0))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001508 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001509 State.CC == llvm::CallingConv::X86_FastCall ||
1510 State.CC == llvm::CallingConv::X86_VectorCall,
1511 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001512
Reid Kleckner661f35b2014-01-18 01:12:41 +00001513 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001514 }
1515
Chris Lattnerd774ae92010-08-26 20:05:13 +00001516 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001517 // On Darwin, some vectors are passed in memory, we handle this by passing
1518 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001519 if (IsDarwinVectorABI) {
1520 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001521 if ((Size == 8 || Size == 16 || Size == 32) ||
1522 (Size == 64 && VT->getNumElements() == 1))
1523 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1524 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001525 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001526
Chad Rosier651c1832013-03-25 21:00:27 +00001527 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1528 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001529
Chris Lattnerd774ae92010-08-26 20:05:13 +00001530 return ABIArgInfo::getDirect();
1531 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001532
1533
Chris Lattner458b2aa2010-07-29 02:16:43 +00001534 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1535 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001536
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001537 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001538
1539 if (Ty->isPromotableIntegerType()) {
1540 if (InReg)
1541 return ABIArgInfo::getExtendInReg();
1542 return ABIArgInfo::getExtend();
1543 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001544
Rafael Espindola703c47f2012-10-19 05:04:37 +00001545 if (InReg)
1546 return ABIArgInfo::getDirectInReg();
1547 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001548}
1549
Rafael Espindolaa6472962012-07-24 00:01:07 +00001550void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001551 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001552 if (IsMCUABI)
1553 State.FreeRegs = 3;
1554 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001555 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001556 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1557 State.FreeRegs = 2;
1558 State.FreeSSERegs = 6;
1559 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001560 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001561 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001562 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001563
Reid Kleckner677539d2014-07-10 01:58:55 +00001564 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001565 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001566 } else if (FI.getReturnInfo().isIndirect()) {
1567 // The C++ ABI is not aware of register usage, so we have to check if the
1568 // return value was sret and put it in a register ourselves if appropriate.
1569 if (State.FreeRegs) {
1570 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001571 if (!IsMCUABI)
1572 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001573 }
1574 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001575
Peter Collingbournef7706832014-12-12 23:41:25 +00001576 // The chain argument effectively gives us another free register.
1577 if (FI.isChainCall())
1578 ++State.FreeRegs;
1579
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001580 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001581 for (auto &I : FI.arguments()) {
1582 I.info = classifyArgumentType(I.type, State);
1583 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001584 }
1585
1586 // If we needed to use inalloca for any argument, do a second pass and rewrite
1587 // all the memory arguments to use inalloca.
1588 if (UsedInAlloca)
1589 rewriteWithInAlloca(FI);
1590}
1591
1592void
1593X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001594 CharUnits &StackOffset, ABIArgInfo &Info,
1595 QualType Type) const {
1596 // Arguments are always 4-byte-aligned.
1597 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1598
1599 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001600 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1601 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001602 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001603
John McCall7f416cc2015-09-08 08:05:57 +00001604 // Insert padding bytes to respect alignment.
1605 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001606 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001607 if (StackOffset != FieldEnd) {
1608 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001609 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001610 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001611 FrameFields.push_back(Ty);
1612 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001613}
1614
Reid Kleckner852361d2014-07-26 00:12:26 +00001615static bool isArgInAlloca(const ABIArgInfo &Info) {
1616 // Leave ignored and inreg arguments alone.
1617 switch (Info.getKind()) {
1618 case ABIArgInfo::InAlloca:
1619 return true;
1620 case ABIArgInfo::Indirect:
1621 assert(Info.getIndirectByVal());
1622 return true;
1623 case ABIArgInfo::Ignore:
1624 return false;
1625 case ABIArgInfo::Direct:
1626 case ABIArgInfo::Extend:
1627 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00001628 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner852361d2014-07-26 00:12:26 +00001629 if (Info.getInReg())
1630 return false;
1631 return true;
1632 }
1633 llvm_unreachable("invalid enum");
1634}
1635
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001636void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1637 assert(IsWin32StructABI && "inalloca only supported on win32");
1638
1639 // Build a packed struct type for all of the arguments in memory.
1640 SmallVector<llvm::Type *, 6> FrameFields;
1641
John McCall7f416cc2015-09-08 08:05:57 +00001642 // The stack alignment is always 4.
1643 CharUnits StackAlign = CharUnits::fromQuantity(4);
1644
1645 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001646 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1647
1648 // Put 'this' into the struct before 'sret', if necessary.
1649 bool IsThisCall =
1650 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1651 ABIArgInfo &Ret = FI.getReturnInfo();
1652 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1653 isArgInAlloca(I->info)) {
1654 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1655 ++I;
1656 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001657
1658 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001659 if (Ret.isIndirect() && !Ret.getInReg()) {
1660 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1661 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001662 // On Windows, the hidden sret parameter is always returned in eax.
1663 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001664 }
1665
1666 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001667 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001668 ++I;
1669
1670 // Put arguments passed in memory into the struct.
1671 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001672 if (isArgInAlloca(I->info))
1673 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001674 }
1675
1676 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001677 /*isPacked=*/true),
1678 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001679}
1680
John McCall7f416cc2015-09-08 08:05:57 +00001681Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1682 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001683
John McCall7f416cc2015-09-08 08:05:57 +00001684 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001685
John McCall7f416cc2015-09-08 08:05:57 +00001686 // x86-32 changes the alignment of certain arguments on the stack.
1687 //
1688 // Just messing with TypeInfo like this works because we never pass
1689 // anything indirectly.
1690 TypeInfo.second = CharUnits::fromQuantity(
1691 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001692
John McCall7f416cc2015-09-08 08:05:57 +00001693 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1694 TypeInfo, CharUnits::fromQuantity(4),
1695 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001696}
1697
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001698bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1699 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1700 assert(Triple.getArch() == llvm::Triple::x86);
1701
1702 switch (Opts.getStructReturnConvention()) {
1703 case CodeGenOptions::SRCK_Default:
1704 break;
1705 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1706 return false;
1707 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1708 return true;
1709 }
1710
Michael Kupersteind749f232015-10-27 07:46:22 +00001711 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001712 return true;
1713
1714 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001715 case llvm::Triple::DragonFly:
1716 case llvm::Triple::FreeBSD:
1717 case llvm::Triple::OpenBSD:
1718 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001719 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001720 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001721 default:
1722 return false;
1723 }
1724}
1725
Eric Christopher162c91c2015-06-05 22:03:00 +00001726void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001727 llvm::GlobalValue *GV,
1728 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001729 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001730 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1731 // Get the LLVM function.
1732 llvm::Function *Fn = cast<llvm::Function>(GV);
1733
1734 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001735 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001736 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001737 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1738 llvm::AttributeSet::get(CGM.getLLVMContext(),
1739 llvm::AttributeSet::FunctionIndex,
1740 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001741 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001742 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1743 llvm::Function *Fn = cast<llvm::Function>(GV);
1744 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1745 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001746 }
1747}
1748
John McCallbeec5a02010-03-06 00:35:14 +00001749bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1750 CodeGen::CodeGenFunction &CGF,
1751 llvm::Value *Address) const {
1752 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001753
Chris Lattnerece04092012-02-07 00:39:47 +00001754 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001755
John McCallbeec5a02010-03-06 00:35:14 +00001756 // 0-7 are the eight integer registers; the order is different
1757 // on Darwin (for EH), but the range is the same.
1758 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001759 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001760
John McCallc8e01702013-04-16 22:48:15 +00001761 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001762 // 12-16 are st(0..4). Not sure why we stop at 4.
1763 // These have size 16, which is sizeof(long double) on
1764 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001765 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001766 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001767
John McCallbeec5a02010-03-06 00:35:14 +00001768 } else {
1769 // 9 is %eflags, which doesn't get a size on Darwin for some
1770 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001771 Builder.CreateAlignedStore(
1772 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1773 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001774
1775 // 11-16 are st(0..5). Not sure why we stop at 5.
1776 // These have size 12, which is sizeof(long double) on
1777 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001778 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001779 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1780 }
John McCallbeec5a02010-03-06 00:35:14 +00001781
1782 return false;
1783}
1784
Chris Lattner0cf24192010-06-28 20:05:43 +00001785//===----------------------------------------------------------------------===//
1786// X86-64 ABI Implementation
1787//===----------------------------------------------------------------------===//
1788
1789
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001790namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001791/// The AVX ABI level for X86 targets.
1792enum class X86AVXABILevel {
1793 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001794 AVX,
1795 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001796};
1797
1798/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1799static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1800 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001801 case X86AVXABILevel::AVX512:
1802 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001803 case X86AVXABILevel::AVX:
1804 return 256;
1805 case X86AVXABILevel::None:
1806 return 128;
1807 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001808 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001809}
1810
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001811/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001812class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001813 enum Class {
1814 Integer = 0,
1815 SSE,
1816 SSEUp,
1817 X87,
1818 X87Up,
1819 ComplexX87,
1820 NoClass,
1821 Memory
1822 };
1823
1824 /// merge - Implement the X86_64 ABI merging algorithm.
1825 ///
1826 /// Merge an accumulating classification \arg Accum with a field
1827 /// classification \arg Field.
1828 ///
1829 /// \param Accum - The accumulating classification. This should
1830 /// always be either NoClass or the result of a previous merge
1831 /// call. In addition, this should never be Memory (the caller
1832 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001833 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001834
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001835 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1836 ///
1837 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1838 /// final MEMORY or SSE classes when necessary.
1839 ///
1840 /// \param AggregateSize - The size of the current aggregate in
1841 /// the classification process.
1842 ///
1843 /// \param Lo - The classification for the parts of the type
1844 /// residing in the low word of the containing object.
1845 ///
1846 /// \param Hi - The classification for the parts of the type
1847 /// residing in the higher words of the containing object.
1848 ///
1849 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1850
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001851 /// classify - Determine the x86_64 register classes in which the
1852 /// given type T should be passed.
1853 ///
1854 /// \param Lo - The classification for the parts of the type
1855 /// residing in the low word of the containing object.
1856 ///
1857 /// \param Hi - The classification for the parts of the type
1858 /// residing in the high word of the containing object.
1859 ///
1860 /// \param OffsetBase - The bit offset of this type in the
1861 /// containing object. Some parameters are classified different
1862 /// depending on whether they straddle an eightbyte boundary.
1863 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001864 /// \param isNamedArg - Whether the argument in question is a "named"
1865 /// argument, as used in AMD64-ABI 3.5.7.
1866 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001867 /// If a word is unused its result will be NoClass; if a type should
1868 /// be passed in Memory then at least the classification of \arg Lo
1869 /// will be Memory.
1870 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001871 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001872 ///
1873 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1874 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001875 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1876 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001877
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001878 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001879 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1880 unsigned IROffset, QualType SourceTy,
1881 unsigned SourceOffset) const;
1882 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1883 unsigned IROffset, QualType SourceTy,
1884 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001885
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001886 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001887 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001888 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001889
1890 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001891 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001892 ///
1893 /// \param freeIntRegs - The number of free integer registers remaining
1894 /// available.
1895 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001896
Chris Lattner458b2aa2010-07-29 02:16:43 +00001897 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001898
Bill Wendling5cd41c42010-10-18 03:41:31 +00001899 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001900 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001901 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001902 unsigned &neededSSE,
1903 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001904
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001905 bool IsIllegalVectorType(QualType Ty) const;
1906
John McCalle0fda732011-04-21 01:20:55 +00001907 /// The 0.98 ABI revision clarified a lot of ambiguities,
1908 /// unfortunately in ways that were not always consistent with
1909 /// certain previous compilers. In particular, platforms which
1910 /// required strict binary compatibility with older versions of GCC
1911 /// may need to exempt themselves.
1912 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001913 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001914 }
1915
David Majnemere2ae2282016-03-04 05:26:16 +00001916 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1917 // compilers require us to classify it as INTEGER.
1918 bool classifyIntegerMMXAsSSE() const {
1919 const llvm::Triple &Triple = getTarget().getTriple();
1920 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1921 return false;
1922 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1923 return false;
1924 return true;
1925 }
1926
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001927 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001928 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1929 // 64-bit hardware.
1930 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001931
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001932public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001933 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00001934 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001935 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001936 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001937
John McCalla729c622012-02-17 03:33:10 +00001938 bool isPassedUsingAVXType(QualType type) const {
1939 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001940 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001941 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1942 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001943 if (info.isDirect()) {
1944 llvm::Type *ty = info.getCoerceToType();
1945 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1946 return (vectorTy->getBitWidth() > 128);
1947 }
1948 return false;
1949 }
1950
Craig Topper4f12f102014-03-12 06:41:41 +00001951 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001952
John McCall7f416cc2015-09-08 08:05:57 +00001953 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1954 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001955 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1956 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001957
1958 bool has64BitPointers() const {
1959 return Has64BitPointers;
1960 }
John McCall12f23522016-04-04 18:33:08 +00001961
1962 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1963 ArrayRef<llvm::Type*> scalars,
1964 bool asReturnValue) const override {
1965 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
1966 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001967};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001968
Chris Lattner04dc9572010-08-31 16:44:54 +00001969/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001970class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001971public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001972 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1973 : ABIInfo(CGT),
1974 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001975
Craig Topper4f12f102014-03-12 06:41:41 +00001976 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001977
John McCall7f416cc2015-09-08 08:05:57 +00001978 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1979 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001980
1981 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1982 // FIXME: Assumes vectorcall is in use.
1983 return isX86VectorTypeForVectorCall(getContext(), Ty);
1984 }
1985
1986 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1987 uint64_t NumMembers) const override {
1988 // FIXME: Assumes vectorcall is in use.
1989 return isX86VectorCallAggregateSmallEnough(NumMembers);
1990 }
Reid Kleckner11a17192015-10-28 22:29:52 +00001991
1992private:
1993 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1994 bool IsReturnType) const;
1995
1996 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00001997};
1998
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001999class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2000public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002001 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002002 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002003
John McCalla729c622012-02-17 03:33:10 +00002004 const X86_64ABIInfo &getABIInfo() const {
2005 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2006 }
2007
Craig Topper4f12f102014-03-12 06:41:41 +00002008 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002009 return 7;
2010 }
2011
2012 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002013 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002014 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002015
John McCall943fae92010-05-27 06:19:26 +00002016 // 0-15 are the 16 integer registers.
2017 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002018 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002019 return false;
2020 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002021
Jay Foad7c57be32011-07-11 09:56:20 +00002022 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002023 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002024 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002025 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2026 }
2027
John McCalla729c622012-02-17 03:33:10 +00002028 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002029 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002030 // The default CC on x86-64 sets %al to the number of SSA
2031 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002032 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002033 // that when AVX types are involved: the ABI explicitly states it is
2034 // undefined, and it doesn't work in practice because of how the ABI
2035 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002036 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002037 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002038 for (CallArgList::const_iterator
2039 it = args.begin(), ie = args.end(); it != ie; ++it) {
2040 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2041 HasAVXType = true;
2042 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002043 }
2044 }
John McCalla729c622012-02-17 03:33:10 +00002045
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002046 if (!HasAVXType)
2047 return true;
2048 }
John McCallcbc038a2011-09-21 08:08:30 +00002049
John McCalla729c622012-02-17 03:33:10 +00002050 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002051 }
2052
Craig Topper4f12f102014-03-12 06:41:41 +00002053 llvm::Constant *
2054 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002055 unsigned Sig;
2056 if (getABIInfo().has64BitPointers())
2057 Sig = (0xeb << 0) | // jmp rel8
2058 (0x0a << 8) | // .+0x0c
2059 ('F' << 16) |
2060 ('T' << 24);
2061 else
2062 Sig = (0xeb << 0) | // jmp rel8
2063 (0x06 << 8) | // .+0x08
2064 ('F' << 16) |
2065 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002066 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2067 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002068
2069 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2070 CodeGen::CodeGenModule &CGM) const override {
2071 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2072 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2073 llvm::Function *Fn = cast<llvm::Function>(GV);
2074 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2075 }
2076 }
2077 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002078};
2079
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002080class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2081public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002082 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2083 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002084
2085 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002086 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002087 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002088 // If the argument contains a space, enclose it in quotes.
2089 if (Lib.find(" ") != StringRef::npos)
2090 Opt += "\"" + Lib.str() + "\"";
2091 else
2092 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002093 }
2094};
2095
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002096static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002097 // If the argument does not end in .lib, automatically add the suffix.
2098 // If the argument contains a space, enclose it in quotes.
2099 // This matches the behavior of MSVC.
2100 bool Quote = (Lib.find(" ") != StringRef::npos);
2101 std::string ArgStr = Quote ? "\"" : "";
2102 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002103 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002104 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002105 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002106 return ArgStr;
2107}
2108
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002109class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2110public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002111 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002112 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2113 unsigned NumRegisterParameters)
2114 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002115 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002116
Eric Christopher162c91c2015-06-05 22:03:00 +00002117 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002118 CodeGen::CodeGenModule &CGM) const override;
2119
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002120 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002121 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002122 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002123 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002124 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002125
2126 void getDetectMismatchOption(llvm::StringRef Name,
2127 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002128 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002129 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002130 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002131};
2132
Hans Wennborg77dc2362015-01-20 19:45:50 +00002133static void addStackProbeSizeTargetAttribute(const Decl *D,
2134 llvm::GlobalValue *GV,
2135 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002136 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002137 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2138 llvm::Function *Fn = cast<llvm::Function>(GV);
2139
Eric Christopher7565e0d2015-05-29 23:09:49 +00002140 Fn->addFnAttr("stack-probe-size",
2141 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002142 }
2143 }
2144}
2145
Eric Christopher162c91c2015-06-05 22:03:00 +00002146void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002147 llvm::GlobalValue *GV,
2148 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002149 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002150
2151 addStackProbeSizeTargetAttribute(D, GV, CGM);
2152}
2153
Chris Lattner04dc9572010-08-31 16:44:54 +00002154class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2155public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002156 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2157 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002158 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002159
Eric Christopher162c91c2015-06-05 22:03:00 +00002160 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002161 CodeGen::CodeGenModule &CGM) const override;
2162
Craig Topper4f12f102014-03-12 06:41:41 +00002163 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002164 return 7;
2165 }
2166
2167 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002168 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002169 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002170
Chris Lattner04dc9572010-08-31 16:44:54 +00002171 // 0-15 are the 16 integer registers.
2172 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002173 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002174 return false;
2175 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002176
2177 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002178 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002179 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002180 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002181 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002182
2183 void getDetectMismatchOption(llvm::StringRef Name,
2184 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002185 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002186 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002187 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002188};
2189
Eric Christopher162c91c2015-06-05 22:03:00 +00002190void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002191 llvm::GlobalValue *GV,
2192 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002193 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002194
Alexey Bataevd51e9932016-01-15 04:06:31 +00002195 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2196 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2197 llvm::Function *Fn = cast<llvm::Function>(GV);
2198 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2199 }
2200 }
2201
Hans Wennborg77dc2362015-01-20 19:45:50 +00002202 addStackProbeSizeTargetAttribute(D, GV, CGM);
2203}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002204}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002205
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002206void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2207 Class &Hi) const {
2208 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2209 //
2210 // (a) If one of the classes is Memory, the whole argument is passed in
2211 // memory.
2212 //
2213 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2214 // memory.
2215 //
2216 // (c) If the size of the aggregate exceeds two eightbytes and the first
2217 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2218 // argument is passed in memory. NOTE: This is necessary to keep the
2219 // ABI working for processors that don't support the __m256 type.
2220 //
2221 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2222 //
2223 // Some of these are enforced by the merging logic. Others can arise
2224 // only with unions; for example:
2225 // union { _Complex double; unsigned; }
2226 //
2227 // Note that clauses (b) and (c) were added in 0.98.
2228 //
2229 if (Hi == Memory)
2230 Lo = Memory;
2231 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2232 Lo = Memory;
2233 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2234 Lo = Memory;
2235 if (Hi == SSEUp && Lo != SSE)
2236 Hi = SSE;
2237}
2238
Chris Lattnerd776fb12010-06-28 21:43:59 +00002239X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002240 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2241 // classified recursively so that always two fields are
2242 // considered. The resulting class is calculated according to
2243 // the classes of the fields in the eightbyte:
2244 //
2245 // (a) If both classes are equal, this is the resulting class.
2246 //
2247 // (b) If one of the classes is NO_CLASS, the resulting class is
2248 // the other class.
2249 //
2250 // (c) If one of the classes is MEMORY, the result is the MEMORY
2251 // class.
2252 //
2253 // (d) If one of the classes is INTEGER, the result is the
2254 // INTEGER.
2255 //
2256 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2257 // MEMORY is used as class.
2258 //
2259 // (f) Otherwise class SSE is used.
2260
2261 // Accum should never be memory (we should have returned) or
2262 // ComplexX87 (because this cannot be passed in a structure).
2263 assert((Accum != Memory && Accum != ComplexX87) &&
2264 "Invalid accumulated classification during merge.");
2265 if (Accum == Field || Field == NoClass)
2266 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002267 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002268 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002269 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002270 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002271 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002272 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002273 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2274 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002275 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002276 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002277}
2278
Chris Lattner5c740f12010-06-30 19:14:05 +00002279void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002280 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002281 // FIXME: This code can be simplified by introducing a simple value class for
2282 // Class pairs with appropriate constructor methods for the various
2283 // situations.
2284
2285 // FIXME: Some of the split computations are wrong; unaligned vectors
2286 // shouldn't be passed in registers for example, so there is no chance they
2287 // can straddle an eightbyte. Verify & simplify.
2288
2289 Lo = Hi = NoClass;
2290
2291 Class &Current = OffsetBase < 64 ? Lo : Hi;
2292 Current = Memory;
2293
John McCall9dd450b2009-09-21 23:43:11 +00002294 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002295 BuiltinType::Kind k = BT->getKind();
2296
2297 if (k == BuiltinType::Void) {
2298 Current = NoClass;
2299 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2300 Lo = Integer;
2301 Hi = Integer;
2302 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2303 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002304 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002305 Current = SSE;
2306 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002307 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2308 if (LDF == &llvm::APFloat::IEEEquad) {
2309 Lo = SSE;
2310 Hi = SSEUp;
2311 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2312 Lo = X87;
2313 Hi = X87Up;
2314 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2315 Current = SSE;
2316 } else
2317 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002318 }
2319 // FIXME: _Decimal32 and _Decimal64 are SSE.
2320 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002321 return;
2322 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002323
Chris Lattnerd776fb12010-06-28 21:43:59 +00002324 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002325 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002326 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002327 return;
2328 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002329
Chris Lattnerd776fb12010-06-28 21:43:59 +00002330 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002331 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002332 return;
2333 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002334
Chris Lattnerd776fb12010-06-28 21:43:59 +00002335 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002336 if (Ty->isMemberFunctionPointerType()) {
2337 if (Has64BitPointers) {
2338 // If Has64BitPointers, this is an {i64, i64}, so classify both
2339 // Lo and Hi now.
2340 Lo = Hi = Integer;
2341 } else {
2342 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2343 // straddles an eightbyte boundary, Hi should be classified as well.
2344 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2345 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2346 if (EB_FuncPtr != EB_ThisAdj) {
2347 Lo = Hi = Integer;
2348 } else {
2349 Current = Integer;
2350 }
2351 }
2352 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002353 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002354 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002355 return;
2356 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002357
Chris Lattnerd776fb12010-06-28 21:43:59 +00002358 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002359 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002360 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2361 // gcc passes the following as integer:
2362 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2363 // 2 bytes - <2 x char>, <1 x short>
2364 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002365 Current = Integer;
2366
2367 // If this type crosses an eightbyte boundary, it should be
2368 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002369 uint64_t EB_Lo = (OffsetBase) / 64;
2370 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2371 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002372 Hi = Lo;
2373 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002374 QualType ElementType = VT->getElementType();
2375
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002376 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002377 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002378 return;
2379
David Majnemere2ae2282016-03-04 05:26:16 +00002380 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2381 // pass them as integer. For platforms where clang is the de facto
2382 // platform compiler, we must continue to use integer.
2383 if (!classifyIntegerMMXAsSSE() &&
2384 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2385 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2386 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2387 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002388 Current = Integer;
2389 else
2390 Current = SSE;
2391
2392 // If this type crosses an eightbyte boundary, it should be
2393 // split.
2394 if (OffsetBase && OffsetBase != 64)
2395 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002396 } else if (Size == 128 ||
2397 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002398 // Arguments of 256-bits are split into four eightbyte chunks. The
2399 // least significant one belongs to class SSE and all the others to class
2400 // SSEUP. The original Lo and Hi design considers that types can't be
2401 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2402 // This design isn't correct for 256-bits, but since there're no cases
2403 // where the upper parts would need to be inspected, avoid adding
2404 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002405 //
2406 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2407 // registers if they are "named", i.e. not part of the "..." of a
2408 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002409 //
2410 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2411 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002412 Lo = SSE;
2413 Hi = SSEUp;
2414 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002415 return;
2416 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002417
Chris Lattnerd776fb12010-06-28 21:43:59 +00002418 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002419 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002420
Chris Lattner2b037972010-07-29 02:01:43 +00002421 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002422 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002423 if (Size <= 64)
2424 Current = Integer;
2425 else if (Size <= 128)
2426 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002427 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002428 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002429 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002430 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002431 } else if (ET == getContext().LongDoubleTy) {
2432 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2433 if (LDF == &llvm::APFloat::IEEEquad)
2434 Current = Memory;
2435 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2436 Current = ComplexX87;
2437 else if (LDF == &llvm::APFloat::IEEEdouble)
2438 Lo = Hi = SSE;
2439 else
2440 llvm_unreachable("unexpected long double representation!");
2441 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002442
2443 // If this complex type crosses an eightbyte boundary then it
2444 // should be split.
2445 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002446 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002447 if (Hi == NoClass && EB_Real != EB_Imag)
2448 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002449
Chris Lattnerd776fb12010-06-28 21:43:59 +00002450 return;
2451 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002452
Chris Lattner2b037972010-07-29 02:01:43 +00002453 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002454 // Arrays are treated like structures.
2455
Chris Lattner2b037972010-07-29 02:01:43 +00002456 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002457
2458 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002459 // than four eightbytes, ..., it has class MEMORY.
2460 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002461 return;
2462
2463 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2464 // fields, it has class MEMORY.
2465 //
2466 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002467 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002468 return;
2469
2470 // Otherwise implement simplified merge. We could be smarter about
2471 // this, but it isn't worth it and would be harder to verify.
2472 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002473 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002474 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002475
2476 // The only case a 256-bit wide vector could be used is when the array
2477 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2478 // to work for sizes wider than 128, early check and fallback to memory.
2479 if (Size > 128 && EltSize != 256)
2480 return;
2481
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002482 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2483 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002484 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002485 Lo = merge(Lo, FieldLo);
2486 Hi = merge(Hi, FieldHi);
2487 if (Lo == Memory || Hi == Memory)
2488 break;
2489 }
2490
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002491 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002492 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002493 return;
2494 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002495
Chris Lattnerd776fb12010-06-28 21:43:59 +00002496 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002497 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002498
2499 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002500 // than four eightbytes, ..., it has class MEMORY.
2501 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002502 return;
2503
Anders Carlsson20759ad2009-09-16 15:53:40 +00002504 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2505 // copy constructor or a non-trivial destructor, it is passed by invisible
2506 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002507 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002508 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002509
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002510 const RecordDecl *RD = RT->getDecl();
2511
2512 // Assume variable sized types are passed in memory.
2513 if (RD->hasFlexibleArrayMember())
2514 return;
2515
Chris Lattner2b037972010-07-29 02:01:43 +00002516 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002517
2518 // Reset Lo class, this will be recomputed.
2519 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002520
2521 // If this is a C++ record, classify the bases first.
2522 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002523 for (const auto &I : CXXRD->bases()) {
2524 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002525 "Unexpected base class!");
2526 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002527 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002528
2529 // Classify this field.
2530 //
2531 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2532 // single eightbyte, each is classified separately. Each eightbyte gets
2533 // initialized to class NO_CLASS.
2534 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002535 uint64_t Offset =
2536 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002537 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002538 Lo = merge(Lo, FieldLo);
2539 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002540 if (Lo == Memory || Hi == Memory) {
2541 postMerge(Size, Lo, Hi);
2542 return;
2543 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002544 }
2545 }
2546
2547 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002548 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002549 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002550 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002551 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2552 bool BitField = i->isBitField();
2553
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002554 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2555 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002556 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002557 // The only case a 256-bit wide vector could be used is when the struct
2558 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2559 // to work for sizes wider than 128, early check and fallback to memory.
2560 //
2561 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2562 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002563 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002564 return;
2565 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002566 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002567 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002568 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002569 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002570 return;
2571 }
2572
2573 // Classify this field.
2574 //
2575 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2576 // exceeds a single eightbyte, each is classified
2577 // separately. Each eightbyte gets initialized to class
2578 // NO_CLASS.
2579 Class FieldLo, FieldHi;
2580
2581 // Bit-fields require special handling, they do not force the
2582 // structure to be passed in memory even if unaligned, and
2583 // therefore they can straddle an eightbyte.
2584 if (BitField) {
2585 // Ignore padding bit-fields.
2586 if (i->isUnnamedBitfield())
2587 continue;
2588
2589 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002590 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002591
2592 uint64_t EB_Lo = Offset / 64;
2593 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002594
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002595 if (EB_Lo) {
2596 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2597 FieldLo = NoClass;
2598 FieldHi = Integer;
2599 } else {
2600 FieldLo = Integer;
2601 FieldHi = EB_Hi ? Integer : NoClass;
2602 }
2603 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002604 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002605 Lo = merge(Lo, FieldLo);
2606 Hi = merge(Hi, FieldHi);
2607 if (Lo == Memory || Hi == Memory)
2608 break;
2609 }
2610
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002611 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002612 }
2613}
2614
Chris Lattner22a931e2010-06-29 06:01:59 +00002615ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002616 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2617 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002618 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002619 // Treat an enum type as its underlying type.
2620 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2621 Ty = EnumTy->getDecl()->getIntegerType();
2622
2623 return (Ty->isPromotableIntegerType() ?
2624 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2625 }
2626
John McCall7f416cc2015-09-08 08:05:57 +00002627 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002628}
2629
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002630bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2631 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2632 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002633 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002634 if (Size <= 64 || Size > LargestVector)
2635 return true;
2636 }
2637
2638 return false;
2639}
2640
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002641ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2642 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002643 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2644 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002645 //
2646 // This assumption is optimistic, as there could be free registers available
2647 // when we need to pass this argument in memory, and LLVM could try to pass
2648 // the argument in the free register. This does not seem to happen currently,
2649 // but this code would be much safer if we could mark the argument with
2650 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002651 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002652 // Treat an enum type as its underlying type.
2653 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2654 Ty = EnumTy->getDecl()->getIntegerType();
2655
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002656 return (Ty->isPromotableIntegerType() ?
2657 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002658 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002659
Mark Lacey3825e832013-10-06 01:33:34 +00002660 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002661 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002662
Chris Lattner44c2b902011-05-22 23:21:23 +00002663 // Compute the byval alignment. We specify the alignment of the byval in all
2664 // cases so that the mid-level optimizer knows the alignment of the byval.
2665 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002666
2667 // Attempt to avoid passing indirect results using byval when possible. This
2668 // is important for good codegen.
2669 //
2670 // We do this by coercing the value into a scalar type which the backend can
2671 // handle naturally (i.e., without using byval).
2672 //
2673 // For simplicity, we currently only do this when we have exhausted all of the
2674 // free integer registers. Doing this when there are free integer registers
2675 // would require more care, as we would have to ensure that the coerced value
2676 // did not claim the unused register. That would require either reording the
2677 // arguments to the function (so that any subsequent inreg values came first),
2678 // or only doing this optimization when there were no following arguments that
2679 // might be inreg.
2680 //
2681 // We currently expect it to be rare (particularly in well written code) for
2682 // arguments to be passed on the stack when there are still free integer
2683 // registers available (this would typically imply large structs being passed
2684 // by value), so this seems like a fair tradeoff for now.
2685 //
2686 // We can revisit this if the backend grows support for 'onstack' parameter
2687 // attributes. See PR12193.
2688 if (freeIntRegs == 0) {
2689 uint64_t Size = getContext().getTypeSize(Ty);
2690
2691 // If this type fits in an eightbyte, coerce it into the matching integral
2692 // type, which will end up on the stack (with alignment 8).
2693 if (Align == 8 && Size <= 64)
2694 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2695 Size));
2696 }
2697
John McCall7f416cc2015-09-08 08:05:57 +00002698 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002699}
2700
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002701/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2702/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002703llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002704 // Wrapper structs/arrays that only contain vectors are passed just like
2705 // vectors; strip them off if present.
2706 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2707 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002708
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002709 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002710 if (isa<llvm::VectorType>(IRType) ||
2711 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002712 return IRType;
2713
2714 // We couldn't find the preferred IR vector type for 'Ty'.
2715 uint64_t Size = getContext().getTypeSize(Ty);
2716 assert((Size == 128 || Size == 256) && "Invalid type found!");
2717
2718 // Return a LLVM IR vector type based on the size of 'Ty'.
2719 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2720 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002721}
2722
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002723/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2724/// is known to either be off the end of the specified type or being in
2725/// alignment padding. The user type specified is known to be at most 128 bits
2726/// in size, and have passed through X86_64ABIInfo::classify with a successful
2727/// classification that put one of the two halves in the INTEGER class.
2728///
2729/// It is conservatively correct to return false.
2730static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2731 unsigned EndBit, ASTContext &Context) {
2732 // If the bytes being queried are off the end of the type, there is no user
2733 // data hiding here. This handles analysis of builtins, vectors and other
2734 // types that don't contain interesting padding.
2735 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2736 if (TySize <= StartBit)
2737 return true;
2738
Chris Lattner98076a22010-07-29 07:43:55 +00002739 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2740 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2741 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2742
2743 // Check each element to see if the element overlaps with the queried range.
2744 for (unsigned i = 0; i != NumElts; ++i) {
2745 // If the element is after the span we care about, then we're done..
2746 unsigned EltOffset = i*EltSize;
2747 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002748
Chris Lattner98076a22010-07-29 07:43:55 +00002749 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2750 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2751 EndBit-EltOffset, Context))
2752 return false;
2753 }
2754 // If it overlaps no elements, then it is safe to process as padding.
2755 return true;
2756 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002757
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002758 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2759 const RecordDecl *RD = RT->getDecl();
2760 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002761
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002762 // If this is a C++ record, check the bases first.
2763 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002764 for (const auto &I : CXXRD->bases()) {
2765 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002766 "Unexpected base class!");
2767 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002768 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002769
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002770 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002771 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002772 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002773
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002774 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002775 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002776 EndBit-BaseOffset, Context))
2777 return false;
2778 }
2779 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002780
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002781 // Verify that no field has data that overlaps the region of interest. Yes
2782 // this could be sped up a lot by being smarter about queried fields,
2783 // however we're only looking at structs up to 16 bytes, so we don't care
2784 // much.
2785 unsigned idx = 0;
2786 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2787 i != e; ++i, ++idx) {
2788 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002789
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002790 // If we found a field after the region we care about, then we're done.
2791 if (FieldOffset >= EndBit) break;
2792
2793 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2794 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2795 Context))
2796 return false;
2797 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002798
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002799 // If nothing in this record overlapped the area of interest, then we're
2800 // clean.
2801 return true;
2802 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002803
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002804 return false;
2805}
2806
Chris Lattnere556a712010-07-29 18:39:32 +00002807/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2808/// float member at the specified offset. For example, {int,{float}} has a
2809/// float at offset 4. It is conservatively correct for this routine to return
2810/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002811static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002812 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002813 // Base case if we find a float.
2814 if (IROffset == 0 && IRType->isFloatTy())
2815 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002816
Chris Lattnere556a712010-07-29 18:39:32 +00002817 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002818 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002819 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2820 unsigned Elt = SL->getElementContainingOffset(IROffset);
2821 IROffset -= SL->getElementOffset(Elt);
2822 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2823 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002824
Chris Lattnere556a712010-07-29 18:39:32 +00002825 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002826 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2827 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002828 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2829 IROffset -= IROffset/EltSize*EltSize;
2830 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2831 }
2832
2833 return false;
2834}
2835
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002836
2837/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2838/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002839llvm::Type *X86_64ABIInfo::
2840GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002841 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002842 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002843 // pass as float if the last 4 bytes is just padding. This happens for
2844 // structs that contain 3 floats.
2845 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2846 SourceOffset*8+64, getContext()))
2847 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002848
Chris Lattnere556a712010-07-29 18:39:32 +00002849 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2850 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2851 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002852 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2853 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002854 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002855
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002856 return llvm::Type::getDoubleTy(getVMContext());
2857}
2858
2859
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002860/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2861/// an 8-byte GPR. This means that we either have a scalar or we are talking
2862/// about the high or low part of an up-to-16-byte struct. This routine picks
2863/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002864/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2865/// etc).
2866///
2867/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2868/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2869/// the 8-byte value references. PrefType may be null.
2870///
Alp Toker9907f082014-07-09 14:06:35 +00002871/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002872/// an offset into this that we're processing (which is always either 0 or 8).
2873///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002874llvm::Type *X86_64ABIInfo::
2875GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002876 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002877 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2878 // returning an 8-byte unit starting with it. See if we can safely use it.
2879 if (IROffset == 0) {
2880 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002881 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2882 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002883 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002884
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002885 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2886 // goodness in the source type is just tail padding. This is allowed to
2887 // kick in for struct {double,int} on the int, but not on
2888 // struct{double,int,int} because we wouldn't return the second int. We
2889 // have to do this analysis on the source type because we can't depend on
2890 // unions being lowered a specific way etc.
2891 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002892 IRType->isIntegerTy(32) ||
2893 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2894 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2895 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002896
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002897 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2898 SourceOffset*8+64, getContext()))
2899 return IRType;
2900 }
2901 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002902
Chris Lattner2192fe52011-07-18 04:24:23 +00002903 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002904 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002905 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002906 if (IROffset < SL->getSizeInBytes()) {
2907 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2908 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002909
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002910 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2911 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002912 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002913 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002914
Chris Lattner2192fe52011-07-18 04:24:23 +00002915 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002916 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002917 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002918 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002919 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2920 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002921 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002922
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002923 // Okay, we don't have any better idea of what to pass, so we pass this in an
2924 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002925 unsigned TySizeInBytes =
2926 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002927
Chris Lattner3f763422010-07-29 17:34:39 +00002928 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002929
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002930 // It is always safe to classify this as an integer type up to i64 that
2931 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002932 return llvm::IntegerType::get(getVMContext(),
2933 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002934}
2935
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002936
2937/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2938/// be used as elements of a two register pair to pass or return, return a
2939/// first class aggregate to represent them. For example, if the low part of
2940/// a by-value argument should be passed as i32* and the high part as float,
2941/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002942static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002943GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002944 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002945 // In order to correctly satisfy the ABI, we need to the high part to start
2946 // at offset 8. If the high and low parts we inferred are both 4-byte types
2947 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2948 // the second element at offset 8. Check for this:
2949 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2950 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002951 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002952 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002953
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002954 // To handle this, we have to increase the size of the low part so that the
2955 // second element will start at an 8 byte offset. We can't increase the size
2956 // of the second element because it might make us access off the end of the
2957 // struct.
2958 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002959 // There are usually two sorts of types the ABI generation code can produce
2960 // for the low part of a pair that aren't 8 bytes in size: float or
2961 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2962 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002963 // Promote these to a larger type.
2964 if (Lo->isFloatTy())
2965 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2966 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002967 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2968 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002969 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2970 }
2971 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002972
Reid Kleckneree7cf842014-12-01 22:02:27 +00002973 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002974
2975
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002976 // Verify that the second element is at an 8-byte offset.
2977 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2978 "Invalid x86-64 argument pair!");
2979 return Result;
2980}
2981
Chris Lattner31faff52010-07-28 23:06:14 +00002982ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002983classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002984 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2985 // classification algorithm.
2986 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002987 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002988
2989 // Check some invariants.
2990 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002991 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2992
Craig Topper8a13c412014-05-21 05:09:00 +00002993 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002994 switch (Lo) {
2995 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002996 if (Hi == NoClass)
2997 return ABIArgInfo::getIgnore();
2998 // If the low part is just padding, it takes no register, leave ResType
2999 // null.
3000 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3001 "Unknown missing lo part");
3002 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003003
3004 case SSEUp:
3005 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003006 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003007
3008 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3009 // hidden argument.
3010 case Memory:
3011 return getIndirectReturnResult(RetTy);
3012
3013 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3014 // available register of the sequence %rax, %rdx is used.
3015 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003016 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003017
Chris Lattner1f3a0632010-07-29 21:42:50 +00003018 // If we have a sign or zero extended integer, make sure to return Extend
3019 // so that the parameter gets the right LLVM IR attributes.
3020 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3021 // Treat an enum type as its underlying type.
3022 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3023 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003024
Chris Lattner1f3a0632010-07-29 21:42:50 +00003025 if (RetTy->isIntegralOrEnumerationType() &&
3026 RetTy->isPromotableIntegerType())
3027 return ABIArgInfo::getExtend();
3028 }
Chris Lattner31faff52010-07-28 23:06:14 +00003029 break;
3030
3031 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3032 // available SSE register of the sequence %xmm0, %xmm1 is used.
3033 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003034 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003035 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003036
3037 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3038 // returned on the X87 stack in %st0 as 80-bit x87 number.
3039 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003040 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003041 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003042
3043 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3044 // part of the value is returned in %st0 and the imaginary part in
3045 // %st1.
3046 case ComplexX87:
3047 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003048 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003049 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003050 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003051 break;
3052 }
3053
Craig Topper8a13c412014-05-21 05:09:00 +00003054 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003055 switch (Hi) {
3056 // Memory was handled previously and X87 should
3057 // never occur as a hi class.
3058 case Memory:
3059 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003060 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003061
3062 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003063 case NoClass:
3064 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003065
Chris Lattner52b3c132010-09-01 00:20:33 +00003066 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003067 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003068 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3069 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003070 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003071 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003072 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003073 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3074 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003075 break;
3076
3077 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003078 // is passed in the next available eightbyte chunk if the last used
3079 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003080 //
Chris Lattner57540c52011-04-15 05:22:18 +00003081 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003082 case SSEUp:
3083 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003084 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003085 break;
3086
3087 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3088 // returned together with the previous X87 value in %st0.
3089 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003090 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003091 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003092 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003093 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003094 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003095 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003096 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3097 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003098 }
Chris Lattner31faff52010-07-28 23:06:14 +00003099 break;
3100 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003101
Chris Lattner52b3c132010-09-01 00:20:33 +00003102 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003103 // known to pass in the high eightbyte of the result. We do this by forming a
3104 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003105 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003106 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003107
Chris Lattner1f3a0632010-07-29 21:42:50 +00003108 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003109}
3110
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003111ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003112 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3113 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003114 const
3115{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003116 Ty = useFirstFieldIfTransparentUnion(Ty);
3117
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003118 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003119 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003120
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003121 // Check some invariants.
3122 // FIXME: Enforce these by construction.
3123 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003124 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3125
3126 neededInt = 0;
3127 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003128 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003129 switch (Lo) {
3130 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003131 if (Hi == NoClass)
3132 return ABIArgInfo::getIgnore();
3133 // If the low part is just padding, it takes no register, leave ResType
3134 // null.
3135 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3136 "Unknown missing lo part");
3137 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003138
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003139 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3140 // on the stack.
3141 case Memory:
3142
3143 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3144 // COMPLEX_X87, it is passed in memory.
3145 case X87:
3146 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003147 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003148 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003149 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003150
3151 case SSEUp:
3152 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003153 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003154
3155 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3156 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3157 // and %r9 is used.
3158 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003159 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003160
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003161 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003162 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003163
3164 // If we have a sign or zero extended integer, make sure to return Extend
3165 // so that the parameter gets the right LLVM IR attributes.
3166 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3167 // Treat an enum type as its underlying type.
3168 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3169 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003170
Chris Lattner1f3a0632010-07-29 21:42:50 +00003171 if (Ty->isIntegralOrEnumerationType() &&
3172 Ty->isPromotableIntegerType())
3173 return ABIArgInfo::getExtend();
3174 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003175
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003176 break;
3177
3178 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3179 // available SSE register is used, the registers are taken in the
3180 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003181 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003182 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003183 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003184 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003185 break;
3186 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003187 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003188
Craig Topper8a13c412014-05-21 05:09:00 +00003189 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003190 switch (Hi) {
3191 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003192 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003193 // which is passed in memory.
3194 case Memory:
3195 case X87:
3196 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003197 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003198
3199 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003200
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003201 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003202 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003203 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003204 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003205
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003206 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3207 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003208 break;
3209
3210 // X87Up generally doesn't occur here (long double is passed in
3211 // memory), except in situations involving unions.
3212 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003213 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003214 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003215
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003216 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3217 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003218
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003219 ++neededSSE;
3220 break;
3221
3222 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3223 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003224 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003225 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003226 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003227 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003228 break;
3229 }
3230
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003231 // If a high part was specified, merge it together with the low part. It is
3232 // known to pass in the high eightbyte of the result. We do this by forming a
3233 // first class struct aggregate with the high and low part: {low, high}
3234 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003235 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003236
Chris Lattner1f3a0632010-07-29 21:42:50 +00003237 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003238}
3239
Chris Lattner22326a12010-07-29 02:31:05 +00003240void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003241
Reid Kleckner40ca9132014-05-13 22:05:45 +00003242 if (!getCXXABI().classifyReturnType(FI))
3243 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003244
3245 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003246 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003247
3248 // If the return value is indirect, then the hidden argument is consuming one
3249 // integer register.
3250 if (FI.getReturnInfo().isIndirect())
3251 --freeIntRegs;
3252
Peter Collingbournef7706832014-12-12 23:41:25 +00003253 // The chain argument effectively gives us another free register.
3254 if (FI.isChainCall())
3255 ++freeIntRegs;
3256
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003257 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003258 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3259 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003260 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003261 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003262 it != ie; ++it, ++ArgNo) {
3263 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003264
Bill Wendling9987c0e2010-10-18 23:51:38 +00003265 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003266 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003267 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003268
3269 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3270 // eightbyte of an argument, the whole argument is passed on the
3271 // stack. If registers have already been assigned for some
3272 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003273 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003274 freeIntRegs -= neededInt;
3275 freeSSERegs -= neededSSE;
3276 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003277 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003278 }
3279 }
3280}
3281
John McCall7f416cc2015-09-08 08:05:57 +00003282static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3283 Address VAListAddr, QualType Ty) {
3284 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3285 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003286 llvm::Value *overflow_arg_area =
3287 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3288
3289 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3290 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003291 // It isn't stated explicitly in the standard, but in practice we use
3292 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003293 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3294 if (Align > CharUnits::fromQuantity(8)) {
3295 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3296 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003297 }
3298
3299 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003300 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003301 llvm::Value *Res =
3302 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003303 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003304
3305 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3306 // l->overflow_arg_area + sizeof(type).
3307 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3308 // an 8 byte boundary.
3309
3310 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003311 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003312 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003313 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3314 "overflow_arg_area.next");
3315 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3316
3317 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003318 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003319}
3320
John McCall7f416cc2015-09-08 08:05:57 +00003321Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3322 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003323 // Assume that va_list type is correct; should be pointer to LLVM type:
3324 // struct {
3325 // i32 gp_offset;
3326 // i32 fp_offset;
3327 // i8* overflow_arg_area;
3328 // i8* reg_save_area;
3329 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003330 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003331
John McCall7f416cc2015-09-08 08:05:57 +00003332 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003333 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003334 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003335
3336 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3337 // in the registers. If not go to step 7.
3338 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003339 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003340
3341 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3342 // general purpose registers needed to pass type and num_fp to hold
3343 // the number of floating point registers needed.
3344
3345 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3346 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3347 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3348 //
3349 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3350 // register save space).
3351
Craig Topper8a13c412014-05-21 05:09:00 +00003352 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003353 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3354 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003355 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003356 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003357 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3358 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003359 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003360 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3361 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003362 }
3363
3364 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003365 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003366 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3367 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003368 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3369 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003370 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3371 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003372 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3373 }
3374
3375 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3376 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3377 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3378 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3379
3380 // Emit code to load the value if it was passed in registers.
3381
3382 CGF.EmitBlock(InRegBlock);
3383
3384 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3385 // an offset of l->gp_offset and/or l->fp_offset. This may require
3386 // copying to a temporary location in case the parameter is passed
3387 // in different register classes or requires an alignment greater
3388 // than 8 for general purpose registers and 16 for XMM registers.
3389 //
3390 // FIXME: This really results in shameful code when we end up needing to
3391 // collect arguments from different places; often what should result in a
3392 // simple assembling of a structure from scattered addresses has many more
3393 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003394 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003395 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3396 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3397 "reg_save_area");
3398
3399 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003400 if (neededInt && neededSSE) {
3401 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003402 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003403 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003404 Address Tmp = CGF.CreateMemTemp(Ty);
3405 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003406 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003407 llvm::Type *TyLo = ST->getElementType(0);
3408 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003409 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003410 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003411 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3412 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003413 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3414 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003415 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3416 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003417
John McCall7f416cc2015-09-08 08:05:57 +00003418 // Copy the first element.
3419 llvm::Value *V =
3420 CGF.Builder.CreateDefaultAlignedLoad(
3421 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3422 CGF.Builder.CreateStore(V,
3423 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3424
3425 // Copy the second element.
3426 V = CGF.Builder.CreateDefaultAlignedLoad(
3427 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3428 CharUnits Offset = CharUnits::fromQuantity(
3429 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3430 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3431
3432 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003433 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003434 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3435 CharUnits::fromQuantity(8));
3436 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003437
3438 // Copy to a temporary if necessary to ensure the appropriate alignment.
3439 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003440 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003441 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003442 CharUnits TyAlign = SizeAlign.second;
3443
3444 // Copy into a temporary if the type is more aligned than the
3445 // register save area.
3446 if (TyAlign.getQuantity() > 8) {
3447 Address Tmp = CGF.CreateMemTemp(Ty);
3448 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003449 RegAddr = Tmp;
3450 }
John McCall7f416cc2015-09-08 08:05:57 +00003451
Chris Lattner0cf24192010-06-28 20:05:43 +00003452 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003453 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3454 CharUnits::fromQuantity(16));
3455 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003456 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003457 assert(neededSSE == 2 && "Invalid number of needed registers!");
3458 // SSE registers are spaced 16 bytes apart in the register save
3459 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003460 // The ABI isn't explicit about this, but it seems reasonable
3461 // to assume that the slots are 16-byte aligned, since the stack is
3462 // naturally 16-byte aligned and the prologue is expected to store
3463 // all the SSE registers to the RSA.
3464 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3465 CharUnits::fromQuantity(16));
3466 Address RegAddrHi =
3467 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3468 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003469 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003470 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003471 llvm::Value *V;
3472 Address Tmp = CGF.CreateMemTemp(Ty);
3473 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3474 V = CGF.Builder.CreateLoad(
3475 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3476 CGF.Builder.CreateStore(V,
3477 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3478 V = CGF.Builder.CreateLoad(
3479 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3480 CGF.Builder.CreateStore(V,
3481 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3482
3483 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003484 }
3485
3486 // AMD64-ABI 3.5.7p5: Step 5. Set:
3487 // l->gp_offset = l->gp_offset + num_gp * 8
3488 // l->fp_offset = l->fp_offset + num_fp * 16.
3489 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003490 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003491 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3492 gp_offset_p);
3493 }
3494 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003495 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003496 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3497 fp_offset_p);
3498 }
3499 CGF.EmitBranch(ContBlock);
3500
3501 // Emit code to load the value if it was passed in memory.
3502
3503 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003504 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003505
3506 // Return the appropriate result.
3507
3508 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003509 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3510 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003511 return ResAddr;
3512}
3513
Charles Davisc7d5c942015-09-17 20:55:33 +00003514Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3515 QualType Ty) const {
3516 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3517 CGF.getContext().getTypeInfoInChars(Ty),
3518 CharUnits::fromQuantity(8),
3519 /*allowHigherAlign*/ false);
3520}
3521
Reid Kleckner80944df2014-10-31 22:00:51 +00003522ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3523 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003524
3525 if (Ty->isVoidType())
3526 return ABIArgInfo::getIgnore();
3527
3528 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3529 Ty = EnumTy->getDecl()->getIntegerType();
3530
Reid Kleckner80944df2014-10-31 22:00:51 +00003531 TypeInfo Info = getContext().getTypeInfo(Ty);
3532 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003533 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003534
Reid Kleckner9005f412014-05-02 00:51:20 +00003535 const RecordType *RT = Ty->getAs<RecordType>();
3536 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003537 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003538 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003539 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003540 }
3541
3542 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003543 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003544
Reid Kleckner9005f412014-05-02 00:51:20 +00003545 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003546
Reid Kleckner80944df2014-10-31 22:00:51 +00003547 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3548 // other targets.
3549 const Type *Base = nullptr;
3550 uint64_t NumElts = 0;
3551 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3552 if (FreeSSERegs >= NumElts) {
3553 FreeSSERegs -= NumElts;
3554 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3555 return ABIArgInfo::getDirect();
3556 return ABIArgInfo::getExpand();
3557 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003558 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003559 }
3560
3561
Reid Klecknerec87fec2014-05-02 01:17:12 +00003562 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003563 // If the member pointer is represented by an LLVM int or ptr, pass it
3564 // directly.
3565 llvm::Type *LLTy = CGT.ConvertType(Ty);
3566 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3567 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003568 }
3569
Michael Kuperstein4f818702015-02-24 09:35:58 +00003570 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003571 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3572 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003573 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003574 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003575
Reid Kleckner9005f412014-05-02 00:51:20 +00003576 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003577 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003578 }
3579
Julien Lerouge10dcff82014-08-27 00:36:55 +00003580 // Bool type is always extended to the ABI, other builtin types are not
3581 // extended.
3582 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3583 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003584 return ABIArgInfo::getExtend();
3585
Reid Kleckner11a17192015-10-28 22:29:52 +00003586 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3587 // passes them indirectly through memory.
3588 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3589 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3590 if (LDF == &llvm::APFloat::x87DoubleExtended)
3591 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3592 }
3593
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003594 return ABIArgInfo::getDirect();
3595}
3596
3597void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003598 bool IsVectorCall =
3599 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003600
Reid Kleckner80944df2014-10-31 22:00:51 +00003601 // We can use up to 4 SSE return registers with vectorcall.
3602 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3603 if (!getCXXABI().classifyReturnType(FI))
3604 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3605
3606 // We can use up to 6 SSE register parameters with vectorcall.
3607 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003608 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003609 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003610}
3611
John McCall7f416cc2015-09-08 08:05:57 +00003612Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3613 QualType Ty) const {
3614 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3615 CGF.getContext().getTypeInfoInChars(Ty),
3616 CharUnits::fromQuantity(8),
3617 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003618}
Chris Lattner0cf24192010-06-28 20:05:43 +00003619
John McCallea8d8bb2010-03-11 00:10:12 +00003620// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003621namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003622/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3623class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003624bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003625public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003626 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3627 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003628
John McCall7f416cc2015-09-08 08:05:57 +00003629 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3630 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003631};
3632
3633class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3634public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003635 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3636 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003637
Craig Topper4f12f102014-03-12 06:41:41 +00003638 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003639 // This is recovered from gcc output.
3640 return 1; // r1 is the dedicated stack pointer
3641 }
3642
3643 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003644 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003645};
3646
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003647}
John McCallea8d8bb2010-03-11 00:10:12 +00003648
James Y Knight29b5f082016-02-24 02:59:33 +00003649// TODO: this implementation is now likely redundant with
3650// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003651Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3652 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003653 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003654 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3655 // TODO: Implement this. For now ignore.
3656 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003657 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003658 }
3659
John McCall7f416cc2015-09-08 08:05:57 +00003660 // struct __va_list_tag {
3661 // unsigned char gpr;
3662 // unsigned char fpr;
3663 // unsigned short reserved;
3664 // void *overflow_arg_area;
3665 // void *reg_save_area;
3666 // };
3667
Roman Divacky8a12d842014-11-03 18:32:54 +00003668 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003669 bool isInt =
3670 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003671 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003672
3673 // All aggregates are passed indirectly? That doesn't seem consistent
3674 // with the argument-lowering code.
3675 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003676
3677 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003678
3679 // The calling convention either uses 1-2 GPRs or 1 FPR.
3680 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003681 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003682 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3683 } else {
3684 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003685 }
John McCall7f416cc2015-09-08 08:05:57 +00003686
3687 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3688
3689 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003690 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003691 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3692 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3693 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003694
Eric Christopher7565e0d2015-05-29 23:09:49 +00003695 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003696 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003697
3698 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3699 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3700 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3701
3702 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3703
John McCall7f416cc2015-09-08 08:05:57 +00003704 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3705 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003706
John McCall7f416cc2015-09-08 08:05:57 +00003707 // Case 1: consume registers.
3708 Address RegAddr = Address::invalid();
3709 {
3710 CGF.EmitBlock(UsingRegs);
3711
3712 Address RegSaveAreaPtr =
3713 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3714 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3715 CharUnits::fromQuantity(8));
3716 assert(RegAddr.getElementType() == CGF.Int8Ty);
3717
3718 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003719 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003720 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3721 CharUnits::fromQuantity(32));
3722 }
3723
3724 // Get the address of the saved value by scaling the number of
3725 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003726 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003727 llvm::Value *RegOffset =
3728 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3729 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3730 RegAddr.getPointer(), RegOffset),
3731 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3732 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3733
3734 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003735 NumRegs =
3736 Builder.CreateAdd(NumRegs,
3737 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003738 Builder.CreateStore(NumRegs, NumRegsAddr);
3739
3740 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003741 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003742
John McCall7f416cc2015-09-08 08:05:57 +00003743 // Case 2: consume space in the overflow area.
3744 Address MemAddr = Address::invalid();
3745 {
3746 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003747
Roman Divacky039b9702016-02-20 08:31:24 +00003748 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3749
John McCall7f416cc2015-09-08 08:05:57 +00003750 // Everything in the overflow area is rounded up to a size of at least 4.
3751 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3752
3753 CharUnits Size;
3754 if (!isIndirect) {
3755 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003756 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003757 } else {
3758 Size = CGF.getPointerSize();
3759 }
3760
3761 Address OverflowAreaAddr =
3762 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003763 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003764 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003765 // Round up address of argument to alignment
3766 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3767 if (Align > OverflowAreaAlign) {
3768 llvm::Value *Ptr = OverflowArea.getPointer();
3769 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3770 Align);
3771 }
3772
John McCall7f416cc2015-09-08 08:05:57 +00003773 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3774
3775 // Increase the overflow area.
3776 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3777 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3778 CGF.EmitBranch(Cont);
3779 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003780
3781 CGF.EmitBlock(Cont);
3782
John McCall7f416cc2015-09-08 08:05:57 +00003783 // Merge the cases with a phi.
3784 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3785 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003786
John McCall7f416cc2015-09-08 08:05:57 +00003787 // Load the pointer if the argument was passed indirectly.
3788 if (isIndirect) {
3789 Result = Address(Builder.CreateLoad(Result, "aggr"),
3790 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003791 }
3792
3793 return Result;
3794}
3795
John McCallea8d8bb2010-03-11 00:10:12 +00003796bool
3797PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3798 llvm::Value *Address) const {
3799 // This is calculated from the LLVM and GCC tables and verified
3800 // against gcc output. AFAIK all ABIs use the same encoding.
3801
3802 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003803
Chris Lattnerece04092012-02-07 00:39:47 +00003804 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003805 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3806 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3807 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3808
3809 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003810 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003811
3812 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003813 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003814
3815 // 64-76 are various 4-byte special-purpose registers:
3816 // 64: mq
3817 // 65: lr
3818 // 66: ctr
3819 // 67: ap
3820 // 68-75 cr0-7
3821 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003822 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003823
3824 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003825 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003826
3827 // 109: vrsave
3828 // 110: vscr
3829 // 111: spe_acc
3830 // 112: spefscr
3831 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003832 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003833
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003834 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003835}
3836
Roman Divackyd966e722012-05-09 18:22:46 +00003837// PowerPC-64
3838
3839namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003840/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00003841class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003842public:
3843 enum ABIKind {
3844 ELFv1 = 0,
3845 ELFv2
3846 };
3847
3848private:
3849 static const unsigned GPRBits = 64;
3850 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003851 bool HasQPX;
3852
3853 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3854 // will be passed in a QPX register.
3855 bool IsQPXVectorTy(const Type *Ty) const {
3856 if (!HasQPX)
3857 return false;
3858
3859 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3860 unsigned NumElements = VT->getNumElements();
3861 if (NumElements == 1)
3862 return false;
3863
3864 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3865 if (getContext().getTypeSize(Ty) <= 256)
3866 return true;
3867 } else if (VT->getElementType()->
3868 isSpecificBuiltinType(BuiltinType::Float)) {
3869 if (getContext().getTypeSize(Ty) <= 128)
3870 return true;
3871 }
3872 }
3873
3874 return false;
3875 }
3876
3877 bool IsQPXVectorTy(QualType Ty) const {
3878 return IsQPXVectorTy(Ty.getTypePtr());
3879 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003880
3881public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003882 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
James Y Knight29b5f082016-02-24 02:59:33 +00003883 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003884
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003885 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003886 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003887
3888 ABIArgInfo classifyReturnType(QualType RetTy) const;
3889 ABIArgInfo classifyArgumentType(QualType Ty) const;
3890
Reid Klecknere9f6a712014-10-31 17:10:41 +00003891 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3892 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3893 uint64_t Members) const override;
3894
Bill Schmidt84d37792012-10-12 19:26:17 +00003895 // TODO: We can add more logic to computeInfo to improve performance.
3896 // Example: For aggregate arguments that fit in a register, we could
3897 // use getDirectInReg (as is done below for structs containing a single
3898 // floating-point value) to avoid pushing them to memory on function
3899 // entry. This would require changing the logic in PPCISelLowering
3900 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003901 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003902 if (!getCXXABI().classifyReturnType(FI))
3903 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003904 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003905 // We rely on the default argument classification for the most part.
3906 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003907 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003908 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003909 if (T) {
3910 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003911 if (IsQPXVectorTy(T) ||
3912 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003913 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003914 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003915 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003916 continue;
3917 }
3918 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003919 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003920 }
3921 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003922
John McCall7f416cc2015-09-08 08:05:57 +00003923 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3924 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003925};
3926
3927class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003928
Bill Schmidt25cb3492012-10-03 19:18:57 +00003929public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003930 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003931 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003932 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003933
Craig Topper4f12f102014-03-12 06:41:41 +00003934 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003935 // This is recovered from gcc output.
3936 return 1; // r1 is the dedicated stack pointer
3937 }
3938
3939 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003940 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003941};
3942
Roman Divackyd966e722012-05-09 18:22:46 +00003943class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3944public:
3945 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3946
Craig Topper4f12f102014-03-12 06:41:41 +00003947 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003948 // This is recovered from gcc output.
3949 return 1; // r1 is the dedicated stack pointer
3950 }
3951
3952 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003953 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003954};
3955
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003956}
Roman Divackyd966e722012-05-09 18:22:46 +00003957
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003958// Return true if the ABI requires Ty to be passed sign- or zero-
3959// extended to 64 bits.
3960bool
3961PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3962 // Treat an enum type as its underlying type.
3963 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3964 Ty = EnumTy->getDecl()->getIntegerType();
3965
3966 // Promotable integer types are required to be promoted by the ABI.
3967 if (Ty->isPromotableIntegerType())
3968 return true;
3969
3970 // In addition to the usual promotable integer types, we also need to
3971 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3972 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3973 switch (BT->getKind()) {
3974 case BuiltinType::Int:
3975 case BuiltinType::UInt:
3976 return true;
3977 default:
3978 break;
3979 }
3980
3981 return false;
3982}
3983
John McCall7f416cc2015-09-08 08:05:57 +00003984/// isAlignedParamType - Determine whether a type requires 16-byte or
3985/// higher alignment in the parameter area. Always returns at least 8.
3986CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003987 // Complex types are passed just like their elements.
3988 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3989 Ty = CTy->getElementType();
3990
3991 // Only vector types of size 16 bytes need alignment (larger types are
3992 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003993 if (IsQPXVectorTy(Ty)) {
3994 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003995 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003996
John McCall7f416cc2015-09-08 08:05:57 +00003997 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003998 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00003999 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004000 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004001
4002 // For single-element float/vector structs, we consider the whole type
4003 // to have the same alignment requirements as its single element.
4004 const Type *AlignAsType = nullptr;
4005 const Type *EltType = isSingleElementStruct(Ty, getContext());
4006 if (EltType) {
4007 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004008 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004009 getContext().getTypeSize(EltType) == 128) ||
4010 (BT && BT->isFloatingPoint()))
4011 AlignAsType = EltType;
4012 }
4013
Ulrich Weigandb7122372014-07-21 00:48:09 +00004014 // Likewise for ELFv2 homogeneous aggregates.
4015 const Type *Base = nullptr;
4016 uint64_t Members = 0;
4017 if (!AlignAsType && Kind == ELFv2 &&
4018 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4019 AlignAsType = Base;
4020
Ulrich Weigand581badc2014-07-10 17:20:07 +00004021 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004022 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4023 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004024 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004025
John McCall7f416cc2015-09-08 08:05:57 +00004026 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004027 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004028 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004029 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004030
4031 // Otherwise, we only need alignment for any aggregate type that
4032 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004033 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4034 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004035 return CharUnits::fromQuantity(32);
4036 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004037 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004038
John McCall7f416cc2015-09-08 08:05:57 +00004039 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004040}
4041
Ulrich Weigandb7122372014-07-21 00:48:09 +00004042/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4043/// aggregate. Base is set to the base element type, and Members is set
4044/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004045bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4046 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004047 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4048 uint64_t NElements = AT->getSize().getZExtValue();
4049 if (NElements == 0)
4050 return false;
4051 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4052 return false;
4053 Members *= NElements;
4054 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4055 const RecordDecl *RD = RT->getDecl();
4056 if (RD->hasFlexibleArrayMember())
4057 return false;
4058
4059 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004060
4061 // If this is a C++ record, check the bases first.
4062 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4063 for (const auto &I : CXXRD->bases()) {
4064 // Ignore empty records.
4065 if (isEmptyRecord(getContext(), I.getType(), true))
4066 continue;
4067
4068 uint64_t FldMembers;
4069 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4070 return false;
4071
4072 Members += FldMembers;
4073 }
4074 }
4075
Ulrich Weigandb7122372014-07-21 00:48:09 +00004076 for (const auto *FD : RD->fields()) {
4077 // Ignore (non-zero arrays of) empty records.
4078 QualType FT = FD->getType();
4079 while (const ConstantArrayType *AT =
4080 getContext().getAsConstantArrayType(FT)) {
4081 if (AT->getSize().getZExtValue() == 0)
4082 return false;
4083 FT = AT->getElementType();
4084 }
4085 if (isEmptyRecord(getContext(), FT, true))
4086 continue;
4087
4088 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4089 if (getContext().getLangOpts().CPlusPlus &&
4090 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4091 continue;
4092
4093 uint64_t FldMembers;
4094 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4095 return false;
4096
4097 Members = (RD->isUnion() ?
4098 std::max(Members, FldMembers) : Members + FldMembers);
4099 }
4100
4101 if (!Base)
4102 return false;
4103
4104 // Ensure there is no padding.
4105 if (getContext().getTypeSize(Base) * Members !=
4106 getContext().getTypeSize(Ty))
4107 return false;
4108 } else {
4109 Members = 1;
4110 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4111 Members = 2;
4112 Ty = CT->getElementType();
4113 }
4114
Reid Klecknere9f6a712014-10-31 17:10:41 +00004115 // Most ABIs only support float, double, and some vector type widths.
4116 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004117 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004118
4119 // The base type must be the same for all members. Types that
4120 // agree in both total size and mode (float vs. vector) are
4121 // treated as being equivalent here.
4122 const Type *TyPtr = Ty.getTypePtr();
4123 if (!Base)
4124 Base = TyPtr;
4125
4126 if (Base->isVectorType() != TyPtr->isVectorType() ||
4127 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4128 return false;
4129 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004130 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4131}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004132
Reid Klecknere9f6a712014-10-31 17:10:41 +00004133bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4134 // Homogeneous aggregates for ELFv2 must have base types of float,
4135 // double, long double, or 128-bit vectors.
4136 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4137 if (BT->getKind() == BuiltinType::Float ||
4138 BT->getKind() == BuiltinType::Double ||
4139 BT->getKind() == BuiltinType::LongDouble)
4140 return true;
4141 }
4142 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004143 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004144 return true;
4145 }
4146 return false;
4147}
4148
4149bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4150 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004151 // Vector types require one register, floating point types require one
4152 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004153 uint32_t NumRegs =
4154 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004155
4156 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004157 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004158}
4159
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004160ABIArgInfo
4161PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004162 Ty = useFirstFieldIfTransparentUnion(Ty);
4163
Bill Schmidt90b22c92012-11-27 02:46:43 +00004164 if (Ty->isAnyComplexType())
4165 return ABIArgInfo::getDirect();
4166
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004167 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4168 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004169 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004170 uint64_t Size = getContext().getTypeSize(Ty);
4171 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004172 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004173 else if (Size < 128) {
4174 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4175 return ABIArgInfo::getDirect(CoerceTy);
4176 }
4177 }
4178
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004179 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004180 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004181 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004182
John McCall7f416cc2015-09-08 08:05:57 +00004183 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4184 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004185
4186 // ELFv2 homogeneous aggregates are passed as array types.
4187 const Type *Base = nullptr;
4188 uint64_t Members = 0;
4189 if (Kind == ELFv2 &&
4190 isHomogeneousAggregate(Ty, Base, Members)) {
4191 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4192 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4193 return ABIArgInfo::getDirect(CoerceTy);
4194 }
4195
Ulrich Weigand601957f2014-07-21 00:56:36 +00004196 // If an aggregate may end up fully in registers, we do not
4197 // use the ByVal method, but pass the aggregate as array.
4198 // This is usually beneficial since we avoid forcing the
4199 // back-end to store the argument to memory.
4200 uint64_t Bits = getContext().getTypeSize(Ty);
4201 if (Bits > 0 && Bits <= 8 * GPRBits) {
4202 llvm::Type *CoerceTy;
4203
4204 // Types up to 8 bytes are passed as integer type (which will be
4205 // properly aligned in the argument save area doubleword).
4206 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004207 CoerceTy =
4208 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004209 // Larger types are passed as arrays, with the base type selected
4210 // according to the required alignment in the save area.
4211 else {
4212 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004213 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004214 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4215 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4216 }
4217
4218 return ABIArgInfo::getDirect(CoerceTy);
4219 }
4220
Ulrich Weigandb7122372014-07-21 00:48:09 +00004221 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004222 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4223 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004224 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004225 }
4226
4227 return (isPromotableTypeForABI(Ty) ?
4228 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4229}
4230
4231ABIArgInfo
4232PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4233 if (RetTy->isVoidType())
4234 return ABIArgInfo::getIgnore();
4235
Bill Schmidta3d121c2012-12-17 04:20:17 +00004236 if (RetTy->isAnyComplexType())
4237 return ABIArgInfo::getDirect();
4238
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004239 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4240 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004241 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004242 uint64_t Size = getContext().getTypeSize(RetTy);
4243 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004244 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004245 else if (Size < 128) {
4246 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4247 return ABIArgInfo::getDirect(CoerceTy);
4248 }
4249 }
4250
Ulrich Weigandb7122372014-07-21 00:48:09 +00004251 if (isAggregateTypeForABI(RetTy)) {
4252 // ELFv2 homogeneous aggregates are returned as array types.
4253 const Type *Base = nullptr;
4254 uint64_t Members = 0;
4255 if (Kind == ELFv2 &&
4256 isHomogeneousAggregate(RetTy, Base, Members)) {
4257 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4258 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4259 return ABIArgInfo::getDirect(CoerceTy);
4260 }
4261
4262 // ELFv2 small aggregates are returned in up to two registers.
4263 uint64_t Bits = getContext().getTypeSize(RetTy);
4264 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4265 if (Bits == 0)
4266 return ABIArgInfo::getIgnore();
4267
4268 llvm::Type *CoerceTy;
4269 if (Bits > GPRBits) {
4270 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004271 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004272 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004273 CoerceTy =
4274 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004275 return ABIArgInfo::getDirect(CoerceTy);
4276 }
4277
4278 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004279 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004280 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004281
4282 return (isPromotableTypeForABI(RetTy) ?
4283 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4284}
4285
Bill Schmidt25cb3492012-10-03 19:18:57 +00004286// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004287Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4288 QualType Ty) const {
4289 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4290 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004291
John McCall7f416cc2015-09-08 08:05:57 +00004292 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004293
Bill Schmidt924c4782013-01-14 17:45:36 +00004294 // If we have a complex type and the base type is smaller than 8 bytes,
4295 // the ABI calls for the real and imaginary parts to be right-adjusted
4296 // in separate doublewords. However, Clang expects us to produce a
4297 // pointer to a structure with the two parts packed tightly. So generate
4298 // loads of the real and imaginary parts relative to the va_list pointer,
4299 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004300 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4301 CharUnits EltSize = TypeInfo.first / 2;
4302 if (EltSize < SlotSize) {
4303 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4304 SlotSize * 2, SlotSize,
4305 SlotSize, /*AllowHigher*/ true);
4306
4307 Address RealAddr = Addr;
4308 Address ImagAddr = RealAddr;
4309 if (CGF.CGM.getDataLayout().isBigEndian()) {
4310 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4311 SlotSize - EltSize);
4312 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4313 2 * SlotSize - EltSize);
4314 } else {
4315 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4316 }
4317
4318 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4319 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4320 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4321 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4322 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4323
4324 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4325 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4326 /*init*/ true);
4327 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004328 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004329 }
4330
John McCall7f416cc2015-09-08 08:05:57 +00004331 // Otherwise, just use the general rule.
4332 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4333 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004334}
4335
4336static bool
4337PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4338 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004339 // This is calculated from the LLVM and GCC tables and verified
4340 // against gcc output. AFAIK all ABIs use the same encoding.
4341
4342 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4343
4344 llvm::IntegerType *i8 = CGF.Int8Ty;
4345 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4346 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4347 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4348
4349 // 0-31: r0-31, the 8-byte general-purpose registers
4350 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4351
4352 // 32-63: fp0-31, the 8-byte floating-point registers
4353 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4354
4355 // 64-76 are various 4-byte special-purpose registers:
4356 // 64: mq
4357 // 65: lr
4358 // 66: ctr
4359 // 67: ap
4360 // 68-75 cr0-7
4361 // 76: xer
4362 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4363
4364 // 77-108: v0-31, the 16-byte vector registers
4365 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4366
4367 // 109: vrsave
4368 // 110: vscr
4369 // 111: spe_acc
4370 // 112: spefscr
4371 // 113: sfp
4372 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4373
4374 return false;
4375}
John McCallea8d8bb2010-03-11 00:10:12 +00004376
Bill Schmidt25cb3492012-10-03 19:18:57 +00004377bool
4378PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4379 CodeGen::CodeGenFunction &CGF,
4380 llvm::Value *Address) const {
4381
4382 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4383}
4384
4385bool
4386PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4387 llvm::Value *Address) const {
4388
4389 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4390}
4391
Chris Lattner0cf24192010-06-28 20:05:43 +00004392//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004393// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004394//===----------------------------------------------------------------------===//
4395
4396namespace {
4397
John McCall12f23522016-04-04 18:33:08 +00004398class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004399public:
4400 enum ABIKind {
4401 AAPCS = 0,
4402 DarwinPCS
4403 };
4404
4405private:
4406 ABIKind Kind;
4407
4408public:
John McCall12f23522016-04-04 18:33:08 +00004409 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4410 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004411
4412private:
4413 ABIKind getABIKind() const { return Kind; }
4414 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4415
4416 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004417 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004418 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4419 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4420 uint64_t Members) const override;
4421
Tim Northovera2ee4332014-03-29 15:09:45 +00004422 bool isIllegalVectorType(QualType Ty) const;
4423
David Blaikie1cbb9712014-11-14 19:09:44 +00004424 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004425 if (!getCXXABI().classifyReturnType(FI))
4426 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004427
Tim Northoverb047bfa2014-11-27 21:02:49 +00004428 for (auto &it : FI.arguments())
4429 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004430 }
4431
John McCall7f416cc2015-09-08 08:05:57 +00004432 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4433 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004434
John McCall7f416cc2015-09-08 08:05:57 +00004435 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4436 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004437
John McCall7f416cc2015-09-08 08:05:57 +00004438 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4439 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004440 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4441 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4442 }
John McCall12f23522016-04-04 18:33:08 +00004443
4444 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4445 ArrayRef<llvm::Type*> scalars,
4446 bool asReturnValue) const override {
4447 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4448 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004449};
4450
Tim Northover573cbee2014-05-24 12:52:07 +00004451class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004452public:
Tim Northover573cbee2014-05-24 12:52:07 +00004453 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4454 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004455
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004456 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004457 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4458 }
4459
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004460 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4461 return 31;
4462 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004463
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004464 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004465};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004466}
Tim Northovera2ee4332014-03-29 15:09:45 +00004467
Tim Northoverb047bfa2014-11-27 21:02:49 +00004468ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004469 Ty = useFirstFieldIfTransparentUnion(Ty);
4470
Tim Northovera2ee4332014-03-29 15:09:45 +00004471 // Handle illegal vector types here.
4472 if (isIllegalVectorType(Ty)) {
4473 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004474 // Android promotes <2 x i8> to i16, not i32
4475 if(isAndroid() && (Size <= 16)) {
4476 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4477 return ABIArgInfo::getDirect(ResType);
4478 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004479 if (Size <= 32) {
4480 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004481 return ABIArgInfo::getDirect(ResType);
4482 }
4483 if (Size == 64) {
4484 llvm::Type *ResType =
4485 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004486 return ABIArgInfo::getDirect(ResType);
4487 }
4488 if (Size == 128) {
4489 llvm::Type *ResType =
4490 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004491 return ABIArgInfo::getDirect(ResType);
4492 }
John McCall7f416cc2015-09-08 08:05:57 +00004493 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004494 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004495
4496 if (!isAggregateTypeForABI(Ty)) {
4497 // Treat an enum type as its underlying type.
4498 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4499 Ty = EnumTy->getDecl()->getIntegerType();
4500
Tim Northovera2ee4332014-03-29 15:09:45 +00004501 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4502 ? ABIArgInfo::getExtend()
4503 : ABIArgInfo::getDirect());
4504 }
4505
4506 // Structures with either a non-trivial destructor or a non-trivial
4507 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004508 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004509 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4510 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004511 }
4512
4513 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4514 // elsewhere for GNU compatibility.
4515 if (isEmptyRecord(getContext(), Ty, true)) {
4516 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4517 return ABIArgInfo::getIgnore();
4518
Tim Northovera2ee4332014-03-29 15:09:45 +00004519 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4520 }
4521
4522 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004523 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004524 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004525 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004526 return ABIArgInfo::getDirect(
4527 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004528 }
4529
4530 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4531 uint64_t Size = getContext().getTypeSize(Ty);
4532 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004533 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004534 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004535
Tim Northovera2ee4332014-03-29 15:09:45 +00004536 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4537 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004538 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004539 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4540 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4541 }
4542 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4543 }
4544
John McCall7f416cc2015-09-08 08:05:57 +00004545 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004546}
4547
Tim Northover573cbee2014-05-24 12:52:07 +00004548ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004549 if (RetTy->isVoidType())
4550 return ABIArgInfo::getIgnore();
4551
4552 // Large vector types should be returned via memory.
4553 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004554 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004555
4556 if (!isAggregateTypeForABI(RetTy)) {
4557 // Treat an enum type as its underlying type.
4558 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4559 RetTy = EnumTy->getDecl()->getIntegerType();
4560
Tim Northover4dab6982014-04-18 13:46:08 +00004561 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4562 ? ABIArgInfo::getExtend()
4563 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004564 }
4565
Tim Northovera2ee4332014-03-29 15:09:45 +00004566 if (isEmptyRecord(getContext(), RetTy, true))
4567 return ABIArgInfo::getIgnore();
4568
Craig Topper8a13c412014-05-21 05:09:00 +00004569 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004570 uint64_t Members = 0;
4571 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004572 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4573 return ABIArgInfo::getDirect();
4574
4575 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4576 uint64_t Size = getContext().getTypeSize(RetTy);
4577 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004578 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004579 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004580
4581 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4582 // For aggregates with 16-byte alignment, we use i128.
4583 if (Alignment < 128 && Size == 128) {
4584 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4585 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4586 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004587 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4588 }
4589
John McCall7f416cc2015-09-08 08:05:57 +00004590 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004591}
4592
Tim Northover573cbee2014-05-24 12:52:07 +00004593/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4594bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004595 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4596 // Check whether VT is legal.
4597 unsigned NumElements = VT->getNumElements();
4598 uint64_t Size = getContext().getTypeSize(VT);
4599 // NumElements should be power of 2 between 1 and 16.
4600 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4601 return true;
4602 return Size != 64 && (Size != 128 || NumElements == 1);
4603 }
4604 return false;
4605}
4606
Reid Klecknere9f6a712014-10-31 17:10:41 +00004607bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4608 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4609 // point type or a short-vector type. This is the same as the 32-bit ABI,
4610 // but with the difference that any floating-point type is allowed,
4611 // including __fp16.
4612 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4613 if (BT->isFloatingPoint())
4614 return true;
4615 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4616 unsigned VecSize = getContext().getTypeSize(VT);
4617 if (VecSize == 64 || VecSize == 128)
4618 return true;
4619 }
4620 return false;
4621}
4622
4623bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4624 uint64_t Members) const {
4625 return Members <= 4;
4626}
4627
John McCall7f416cc2015-09-08 08:05:57 +00004628Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004629 QualType Ty,
4630 CodeGenFunction &CGF) const {
4631 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004632 bool IsIndirect = AI.isIndirect();
4633
Tim Northoverb047bfa2014-11-27 21:02:49 +00004634 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4635 if (IsIndirect)
4636 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4637 else if (AI.getCoerceToType())
4638 BaseTy = AI.getCoerceToType();
4639
4640 unsigned NumRegs = 1;
4641 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4642 BaseTy = ArrTy->getElementType();
4643 NumRegs = ArrTy->getNumElements();
4644 }
4645 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4646
Tim Northovera2ee4332014-03-29 15:09:45 +00004647 // The AArch64 va_list type and handling is specified in the Procedure Call
4648 // Standard, section B.4:
4649 //
4650 // struct {
4651 // void *__stack;
4652 // void *__gr_top;
4653 // void *__vr_top;
4654 // int __gr_offs;
4655 // int __vr_offs;
4656 // };
4657
4658 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4659 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4660 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4661 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004662
John McCall7f416cc2015-09-08 08:05:57 +00004663 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4664 CharUnits TyAlign = TyInfo.second;
4665
4666 Address reg_offs_p = Address::invalid();
4667 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004668 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004669 CharUnits reg_top_offset;
4670 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004671 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004672 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004673 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004674 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4675 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004676 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4677 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004678 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004679 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004680 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004681 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004682 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004683 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4684 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004685 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4686 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004687 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004688 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004689 }
4690
4691 //=======================================
4692 // Find out where argument was passed
4693 //=======================================
4694
4695 // If reg_offs >= 0 we're already using the stack for this type of
4696 // argument. We don't want to keep updating reg_offs (in case it overflows,
4697 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4698 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004699 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004700 UsingStack = CGF.Builder.CreateICmpSGE(
4701 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4702
4703 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4704
4705 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004706 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004707 CGF.EmitBlock(MaybeRegBlock);
4708
4709 // Integer arguments may need to correct register alignment (for example a
4710 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4711 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004712 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4713 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004714
4715 reg_offs = CGF.Builder.CreateAdd(
4716 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4717 "align_regoffs");
4718 reg_offs = CGF.Builder.CreateAnd(
4719 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4720 "aligned_regoffs");
4721 }
4722
4723 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004724 // The fact that this is done unconditionally reflects the fact that
4725 // allocating an argument to the stack also uses up all the remaining
4726 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004727 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004728 NewOffset = CGF.Builder.CreateAdd(
4729 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4730 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4731
4732 // Now we're in a position to decide whether this argument really was in
4733 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004734 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004735 InRegs = CGF.Builder.CreateICmpSLE(
4736 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4737
4738 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4739
4740 //=======================================
4741 // Argument was in registers
4742 //=======================================
4743
4744 // Now we emit the code for if the argument was originally passed in
4745 // registers. First start the appropriate block:
4746 CGF.EmitBlock(InRegBlock);
4747
John McCall7f416cc2015-09-08 08:05:57 +00004748 llvm::Value *reg_top = nullptr;
4749 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4750 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004751 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004752 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4753 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4754 Address RegAddr = Address::invalid();
4755 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004756
4757 if (IsIndirect) {
4758 // If it's been passed indirectly (actually a struct), whatever we find from
4759 // stored registers or on the stack will actually be a struct **.
4760 MemTy = llvm::PointerType::getUnqual(MemTy);
4761 }
4762
Craig Topper8a13c412014-05-21 05:09:00 +00004763 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004764 uint64_t NumMembers = 0;
4765 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004766 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004767 // Homogeneous aggregates passed in registers will have their elements split
4768 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4769 // qN+1, ...). We reload and store into a temporary local variable
4770 // contiguously.
4771 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004772 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004773 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4774 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004775 Address Tmp = CGF.CreateTempAlloca(HFATy,
4776 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004777
John McCall7f416cc2015-09-08 08:05:57 +00004778 // On big-endian platforms, the value will be right-aligned in its slot.
4779 int Offset = 0;
4780 if (CGF.CGM.getDataLayout().isBigEndian() &&
4781 BaseTyInfo.first.getQuantity() < 16)
4782 Offset = 16 - BaseTyInfo.first.getQuantity();
4783
Tim Northovera2ee4332014-03-29 15:09:45 +00004784 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004785 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4786 Address LoadAddr =
4787 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4788 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4789
4790 Address StoreAddr =
4791 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004792
4793 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4794 CGF.Builder.CreateStore(Elem, StoreAddr);
4795 }
4796
John McCall7f416cc2015-09-08 08:05:57 +00004797 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004798 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004799 // Otherwise the object is contiguous in memory.
4800
4801 // It might be right-aligned in its slot.
4802 CharUnits SlotSize = BaseAddr.getAlignment();
4803 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004804 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004805 TyInfo.first < SlotSize) {
4806 CharUnits Offset = SlotSize - TyInfo.first;
4807 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004808 }
4809
John McCall7f416cc2015-09-08 08:05:57 +00004810 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004811 }
4812
4813 CGF.EmitBranch(ContBlock);
4814
4815 //=======================================
4816 // Argument was on the stack
4817 //=======================================
4818 CGF.EmitBlock(OnStackBlock);
4819
John McCall7f416cc2015-09-08 08:05:57 +00004820 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4821 CharUnits::Zero(), "stack_p");
4822 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004823
John McCall7f416cc2015-09-08 08:05:57 +00004824 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004825 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004826 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4827 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004828
John McCall7f416cc2015-09-08 08:05:57 +00004829 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004830
John McCall7f416cc2015-09-08 08:05:57 +00004831 OnStackPtr = CGF.Builder.CreateAdd(
4832 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004833 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004834 OnStackPtr = CGF.Builder.CreateAnd(
4835 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004836 "align_stack");
4837
John McCall7f416cc2015-09-08 08:05:57 +00004838 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004839 }
John McCall7f416cc2015-09-08 08:05:57 +00004840 Address OnStackAddr(OnStackPtr,
4841 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004842
John McCall7f416cc2015-09-08 08:05:57 +00004843 // All stack slots are multiples of 8 bytes.
4844 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4845 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004846 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004847 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004848 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004849 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004850
John McCall7f416cc2015-09-08 08:05:57 +00004851 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004852 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004853 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004854
4855 // Write the new value of __stack for the next call to va_arg
4856 CGF.Builder.CreateStore(NewStack, stack_p);
4857
4858 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004859 TyInfo.first < StackSlotSize) {
4860 CharUnits Offset = StackSlotSize - TyInfo.first;
4861 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004862 }
4863
John McCall7f416cc2015-09-08 08:05:57 +00004864 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004865
4866 CGF.EmitBranch(ContBlock);
4867
4868 //=======================================
4869 // Tidy up
4870 //=======================================
4871 CGF.EmitBlock(ContBlock);
4872
John McCall7f416cc2015-09-08 08:05:57 +00004873 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4874 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004875
4876 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004877 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4878 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004879
4880 return ResAddr;
4881}
4882
John McCall7f416cc2015-09-08 08:05:57 +00004883Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4884 CodeGenFunction &CGF) const {
4885 // The backend's lowering doesn't support va_arg for aggregates or
4886 // illegal vector types. Lower VAArg here for these cases and use
4887 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004888 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00004889 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004890
John McCall7f416cc2015-09-08 08:05:57 +00004891 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004892
John McCall7f416cc2015-09-08 08:05:57 +00004893 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004894 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004895 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4896 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4897 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004898 }
4899
John McCall7f416cc2015-09-08 08:05:57 +00004900 // The size of the actual thing passed, which might end up just
4901 // being a pointer for indirect types.
4902 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4903
4904 // Arguments bigger than 16 bytes which aren't homogeneous
4905 // aggregates should be passed indirectly.
4906 bool IsIndirect = false;
4907 if (TyInfo.first.getQuantity() > 16) {
4908 const Type *Base = nullptr;
4909 uint64_t Members = 0;
4910 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004911 }
4912
John McCall7f416cc2015-09-08 08:05:57 +00004913 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4914 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004915}
4916
4917//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004918// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004919//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004920
4921namespace {
4922
John McCall12f23522016-04-04 18:33:08 +00004923class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004924public:
4925 enum ABIKind {
4926 APCS = 0,
4927 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004928 AAPCS_VFP = 2,
4929 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004930 };
4931
4932private:
4933 ABIKind Kind;
4934
4935public:
John McCall12f23522016-04-04 18:33:08 +00004936 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
4937 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004938 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004939 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004940
John McCall3480ef22011-08-30 01:42:09 +00004941 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004942 switch (getTarget().getTriple().getEnvironment()) {
4943 case llvm::Triple::Android:
4944 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004945 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004946 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004947 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004948 return true;
4949 default:
4950 return false;
4951 }
John McCall3480ef22011-08-30 01:42:09 +00004952 }
4953
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004954 bool isEABIHF() const {
4955 switch (getTarget().getTriple().getEnvironment()) {
4956 case llvm::Triple::EABIHF:
4957 case llvm::Triple::GNUEABIHF:
4958 return true;
4959 default:
4960 return false;
4961 }
4962 }
4963
Daniel Dunbar020daa92009-09-12 01:00:39 +00004964 ABIKind getABIKind() const { return Kind; }
4965
Tim Northovera484bc02013-10-01 14:34:25 +00004966private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004967 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004968 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004969 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004970
Reid Klecknere9f6a712014-10-31 17:10:41 +00004971 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4972 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4973 uint64_t Members) const override;
4974
Craig Topper4f12f102014-03-12 06:41:41 +00004975 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004976
John McCall7f416cc2015-09-08 08:05:57 +00004977 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4978 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004979
4980 llvm::CallingConv::ID getLLVMDefaultCC() const;
4981 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004982 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00004983
4984 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4985 ArrayRef<llvm::Type*> scalars,
4986 bool asReturnValue) const override {
4987 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4988 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004989};
4990
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004991class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4992public:
Chris Lattner2b037972010-07-29 02:01:43 +00004993 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4994 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004995
John McCall3480ef22011-08-30 01:42:09 +00004996 const ARMABIInfo &getABIInfo() const {
4997 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4998 }
4999
Craig Topper4f12f102014-03-12 06:41:41 +00005000 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005001 return 13;
5002 }
Roman Divackyc1617352011-05-18 19:36:54 +00005003
Craig Topper4f12f102014-03-12 06:41:41 +00005004 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005005 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5006 }
5007
Roman Divackyc1617352011-05-18 19:36:54 +00005008 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005009 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005010 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005011
5012 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005013 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005014 return false;
5015 }
John McCall3480ef22011-08-30 01:42:09 +00005016
Craig Topper4f12f102014-03-12 06:41:41 +00005017 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005018 if (getABIInfo().isEABI()) return 88;
5019 return TargetCodeGenInfo::getSizeOfUnwindException();
5020 }
Tim Northovera484bc02013-10-01 14:34:25 +00005021
Eric Christopher162c91c2015-06-05 22:03:00 +00005022 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005023 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005024 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005025 if (!FD)
5026 return;
5027
5028 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5029 if (!Attr)
5030 return;
5031
5032 const char *Kind;
5033 switch (Attr->getInterrupt()) {
5034 case ARMInterruptAttr::Generic: Kind = ""; break;
5035 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5036 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5037 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5038 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5039 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5040 }
5041
5042 llvm::Function *Fn = cast<llvm::Function>(GV);
5043
5044 Fn->addFnAttr("interrupt", Kind);
5045
Tim Northover5627d392015-10-30 16:30:45 +00005046 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5047 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005048 return;
5049
5050 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5051 // however this is not necessarily true on taking any interrupt. Instruct
5052 // the backend to perform a realignment as part of the function prologue.
5053 llvm::AttrBuilder B;
5054 B.addStackAlignmentAttr(8);
5055 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5056 llvm::AttributeSet::get(CGM.getLLVMContext(),
5057 llvm::AttributeSet::FunctionIndex,
5058 B));
5059 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005060};
5061
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005062class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005063public:
5064 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5065 : ARMTargetCodeGenInfo(CGT, K) {}
5066
Eric Christopher162c91c2015-06-05 22:03:00 +00005067 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005068 CodeGen::CodeGenModule &CGM) const override;
5069};
5070
Eric Christopher162c91c2015-06-05 22:03:00 +00005071void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005072 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005073 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005074 addStackProbeSizeTargetAttribute(D, GV, CGM);
5075}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005076}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005077
Chris Lattner22326a12010-07-29 02:31:05 +00005078void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005079 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005080 FI.getReturnInfo() =
5081 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005082
Tim Northoverbc784d12015-02-24 17:22:40 +00005083 for (auto &I : FI.arguments())
5084 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005085
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005086 // Always honor user-specified calling convention.
5087 if (FI.getCallingConvention() != llvm::CallingConv::C)
5088 return;
5089
John McCall882987f2013-02-28 19:01:20 +00005090 llvm::CallingConv::ID cc = getRuntimeCC();
5091 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005092 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005093}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005094
John McCall882987f2013-02-28 19:01:20 +00005095/// Return the default calling convention that LLVM will use.
5096llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5097 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005098 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005099 return llvm::CallingConv::ARM_AAPCS_VFP;
5100 else if (isEABI())
5101 return llvm::CallingConv::ARM_AAPCS;
5102 else
5103 return llvm::CallingConv::ARM_APCS;
5104}
5105
5106/// Return the calling convention that our ABI would like us to use
5107/// as the C calling convention.
5108llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005109 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005110 case APCS: return llvm::CallingConv::ARM_APCS;
5111 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5112 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005113 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005114 }
John McCall882987f2013-02-28 19:01:20 +00005115 llvm_unreachable("bad ABI kind");
5116}
5117
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005118void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005119 assert(getRuntimeCC() == llvm::CallingConv::C);
5120
5121 // Don't muddy up the IR with a ton of explicit annotations if
5122 // they'd just match what LLVM will infer from the triple.
5123 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5124 if (abiCC != getLLVMDefaultCC())
5125 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005126
Tim Northover5627d392015-10-30 16:30:45 +00005127 // AAPCS apparently requires runtime support functions to be soft-float, but
5128 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5129 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5130 switch (getABIKind()) {
5131 case APCS:
5132 case AAPCS16_VFP:
5133 if (abiCC != getLLVMDefaultCC())
5134 BuiltinCC = abiCC;
5135 break;
5136 case AAPCS:
5137 case AAPCS_VFP:
5138 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5139 break;
5140 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005141}
5142
Tim Northoverbc784d12015-02-24 17:22:40 +00005143ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5144 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005145 // 6.1.2.1 The following argument types are VFP CPRCs:
5146 // A single-precision floating-point type (including promoted
5147 // half-precision types); A double-precision floating-point type;
5148 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5149 // with a Base Type of a single- or double-precision floating-point type,
5150 // 64-bit containerized vectors or 128-bit containerized vectors with one
5151 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005152 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005153
Reid Klecknerb1be6832014-11-15 01:41:41 +00005154 Ty = useFirstFieldIfTransparentUnion(Ty);
5155
Manman Renfef9e312012-10-16 19:18:39 +00005156 // Handle illegal vector types here.
5157 if (isIllegalVectorType(Ty)) {
5158 uint64_t Size = getContext().getTypeSize(Ty);
5159 if (Size <= 32) {
5160 llvm::Type *ResType =
5161 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005162 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005163 }
5164 if (Size == 64) {
5165 llvm::Type *ResType = llvm::VectorType::get(
5166 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005167 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005168 }
5169 if (Size == 128) {
5170 llvm::Type *ResType = llvm::VectorType::get(
5171 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005172 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005173 }
John McCall7f416cc2015-09-08 08:05:57 +00005174 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005175 }
5176
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005177 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5178 // unspecified. This is not done for OpenCL as it handles the half type
5179 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005180 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005181 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5182 llvm::Type::getFloatTy(getVMContext()) :
5183 llvm::Type::getInt32Ty(getVMContext());
5184 return ABIArgInfo::getDirect(ResType);
5185 }
5186
John McCalla1dee5302010-08-22 10:59:02 +00005187 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005188 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005189 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005190 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005191 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005192
Tim Northover5a1558e2014-11-07 22:30:50 +00005193 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5194 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005195 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005196
Oliver Stannard405bded2014-02-11 09:25:50 +00005197 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005198 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005199 }
Tim Northover1060eae2013-06-21 22:49:34 +00005200
Daniel Dunbar09d33622009-09-14 21:54:03 +00005201 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005202 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005203 return ABIArgInfo::getIgnore();
5204
Tim Northover5a1558e2014-11-07 22:30:50 +00005205 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005206 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5207 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005208 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005209 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005210 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005211 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005212 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005213 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005214 }
Tim Northover5627d392015-10-30 16:30:45 +00005215 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5216 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5217 // this convention even for a variadic function: the backend will use GPRs
5218 // if needed.
5219 const Type *Base = nullptr;
5220 uint64_t Members = 0;
5221 if (isHomogeneousAggregate(Ty, Base, Members)) {
5222 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5223 llvm::Type *Ty =
5224 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5225 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5226 }
5227 }
5228
5229 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5230 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5231 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5232 // bigger than 128-bits, they get placed in space allocated by the caller,
5233 // and a pointer is passed.
5234 return ABIArgInfo::getIndirect(
5235 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005236 }
5237
Manman Ren6c30e132012-08-13 21:23:55 +00005238 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005239 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5240 // most 8-byte. We realign the indirect argument if type alignment is bigger
5241 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005242 uint64_t ABIAlign = 4;
5243 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5244 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005245 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005246 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005247
Manman Ren8cd99812012-11-06 04:58:01 +00005248 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005249 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005250 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5251 /*ByVal=*/true,
5252 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005253 }
5254
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005255 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005256 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005257 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005258 // FIXME: Try to match the types of the arguments more accurately where
5259 // we can.
5260 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005261 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5262 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005263 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005264 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5265 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005266 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005267
Tim Northover5a1558e2014-11-07 22:30:50 +00005268 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005269}
5270
Chris Lattner458b2aa2010-07-29 02:16:43 +00005271static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005272 llvm::LLVMContext &VMContext) {
5273 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5274 // is called integer-like if its size is less than or equal to one word, and
5275 // the offset of each of its addressable sub-fields is zero.
5276
5277 uint64_t Size = Context.getTypeSize(Ty);
5278
5279 // Check that the type fits in a word.
5280 if (Size > 32)
5281 return false;
5282
5283 // FIXME: Handle vector types!
5284 if (Ty->isVectorType())
5285 return false;
5286
Daniel Dunbard53bac72009-09-14 02:20:34 +00005287 // Float types are never treated as "integer like".
5288 if (Ty->isRealFloatingType())
5289 return false;
5290
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005291 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005292 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005293 return true;
5294
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005295 // Small complex integer types are "integer like".
5296 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5297 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005298
5299 // Single element and zero sized arrays should be allowed, by the definition
5300 // above, but they are not.
5301
5302 // Otherwise, it must be a record type.
5303 const RecordType *RT = Ty->getAs<RecordType>();
5304 if (!RT) return false;
5305
5306 // Ignore records with flexible arrays.
5307 const RecordDecl *RD = RT->getDecl();
5308 if (RD->hasFlexibleArrayMember())
5309 return false;
5310
5311 // Check that all sub-fields are at offset 0, and are themselves "integer
5312 // like".
5313 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5314
5315 bool HadField = false;
5316 unsigned idx = 0;
5317 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5318 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005319 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005320
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005321 // Bit-fields are not addressable, we only need to verify they are "integer
5322 // like". We still have to disallow a subsequent non-bitfield, for example:
5323 // struct { int : 0; int x }
5324 // is non-integer like according to gcc.
5325 if (FD->isBitField()) {
5326 if (!RD->isUnion())
5327 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005328
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005329 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5330 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005331
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005332 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005333 }
5334
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005335 // Check if this field is at offset 0.
5336 if (Layout.getFieldOffset(idx) != 0)
5337 return false;
5338
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005339 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5340 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005341
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005342 // Only allow at most one field in a structure. This doesn't match the
5343 // wording above, but follows gcc in situations with a field following an
5344 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005345 if (!RD->isUnion()) {
5346 if (HadField)
5347 return false;
5348
5349 HadField = true;
5350 }
5351 }
5352
5353 return true;
5354}
5355
Oliver Stannard405bded2014-02-11 09:25:50 +00005356ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5357 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005358 bool IsEffectivelyAAPCS_VFP =
5359 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005360
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005361 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005362 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005363
Daniel Dunbar19964db2010-09-23 01:54:32 +00005364 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005365 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005366 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005367 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005368
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005369 // __fp16 gets returned as if it were an int or float, but with the top 16
5370 // bits unspecified. This is not done for OpenCL as it handles the half type
5371 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005372 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005373 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5374 llvm::Type::getFloatTy(getVMContext()) :
5375 llvm::Type::getInt32Ty(getVMContext());
5376 return ABIArgInfo::getDirect(ResType);
5377 }
5378
John McCalla1dee5302010-08-22 10:59:02 +00005379 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005380 // Treat an enum type as its underlying type.
5381 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5382 RetTy = EnumTy->getDecl()->getIntegerType();
5383
Tim Northover5a1558e2014-11-07 22:30:50 +00005384 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5385 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005386 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005387
5388 // Are we following APCS?
5389 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005390 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005391 return ABIArgInfo::getIgnore();
5392
Daniel Dunbareedf1512010-02-01 23:31:19 +00005393 // Complex types are all returned as packed integers.
5394 //
5395 // FIXME: Consider using 2 x vector types if the back end handles them
5396 // correctly.
5397 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005398 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5399 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005400
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005401 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005402 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005403 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005404 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005405 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005406 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005407 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005408 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5409 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005410 }
5411
5412 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005413 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005414 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005415
5416 // Otherwise this is an AAPCS variant.
5417
Chris Lattner458b2aa2010-07-29 02:16:43 +00005418 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005419 return ABIArgInfo::getIgnore();
5420
Bob Wilson1d9269a2011-11-02 04:51:36 +00005421 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005422 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005423 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005424 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005425 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005426 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005427 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005428 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005429 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005430 }
5431
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005432 // Aggregates <= 4 bytes are returned in r0; other aggregates
5433 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005434 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005435 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005436 if (getDataLayout().isBigEndian())
5437 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005438 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005439
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005440 // Return in the smallest viable integer type.
5441 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005442 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005443 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005444 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5445 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005446 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5447 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5448 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005449 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005450 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005451 }
5452
John McCall7f416cc2015-09-08 08:05:57 +00005453 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005454}
5455
Manman Renfef9e312012-10-16 19:18:39 +00005456/// isIllegalVector - check whether Ty is an illegal vector type.
5457bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005458 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5459 if (isAndroid()) {
5460 // Android shipped using Clang 3.1, which supported a slightly different
5461 // vector ABI. The primary differences were that 3-element vector types
5462 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5463 // accepts that legacy behavior for Android only.
5464 // Check whether VT is legal.
5465 unsigned NumElements = VT->getNumElements();
5466 // NumElements should be power of 2 or equal to 3.
5467 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5468 return true;
5469 } else {
5470 // Check whether VT is legal.
5471 unsigned NumElements = VT->getNumElements();
5472 uint64_t Size = getContext().getTypeSize(VT);
5473 // NumElements should be power of 2.
5474 if (!llvm::isPowerOf2_32(NumElements))
5475 return true;
5476 // Size should be greater than 32 bits.
5477 return Size <= 32;
5478 }
Manman Renfef9e312012-10-16 19:18:39 +00005479 }
5480 return false;
5481}
5482
Reid Klecknere9f6a712014-10-31 17:10:41 +00005483bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5484 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5485 // double, or 64-bit or 128-bit vectors.
5486 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5487 if (BT->getKind() == BuiltinType::Float ||
5488 BT->getKind() == BuiltinType::Double ||
5489 BT->getKind() == BuiltinType::LongDouble)
5490 return true;
5491 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5492 unsigned VecSize = getContext().getTypeSize(VT);
5493 if (VecSize == 64 || VecSize == 128)
5494 return true;
5495 }
5496 return false;
5497}
5498
5499bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5500 uint64_t Members) const {
5501 return Members <= 4;
5502}
5503
John McCall7f416cc2015-09-08 08:05:57 +00005504Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5505 QualType Ty) const {
5506 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005507
John McCall7f416cc2015-09-08 08:05:57 +00005508 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005509 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005510 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5511 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5512 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005513 }
5514
John McCall7f416cc2015-09-08 08:05:57 +00005515 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5516 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005517
John McCall7f416cc2015-09-08 08:05:57 +00005518 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5519 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005520 const Type *Base = nullptr;
5521 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005522 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5523 IsIndirect = true;
5524
Tim Northover5627d392015-10-30 16:30:45 +00005525 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5526 // allocated by the caller.
5527 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5528 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5529 !isHomogeneousAggregate(Ty, Base, Members)) {
5530 IsIndirect = true;
5531
John McCall7f416cc2015-09-08 08:05:57 +00005532 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005533 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5534 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005535 // Our callers should be prepared to handle an under-aligned address.
5536 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5537 getABIKind() == ARMABIInfo::AAPCS) {
5538 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5539 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005540 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5541 // ARMv7k allows type alignment up to 16 bytes.
5542 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5543 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005544 } else {
5545 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005546 }
John McCall7f416cc2015-09-08 08:05:57 +00005547 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005548
John McCall7f416cc2015-09-08 08:05:57 +00005549 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5550 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005551}
5552
Chris Lattner0cf24192010-06-28 20:05:43 +00005553//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005554// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005555//===----------------------------------------------------------------------===//
5556
5557namespace {
5558
Justin Holewinski83e96682012-05-24 17:43:12 +00005559class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005560public:
Justin Holewinski36837432013-03-30 14:38:24 +00005561 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005562
5563 ABIArgInfo classifyReturnType(QualType RetTy) const;
5564 ABIArgInfo classifyArgumentType(QualType Ty) const;
5565
Craig Topper4f12f102014-03-12 06:41:41 +00005566 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005567 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5568 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005569};
5570
Justin Holewinski83e96682012-05-24 17:43:12 +00005571class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005572public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005573 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5574 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005575
Eric Christopher162c91c2015-06-05 22:03:00 +00005576 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005577 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005578private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005579 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5580 // resulting MDNode to the nvvm.annotations MDNode.
5581 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005582};
5583
Justin Holewinski83e96682012-05-24 17:43:12 +00005584ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005585 if (RetTy->isVoidType())
5586 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005587
5588 // note: this is different from default ABI
5589 if (!RetTy->isScalarType())
5590 return ABIArgInfo::getDirect();
5591
5592 // Treat an enum type as its underlying type.
5593 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5594 RetTy = EnumTy->getDecl()->getIntegerType();
5595
5596 return (RetTy->isPromotableIntegerType() ?
5597 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005598}
5599
Justin Holewinski83e96682012-05-24 17:43:12 +00005600ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005601 // Treat an enum type as its underlying type.
5602 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5603 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005604
Eli Bendersky95338a02014-10-29 13:43:21 +00005605 // Return aggregates type as indirect by value
5606 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005607 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005608
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005609 return (Ty->isPromotableIntegerType() ?
5610 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005611}
5612
Justin Holewinski83e96682012-05-24 17:43:12 +00005613void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005614 if (!getCXXABI().classifyReturnType(FI))
5615 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005616 for (auto &I : FI.arguments())
5617 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005618
5619 // Always honor user-specified calling convention.
5620 if (FI.getCallingConvention() != llvm::CallingConv::C)
5621 return;
5622
John McCall882987f2013-02-28 19:01:20 +00005623 FI.setEffectiveCallingConvention(getRuntimeCC());
5624}
5625
John McCall7f416cc2015-09-08 08:05:57 +00005626Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5627 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005628 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005629}
5630
Justin Holewinski83e96682012-05-24 17:43:12 +00005631void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005632setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005633 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005634 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005635 if (!FD) return;
5636
5637 llvm::Function *F = cast<llvm::Function>(GV);
5638
5639 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005640 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005641 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005642 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005643 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005644 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005645 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5646 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005647 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005648 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005649 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005650 }
Justin Holewinski38031972011-10-05 17:58:44 +00005651
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005652 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005653 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005654 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005655 // __global__ functions cannot be called from the device, we do not
5656 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005657 if (FD->hasAttr<CUDAGlobalAttr>()) {
5658 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5659 addNVVMMetadata(F, "kernel", 1);
5660 }
Artem Belevich7093e402015-04-21 22:55:54 +00005661 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005662 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005663 llvm::APSInt MaxThreads(32);
5664 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5665 if (MaxThreads > 0)
5666 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5667
5668 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5669 // not specified in __launch_bounds__ or if the user specified a 0 value,
5670 // we don't have to add a PTX directive.
5671 if (Attr->getMinBlocks()) {
5672 llvm::APSInt MinBlocks(32);
5673 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5674 if (MinBlocks > 0)
5675 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5676 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005677 }
5678 }
Justin Holewinski38031972011-10-05 17:58:44 +00005679 }
5680}
5681
Eli Benderskye06a2c42014-04-15 16:57:05 +00005682void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5683 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005684 llvm::Module *M = F->getParent();
5685 llvm::LLVMContext &Ctx = M->getContext();
5686
5687 // Get "nvvm.annotations" metadata node
5688 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5689
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005690 llvm::Metadata *MDVals[] = {
5691 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5692 llvm::ConstantAsMetadata::get(
5693 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005694 // Append metadata to nvvm.annotations
5695 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5696}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005697}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005698
5699//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005700// SystemZ ABI Implementation
5701//===----------------------------------------------------------------------===//
5702
5703namespace {
5704
5705class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005706 bool HasVector;
5707
Ulrich Weigand47445072013-05-06 16:26:41 +00005708public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005709 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5710 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005711
5712 bool isPromotableIntegerType(QualType Ty) const;
5713 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005714 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005715 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005716 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005717
5718 ABIArgInfo classifyReturnType(QualType RetTy) const;
5719 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5720
Craig Topper4f12f102014-03-12 06:41:41 +00005721 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005722 if (!getCXXABI().classifyReturnType(FI))
5723 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005724 for (auto &I : FI.arguments())
5725 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005726 }
5727
John McCall7f416cc2015-09-08 08:05:57 +00005728 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5729 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005730};
5731
5732class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5733public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005734 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5735 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005736};
5737
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005738}
Ulrich Weigand47445072013-05-06 16:26:41 +00005739
5740bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5741 // Treat an enum type as its underlying type.
5742 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5743 Ty = EnumTy->getDecl()->getIntegerType();
5744
5745 // Promotable integer types are required to be promoted by the ABI.
5746 if (Ty->isPromotableIntegerType())
5747 return true;
5748
5749 // 32-bit values must also be promoted.
5750 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5751 switch (BT->getKind()) {
5752 case BuiltinType::Int:
5753 case BuiltinType::UInt:
5754 return true;
5755 default:
5756 return false;
5757 }
5758 return false;
5759}
5760
5761bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005762 return (Ty->isAnyComplexType() ||
5763 Ty->isVectorType() ||
5764 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005765}
5766
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005767bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5768 return (HasVector &&
5769 Ty->isVectorType() &&
5770 getContext().getTypeSize(Ty) <= 128);
5771}
5772
Ulrich Weigand47445072013-05-06 16:26:41 +00005773bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5774 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5775 switch (BT->getKind()) {
5776 case BuiltinType::Float:
5777 case BuiltinType::Double:
5778 return true;
5779 default:
5780 return false;
5781 }
5782
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005783 return false;
5784}
5785
5786QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005787 if (const RecordType *RT = Ty->getAsStructureType()) {
5788 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005789 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005790
5791 // If this is a C++ record, check the bases first.
5792 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005793 for (const auto &I : CXXRD->bases()) {
5794 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005795
5796 // Empty bases don't affect things either way.
5797 if (isEmptyRecord(getContext(), Base, true))
5798 continue;
5799
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005800 if (!Found.isNull())
5801 return Ty;
5802 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005803 }
5804
5805 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005806 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005807 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005808 // Unlike isSingleElementStruct(), empty structure and array fields
5809 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005810 if (getContext().getLangOpts().CPlusPlus &&
5811 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5812 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005813
5814 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005815 // Nested structures still do though.
5816 if (!Found.isNull())
5817 return Ty;
5818 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005819 }
5820
5821 // Unlike isSingleElementStruct(), trailing padding is allowed.
5822 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005823 if (!Found.isNull())
5824 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005825 }
5826
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005827 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005828}
5829
John McCall7f416cc2015-09-08 08:05:57 +00005830Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5831 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005832 // Assume that va_list type is correct; should be pointer to LLVM type:
5833 // struct {
5834 // i64 __gpr;
5835 // i64 __fpr;
5836 // i8 *__overflow_arg_area;
5837 // i8 *__reg_save_area;
5838 // };
5839
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005840 // Every non-vector argument occupies 8 bytes and is passed by preference
5841 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5842 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005843 Ty = getContext().getCanonicalType(Ty);
5844 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005845 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005846 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005847 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005848 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005849 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005850 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005851 CharUnits UnpaddedSize;
5852 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005853 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005854 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5855 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005856 } else {
5857 if (AI.getCoerceToType())
5858 ArgTy = AI.getCoerceToType();
5859 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005860 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005861 UnpaddedSize = TyInfo.first;
5862 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005863 }
John McCall7f416cc2015-09-08 08:05:57 +00005864 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5865 if (IsVector && UnpaddedSize > PaddedSize)
5866 PaddedSize = CharUnits::fromQuantity(16);
5867 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005868
John McCall7f416cc2015-09-08 08:05:57 +00005869 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005870
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005871 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005872 llvm::Value *PaddedSizeV =
5873 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005874
5875 if (IsVector) {
5876 // Work out the address of a vector argument on the stack.
5877 // Vector arguments are always passed in the high bits of a
5878 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005879 Address OverflowArgAreaPtr =
5880 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005881 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005882 Address OverflowArgArea =
5883 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5884 TyInfo.second);
5885 Address MemAddr =
5886 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005887
5888 // Update overflow_arg_area_ptr pointer
5889 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005890 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5891 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005892 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5893
5894 return MemAddr;
5895 }
5896
John McCall7f416cc2015-09-08 08:05:57 +00005897 assert(PaddedSize.getQuantity() == 8);
5898
5899 unsigned MaxRegs, RegCountField, RegSaveIndex;
5900 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005901 if (InFPRs) {
5902 MaxRegs = 4; // Maximum of 4 FPR arguments
5903 RegCountField = 1; // __fpr
5904 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005905 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005906 } else {
5907 MaxRegs = 5; // Maximum of 5 GPR arguments
5908 RegCountField = 0; // __gpr
5909 RegSaveIndex = 2; // save offset for r2
5910 RegPadding = Padding; // values are passed in the low bits of a GPR
5911 }
5912
John McCall7f416cc2015-09-08 08:05:57 +00005913 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5914 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5915 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005916 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005917 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5918 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005919 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005920
5921 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5922 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5923 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5924 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5925
5926 // Emit code to load the value if it was passed in registers.
5927 CGF.EmitBlock(InRegBlock);
5928
5929 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005930 llvm::Value *ScaledRegCount =
5931 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5932 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005933 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5934 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005935 llvm::Value *RegOffset =
5936 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005937 Address RegSaveAreaPtr =
5938 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5939 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005940 llvm::Value *RegSaveArea =
5941 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005942 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5943 "raw_reg_addr"),
5944 PaddedSize);
5945 Address RegAddr =
5946 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005947
5948 // Update the register count
5949 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5950 llvm::Value *NewRegCount =
5951 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5952 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5953 CGF.EmitBranch(ContBlock);
5954
5955 // Emit code to load the value if it was passed in memory.
5956 CGF.EmitBlock(InMemBlock);
5957
5958 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005959 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5960 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5961 Address OverflowArgArea =
5962 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5963 PaddedSize);
5964 Address RawMemAddr =
5965 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5966 Address MemAddr =
5967 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005968
5969 // Update overflow_arg_area_ptr pointer
5970 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005971 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5972 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005973 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5974 CGF.EmitBranch(ContBlock);
5975
5976 // Return the appropriate result.
5977 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005978 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5979 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005980
5981 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005982 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5983 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005984
5985 return ResAddr;
5986}
5987
Ulrich Weigand47445072013-05-06 16:26:41 +00005988ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5989 if (RetTy->isVoidType())
5990 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005991 if (isVectorArgumentType(RetTy))
5992 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005993 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00005994 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005995 return (isPromotableIntegerType(RetTy) ?
5996 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5997}
5998
5999ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6000 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006001 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006002 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006003
6004 // Integers and enums are extended to full register width.
6005 if (isPromotableIntegerType(Ty))
6006 return ABIArgInfo::getExtend();
6007
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006008 // Handle vector types and vector-like structure types. Note that
6009 // as opposed to float-like structure types, we do not allow any
6010 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006011 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006012 QualType SingleElementTy = GetSingleElementType(Ty);
6013 if (isVectorArgumentType(SingleElementTy) &&
6014 getContext().getTypeSize(SingleElementTy) == Size)
6015 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6016
6017 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006018 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006019 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006020
6021 // Handle small structures.
6022 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6023 // Structures with flexible arrays have variable length, so really
6024 // fail the size test above.
6025 const RecordDecl *RD = RT->getDecl();
6026 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006027 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006028
6029 // The structure is passed as an unextended integer, a float, or a double.
6030 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006031 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006032 assert(Size == 32 || Size == 64);
6033 if (Size == 32)
6034 PassTy = llvm::Type::getFloatTy(getVMContext());
6035 else
6036 PassTy = llvm::Type::getDoubleTy(getVMContext());
6037 } else
6038 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6039 return ABIArgInfo::getDirect(PassTy);
6040 }
6041
6042 // Non-structure compounds are passed indirectly.
6043 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006044 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006045
Craig Topper8a13c412014-05-21 05:09:00 +00006046 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006047}
6048
6049//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006050// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006051//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006052
6053namespace {
6054
6055class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6056public:
Chris Lattner2b037972010-07-29 02:01:43 +00006057 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6058 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006059 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006060 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006061};
6062
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006063}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006064
Eric Christopher162c91c2015-06-05 22:03:00 +00006065void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006066 llvm::GlobalValue *GV,
6067 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006068 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006069 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6070 // Handle 'interrupt' attribute:
6071 llvm::Function *F = cast<llvm::Function>(GV);
6072
6073 // Step 1: Set ISR calling convention.
6074 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6075
6076 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006077 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006078
6079 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006080 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006081 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6082 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006083 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006084 }
6085}
6086
Chris Lattner0cf24192010-06-28 20:05:43 +00006087//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006088// MIPS ABI Implementation. This works for both little-endian and
6089// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006090//===----------------------------------------------------------------------===//
6091
John McCall943fae92010-05-27 06:19:26 +00006092namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006093class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006094 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006095 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6096 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006097 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006098 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006099 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006100 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006101public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006102 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006103 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006104 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006105
6106 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006107 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006108 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006109 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6110 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006111 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006112};
6113
John McCall943fae92010-05-27 06:19:26 +00006114class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006115 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006116public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006117 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6118 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006119 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006120
Craig Topper4f12f102014-03-12 06:41:41 +00006121 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006122 return 29;
6123 }
6124
Eric Christopher162c91c2015-06-05 22:03:00 +00006125 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006126 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006127 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006128 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006129 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006130 if (FD->hasAttr<Mips16Attr>()) {
6131 Fn->addFnAttr("mips16");
6132 }
6133 else if (FD->hasAttr<NoMips16Attr>()) {
6134 Fn->addFnAttr("nomips16");
6135 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006136
6137 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6138 if (!Attr)
6139 return;
6140
6141 const char *Kind;
6142 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006143 case MipsInterruptAttr::eic: Kind = "eic"; break;
6144 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6145 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6146 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6147 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6148 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6149 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6150 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6151 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6152 }
6153
6154 Fn->addFnAttr("interrupt", Kind);
6155
Reed Kotler373feca2013-01-16 17:10:28 +00006156 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006157
John McCall943fae92010-05-27 06:19:26 +00006158 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006159 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006160
Craig Topper4f12f102014-03-12 06:41:41 +00006161 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006162 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006163 }
John McCall943fae92010-05-27 06:19:26 +00006164};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006165}
John McCall943fae92010-05-27 06:19:26 +00006166
Eric Christopher7565e0d2015-05-29 23:09:49 +00006167void MipsABIInfo::CoerceToIntArgs(
6168 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006169 llvm::IntegerType *IntTy =
6170 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006171
6172 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6173 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6174 ArgList.push_back(IntTy);
6175
6176 // If necessary, add one more integer type to ArgList.
6177 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6178
6179 if (R)
6180 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006181}
6182
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006183// In N32/64, an aligned double precision floating point field is passed in
6184// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006185llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006186 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6187
6188 if (IsO32) {
6189 CoerceToIntArgs(TySize, ArgList);
6190 return llvm::StructType::get(getVMContext(), ArgList);
6191 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006192
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006193 if (Ty->isComplexType())
6194 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006195
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006196 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006197
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006198 // Unions/vectors are passed in integer registers.
6199 if (!RT || !RT->isStructureOrClassType()) {
6200 CoerceToIntArgs(TySize, ArgList);
6201 return llvm::StructType::get(getVMContext(), ArgList);
6202 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006203
6204 const RecordDecl *RD = RT->getDecl();
6205 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006206 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006207
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006208 uint64_t LastOffset = 0;
6209 unsigned idx = 0;
6210 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6211
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006212 // Iterate over fields in the struct/class and check if there are any aligned
6213 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006214 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6215 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006216 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006217 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6218
6219 if (!BT || BT->getKind() != BuiltinType::Double)
6220 continue;
6221
6222 uint64_t Offset = Layout.getFieldOffset(idx);
6223 if (Offset % 64) // Ignore doubles that are not aligned.
6224 continue;
6225
6226 // Add ((Offset - LastOffset) / 64) args of type i64.
6227 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6228 ArgList.push_back(I64);
6229
6230 // Add double type.
6231 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6232 LastOffset = Offset + 64;
6233 }
6234
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006235 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6236 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006237
6238 return llvm::StructType::get(getVMContext(), ArgList);
6239}
6240
Akira Hatanakaddd66342013-10-29 18:41:15 +00006241llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6242 uint64_t Offset) const {
6243 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006244 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006245
Akira Hatanakaddd66342013-10-29 18:41:15 +00006246 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006247}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006248
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006249ABIArgInfo
6250MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006251 Ty = useFirstFieldIfTransparentUnion(Ty);
6252
Akira Hatanaka1632af62012-01-09 19:31:25 +00006253 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006254 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006255 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006256
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006257 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6258 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006259 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6260 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006261
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006262 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006263 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006264 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006265 return ABIArgInfo::getIgnore();
6266
Mark Lacey3825e832013-10-06 01:33:34 +00006267 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006268 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006269 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006270 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006271
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006272 // If we have reached here, aggregates are passed directly by coercing to
6273 // another structure type. Padding is inserted if the offset of the
6274 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006275 ABIArgInfo ArgInfo =
6276 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6277 getPaddingType(OrigOffset, CurrOffset));
6278 ArgInfo.setInReg(true);
6279 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006280 }
6281
6282 // Treat an enum type as its underlying type.
6283 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6284 Ty = EnumTy->getDecl()->getIntegerType();
6285
Daniel Sanders5b445b32014-10-24 14:42:42 +00006286 // All integral types are promoted to the GPR width.
6287 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006288 return ABIArgInfo::getExtend();
6289
Akira Hatanakaddd66342013-10-29 18:41:15 +00006290 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006291 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006292}
6293
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006294llvm::Type*
6295MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006296 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006297 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006298
Akira Hatanakab6f74432012-02-09 18:49:26 +00006299 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006300 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006301 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6302 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006303
Akira Hatanakab6f74432012-02-09 18:49:26 +00006304 // N32/64 returns struct/classes in floating point registers if the
6305 // following conditions are met:
6306 // 1. The size of the struct/class is no larger than 128-bit.
6307 // 2. The struct/class has one or two fields all of which are floating
6308 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006309 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006310 //
6311 // Any other composite results are returned in integer registers.
6312 //
6313 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6314 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6315 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006316 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006317
Akira Hatanakab6f74432012-02-09 18:49:26 +00006318 if (!BT || !BT->isFloatingPoint())
6319 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006320
David Blaikie2d7c57e2012-04-30 02:36:29 +00006321 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006322 }
6323
6324 if (b == e)
6325 return llvm::StructType::get(getVMContext(), RTList,
6326 RD->hasAttr<PackedAttr>());
6327
6328 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006329 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006330 }
6331
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006332 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006333 return llvm::StructType::get(getVMContext(), RTList);
6334}
6335
Akira Hatanakab579fe52011-06-02 00:09:17 +00006336ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006337 uint64_t Size = getContext().getTypeSize(RetTy);
6338
Daniel Sandersed39f582014-09-04 13:28:14 +00006339 if (RetTy->isVoidType())
6340 return ABIArgInfo::getIgnore();
6341
6342 // O32 doesn't treat zero-sized structs differently from other structs.
6343 // However, N32/N64 ignores zero sized return values.
6344 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006345 return ABIArgInfo::getIgnore();
6346
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006347 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006348 if (Size <= 128) {
6349 if (RetTy->isAnyComplexType())
6350 return ABIArgInfo::getDirect();
6351
Daniel Sanderse5018b62014-09-04 15:05:39 +00006352 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006353 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006354 if (!IsO32 ||
6355 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6356 ABIArgInfo ArgInfo =
6357 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6358 ArgInfo.setInReg(true);
6359 return ArgInfo;
6360 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006361 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006362
John McCall7f416cc2015-09-08 08:05:57 +00006363 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006364 }
6365
6366 // Treat an enum type as its underlying type.
6367 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6368 RetTy = EnumTy->getDecl()->getIntegerType();
6369
6370 return (RetTy->isPromotableIntegerType() ?
6371 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6372}
6373
6374void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006375 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006376 if (!getCXXABI().classifyReturnType(FI))
6377 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006378
Eric Christopher7565e0d2015-05-29 23:09:49 +00006379 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006380 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006381
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006382 for (auto &I : FI.arguments())
6383 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006384}
6385
John McCall7f416cc2015-09-08 08:05:57 +00006386Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6387 QualType OrigTy) const {
6388 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006389
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006390 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6391 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006392 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006393 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006394 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006395 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006396 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006397 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006398 DidPromote = true;
6399 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6400 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006401 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006402
John McCall7f416cc2015-09-08 08:05:57 +00006403 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006404
John McCall7f416cc2015-09-08 08:05:57 +00006405 // The alignment of things in the argument area is never larger than
6406 // StackAlignInBytes.
6407 TyInfo.second =
6408 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6409
6410 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6411 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6412
6413 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6414 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6415
6416
6417 // If there was a promotion, "unpromote" into a temporary.
6418 // TODO: can we just use a pointer into a subset of the original slot?
6419 if (DidPromote) {
6420 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6421 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6422
6423 // Truncate down to the right width.
6424 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6425 : CGF.IntPtrTy);
6426 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6427 if (OrigTy->isPointerType())
6428 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6429
6430 CGF.Builder.CreateStore(V, Temp);
6431 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006432 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006433
John McCall7f416cc2015-09-08 08:05:57 +00006434 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006435}
6436
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006437bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6438 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006439
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006440 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6441 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6442 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006443
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006444 return false;
6445}
6446
John McCall943fae92010-05-27 06:19:26 +00006447bool
6448MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6449 llvm::Value *Address) const {
6450 // This information comes from gcc's implementation, which seems to
6451 // as canonical as it gets.
6452
John McCall943fae92010-05-27 06:19:26 +00006453 // Everything on MIPS is 4 bytes. Double-precision FP registers
6454 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006455 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006456
6457 // 0-31 are the general purpose registers, $0 - $31.
6458 // 32-63 are the floating-point registers, $f0 - $f31.
6459 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6460 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006461 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006462
6463 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6464 // They are one bit wide and ignored here.
6465
6466 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6467 // (coprocessor 1 is the FP unit)
6468 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6469 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6470 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006471 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006472 return false;
6473}
6474
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006475//===----------------------------------------------------------------------===//
6476// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006477// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006478// handling.
6479//===----------------------------------------------------------------------===//
6480
6481namespace {
6482
6483class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6484public:
6485 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6486 : DefaultTargetCodeGenInfo(CGT) {}
6487
Eric Christopher162c91c2015-06-05 22:03:00 +00006488 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006489 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006490};
6491
Eric Christopher162c91c2015-06-05 22:03:00 +00006492void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006493 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006494 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006495 if (!FD) return;
6496
6497 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006498
David Blaikiebbafb8a2012-03-11 07:00:24 +00006499 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006500 if (FD->hasAttr<OpenCLKernelAttr>()) {
6501 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006502 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006503 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6504 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006505 // Convert the reqd_work_group_size() attributes to metadata.
6506 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006507 llvm::NamedMDNode *OpenCLMetadata =
6508 M.getModule().getOrInsertNamedMetadata(
6509 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006510
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006511 SmallVector<llvm::Metadata *, 5> Operands;
6512 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006513
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006514 Operands.push_back(
6515 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6516 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6517 Operands.push_back(
6518 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6519 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6520 Operands.push_back(
6521 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6522 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006523
Eric Christopher7565e0d2015-05-29 23:09:49 +00006524 // Add a boolean constant operand for "required" (true) or "hint"
6525 // (false) for implementing the work_group_size_hint attr later.
6526 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006527 Operands.push_back(
6528 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006529 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6530 }
6531 }
6532 }
6533}
6534
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006535}
John McCall943fae92010-05-27 06:19:26 +00006536
Tony Linthicum76329bf2011-12-12 21:14:55 +00006537//===----------------------------------------------------------------------===//
6538// Hexagon ABI Implementation
6539//===----------------------------------------------------------------------===//
6540
6541namespace {
6542
6543class HexagonABIInfo : public ABIInfo {
6544
6545
6546public:
6547 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6548
6549private:
6550
6551 ABIArgInfo classifyReturnType(QualType RetTy) const;
6552 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6553
Craig Topper4f12f102014-03-12 06:41:41 +00006554 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006555
John McCall7f416cc2015-09-08 08:05:57 +00006556 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6557 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006558};
6559
6560class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6561public:
6562 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6563 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6564
Craig Topper4f12f102014-03-12 06:41:41 +00006565 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006566 return 29;
6567 }
6568};
6569
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006570}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006571
6572void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006573 if (!getCXXABI().classifyReturnType(FI))
6574 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006575 for (auto &I : FI.arguments())
6576 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006577}
6578
6579ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6580 if (!isAggregateTypeForABI(Ty)) {
6581 // Treat an enum type as its underlying type.
6582 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6583 Ty = EnumTy->getDecl()->getIntegerType();
6584
6585 return (Ty->isPromotableIntegerType() ?
6586 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6587 }
6588
6589 // Ignore empty records.
6590 if (isEmptyRecord(getContext(), Ty, true))
6591 return ABIArgInfo::getIgnore();
6592
Mark Lacey3825e832013-10-06 01:33:34 +00006593 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006594 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006595
6596 uint64_t Size = getContext().getTypeSize(Ty);
6597 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006598 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006599 // Pass in the smallest viable integer type.
6600 else if (Size > 32)
6601 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6602 else if (Size > 16)
6603 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6604 else if (Size > 8)
6605 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6606 else
6607 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6608}
6609
6610ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6611 if (RetTy->isVoidType())
6612 return ABIArgInfo::getIgnore();
6613
6614 // Large vector types should be returned via memory.
6615 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006616 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006617
6618 if (!isAggregateTypeForABI(RetTy)) {
6619 // Treat an enum type as its underlying type.
6620 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6621 RetTy = EnumTy->getDecl()->getIntegerType();
6622
6623 return (RetTy->isPromotableIntegerType() ?
6624 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6625 }
6626
Tony Linthicum76329bf2011-12-12 21:14:55 +00006627 if (isEmptyRecord(getContext(), RetTy, true))
6628 return ABIArgInfo::getIgnore();
6629
6630 // Aggregates <= 8 bytes are returned in r0; other aggregates
6631 // are returned indirectly.
6632 uint64_t Size = getContext().getTypeSize(RetTy);
6633 if (Size <= 64) {
6634 // Return in the smallest viable integer type.
6635 if (Size <= 8)
6636 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6637 if (Size <= 16)
6638 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6639 if (Size <= 32)
6640 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6641 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6642 }
6643
John McCall7f416cc2015-09-08 08:05:57 +00006644 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006645}
6646
John McCall7f416cc2015-09-08 08:05:57 +00006647Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6648 QualType Ty) const {
6649 // FIXME: Someone needs to audit that this handle alignment correctly.
6650 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6651 getContext().getTypeInfoInChars(Ty),
6652 CharUnits::fromQuantity(4),
6653 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006654}
6655
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006656//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006657// Lanai ABI Implementation
6658//===----------------------------------------------------------------------===//
6659
6660class LanaiABIInfo : public DefaultABIInfo {
6661public:
6662 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6663
6664 bool shouldUseInReg(QualType Ty, CCState &State) const;
6665
6666 void computeInfo(CGFunctionInfo &FI) const override {
6667 CCState State(FI.getCallingConvention());
6668 // Lanai uses 4 registers to pass arguments unless the function has the
6669 // regparm attribute set.
6670 if (FI.getHasRegParm()) {
6671 State.FreeRegs = FI.getRegParm();
6672 } else {
6673 State.FreeRegs = 4;
6674 }
6675
6676 if (!getCXXABI().classifyReturnType(FI))
6677 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6678 for (auto &I : FI.arguments())
6679 I.info = classifyArgumentType(I.type, State);
6680 }
6681
6682 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6683};
6684
6685bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6686 unsigned Size = getContext().getTypeSize(Ty);
6687 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6688
6689 if (SizeInRegs == 0)
6690 return false;
6691
6692 if (SizeInRegs > State.FreeRegs) {
6693 State.FreeRegs = 0;
6694 return false;
6695 }
6696
6697 State.FreeRegs -= SizeInRegs;
6698
6699 return true;
6700}
6701
6702ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6703 CCState &State) const {
6704 if (isAggregateTypeForABI(Ty))
6705 return getNaturalAlignIndirect(Ty);
6706
6707 // Treat an enum type as its underlying type.
6708 if (const auto *EnumTy = Ty->getAs<EnumType>())
6709 Ty = EnumTy->getDecl()->getIntegerType();
6710
6711 if (shouldUseInReg(Ty, State))
6712 return ABIArgInfo::getDirectInReg();
6713
6714 if (Ty->isPromotableIntegerType())
6715 return ABIArgInfo::getExtend();
6716
6717 return ABIArgInfo::getDirect();
6718}
6719
6720namespace {
6721class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6722public:
6723 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
6724 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
6725};
6726}
6727
6728//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006729// AMDGPU ABI Implementation
6730//===----------------------------------------------------------------------===//
6731
6732namespace {
6733
6734class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6735public:
6736 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6737 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006738 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006739 CodeGen::CodeGenModule &M) const override;
6740};
6741
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006742}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006743
Eric Christopher162c91c2015-06-05 22:03:00 +00006744void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006745 const Decl *D,
6746 llvm::GlobalValue *GV,
6747 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006748 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006749 if (!FD)
6750 return;
6751
6752 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6753 llvm::Function *F = cast<llvm::Function>(GV);
6754 uint32_t NumVGPR = Attr->getNumVGPR();
6755 if (NumVGPR != 0)
6756 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6757 }
6758
6759 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6760 llvm::Function *F = cast<llvm::Function>(GV);
6761 unsigned NumSGPR = Attr->getNumSGPR();
6762 if (NumSGPR != 0)
6763 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6764 }
6765}
6766
Tony Linthicum76329bf2011-12-12 21:14:55 +00006767
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006768//===----------------------------------------------------------------------===//
6769// SPARC v9 ABI Implementation.
6770// Based on the SPARC Compliance Definition version 2.4.1.
6771//
6772// Function arguments a mapped to a nominal "parameter array" and promoted to
6773// registers depending on their type. Each argument occupies 8 or 16 bytes in
6774// the array, structs larger than 16 bytes are passed indirectly.
6775//
6776// One case requires special care:
6777//
6778// struct mixed {
6779// int i;
6780// float f;
6781// };
6782//
6783// When a struct mixed is passed by value, it only occupies 8 bytes in the
6784// parameter array, but the int is passed in an integer register, and the float
6785// is passed in a floating point register. This is represented as two arguments
6786// with the LLVM IR inreg attribute:
6787//
6788// declare void f(i32 inreg %i, float inreg %f)
6789//
6790// The code generator will only allocate 4 bytes from the parameter array for
6791// the inreg arguments. All other arguments are allocated a multiple of 8
6792// bytes.
6793//
6794namespace {
6795class SparcV9ABIInfo : public ABIInfo {
6796public:
6797 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6798
6799private:
6800 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006801 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006802 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6803 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006804
6805 // Coercion type builder for structs passed in registers. The coercion type
6806 // serves two purposes:
6807 //
6808 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6809 // in registers.
6810 // 2. Expose aligned floating point elements as first-level elements, so the
6811 // code generator knows to pass them in floating point registers.
6812 //
6813 // We also compute the InReg flag which indicates that the struct contains
6814 // aligned 32-bit floats.
6815 //
6816 struct CoerceBuilder {
6817 llvm::LLVMContext &Context;
6818 const llvm::DataLayout &DL;
6819 SmallVector<llvm::Type*, 8> Elems;
6820 uint64_t Size;
6821 bool InReg;
6822
6823 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6824 : Context(c), DL(dl), Size(0), InReg(false) {}
6825
6826 // Pad Elems with integers until Size is ToSize.
6827 void pad(uint64_t ToSize) {
6828 assert(ToSize >= Size && "Cannot remove elements");
6829 if (ToSize == Size)
6830 return;
6831
6832 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006833 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006834 if (Aligned > Size && Aligned <= ToSize) {
6835 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6836 Size = Aligned;
6837 }
6838
6839 // Add whole 64-bit words.
6840 while (Size + 64 <= ToSize) {
6841 Elems.push_back(llvm::Type::getInt64Ty(Context));
6842 Size += 64;
6843 }
6844
6845 // Final in-word padding.
6846 if (Size < ToSize) {
6847 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6848 Size = ToSize;
6849 }
6850 }
6851
6852 // Add a floating point element at Offset.
6853 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6854 // Unaligned floats are treated as integers.
6855 if (Offset % Bits)
6856 return;
6857 // The InReg flag is only required if there are any floats < 64 bits.
6858 if (Bits < 64)
6859 InReg = true;
6860 pad(Offset);
6861 Elems.push_back(Ty);
6862 Size = Offset + Bits;
6863 }
6864
6865 // Add a struct type to the coercion type, starting at Offset (in bits).
6866 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6867 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6868 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6869 llvm::Type *ElemTy = StrTy->getElementType(i);
6870 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6871 switch (ElemTy->getTypeID()) {
6872 case llvm::Type::StructTyID:
6873 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6874 break;
6875 case llvm::Type::FloatTyID:
6876 addFloat(ElemOffset, ElemTy, 32);
6877 break;
6878 case llvm::Type::DoubleTyID:
6879 addFloat(ElemOffset, ElemTy, 64);
6880 break;
6881 case llvm::Type::FP128TyID:
6882 addFloat(ElemOffset, ElemTy, 128);
6883 break;
6884 case llvm::Type::PointerTyID:
6885 if (ElemOffset % 64 == 0) {
6886 pad(ElemOffset);
6887 Elems.push_back(ElemTy);
6888 Size += 64;
6889 }
6890 break;
6891 default:
6892 break;
6893 }
6894 }
6895 }
6896
6897 // Check if Ty is a usable substitute for the coercion type.
6898 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006899 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006900 }
6901
6902 // Get the coercion type as a literal struct type.
6903 llvm::Type *getType() const {
6904 if (Elems.size() == 1)
6905 return Elems.front();
6906 else
6907 return llvm::StructType::get(Context, Elems);
6908 }
6909 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006910};
6911} // end anonymous namespace
6912
6913ABIArgInfo
6914SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6915 if (Ty->isVoidType())
6916 return ABIArgInfo::getIgnore();
6917
6918 uint64_t Size = getContext().getTypeSize(Ty);
6919
6920 // Anything too big to fit in registers is passed with an explicit indirect
6921 // pointer / sret pointer.
6922 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006923 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006924
6925 // Treat an enum type as its underlying type.
6926 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6927 Ty = EnumTy->getDecl()->getIntegerType();
6928
6929 // Integer types smaller than a register are extended.
6930 if (Size < 64 && Ty->isIntegerType())
6931 return ABIArgInfo::getExtend();
6932
6933 // Other non-aggregates go in registers.
6934 if (!isAggregateTypeForABI(Ty))
6935 return ABIArgInfo::getDirect();
6936
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006937 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6938 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6939 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006940 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006941
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006942 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006943 // Build a coercion type from the LLVM struct type.
6944 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6945 if (!StrTy)
6946 return ABIArgInfo::getDirect();
6947
6948 CoerceBuilder CB(getVMContext(), getDataLayout());
6949 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006950 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006951
6952 // Try to use the original type for coercion.
6953 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6954
6955 if (CB.InReg)
6956 return ABIArgInfo::getDirectInReg(CoerceTy);
6957 else
6958 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006959}
6960
John McCall7f416cc2015-09-08 08:05:57 +00006961Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6962 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006963 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6964 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6965 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6966 AI.setCoerceToType(ArgTy);
6967
John McCall7f416cc2015-09-08 08:05:57 +00006968 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006969
John McCall7f416cc2015-09-08 08:05:57 +00006970 CGBuilderTy &Builder = CGF.Builder;
6971 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6972 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6973
6974 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
6975
6976 Address ArgAddr = Address::invalid();
6977 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006978 switch (AI.getKind()) {
6979 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00006980 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006981 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006982 llvm_unreachable("Unsupported ABI kind for va_arg");
6983
John McCall7f416cc2015-09-08 08:05:57 +00006984 case ABIArgInfo::Extend: {
6985 Stride = SlotSize;
6986 CharUnits Offset = SlotSize - TypeInfo.first;
6987 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006988 break;
John McCall7f416cc2015-09-08 08:05:57 +00006989 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006990
John McCall7f416cc2015-09-08 08:05:57 +00006991 case ABIArgInfo::Direct: {
6992 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00006993 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006994 ArgAddr = Addr;
6995 break;
John McCall7f416cc2015-09-08 08:05:57 +00006996 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006997
6998 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006999 Stride = SlotSize;
7000 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7001 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7002 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007003 break;
7004
7005 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007006 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007007 }
7008
7009 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007010 llvm::Value *NextPtr =
7011 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7012 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007013
John McCall7f416cc2015-09-08 08:05:57 +00007014 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007015}
7016
7017void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7018 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007019 for (auto &I : FI.arguments())
7020 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007021}
7022
7023namespace {
7024class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7025public:
7026 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7027 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007028
Craig Topper4f12f102014-03-12 06:41:41 +00007029 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007030 return 14;
7031 }
7032
7033 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007034 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007035};
7036} // end anonymous namespace
7037
Roman Divackyf02c9942014-02-24 18:46:27 +00007038bool
7039SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7040 llvm::Value *Address) const {
7041 // This is calculated from the LLVM and GCC tables and verified
7042 // against gcc output. AFAIK all ABIs use the same encoding.
7043
7044 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7045
7046 llvm::IntegerType *i8 = CGF.Int8Ty;
7047 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7048 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7049
7050 // 0-31: the 8-byte general-purpose registers
7051 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7052
7053 // 32-63: f0-31, the 4-byte floating-point registers
7054 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7055
7056 // Y = 64
7057 // PSR = 65
7058 // WIM = 66
7059 // TBR = 67
7060 // PC = 68
7061 // NPC = 69
7062 // FSR = 70
7063 // CSR = 71
7064 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007065
Roman Divackyf02c9942014-02-24 18:46:27 +00007066 // 72-87: d0-15, the 8-byte floating-point registers
7067 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7068
7069 return false;
7070}
7071
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007072
Robert Lytton0e076492013-08-13 09:43:10 +00007073//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007074// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007075//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007076
Robert Lytton0e076492013-08-13 09:43:10 +00007077namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007078
7079/// A SmallStringEnc instance is used to build up the TypeString by passing
7080/// it by reference between functions that append to it.
7081typedef llvm::SmallString<128> SmallStringEnc;
7082
7083/// TypeStringCache caches the meta encodings of Types.
7084///
7085/// The reason for caching TypeStrings is two fold:
7086/// 1. To cache a type's encoding for later uses;
7087/// 2. As a means to break recursive member type inclusion.
7088///
7089/// A cache Entry can have a Status of:
7090/// NonRecursive: The type encoding is not recursive;
7091/// Recursive: The type encoding is recursive;
7092/// Incomplete: An incomplete TypeString;
7093/// IncompleteUsed: An incomplete TypeString that has been used in a
7094/// Recursive type encoding.
7095///
7096/// A NonRecursive entry will have all of its sub-members expanded as fully
7097/// as possible. Whilst it may contain types which are recursive, the type
7098/// itself is not recursive and thus its encoding may be safely used whenever
7099/// the type is encountered.
7100///
7101/// A Recursive entry will have all of its sub-members expanded as fully as
7102/// possible. The type itself is recursive and it may contain other types which
7103/// are recursive. The Recursive encoding must not be used during the expansion
7104/// of a recursive type's recursive branch. For simplicity the code uses
7105/// IncompleteCount to reject all usage of Recursive encodings for member types.
7106///
7107/// An Incomplete entry is always a RecordType and only encodes its
7108/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7109/// are placed into the cache during type expansion as a means to identify and
7110/// handle recursive inclusion of types as sub-members. If there is recursion
7111/// the entry becomes IncompleteUsed.
7112///
7113/// During the expansion of a RecordType's members:
7114///
7115/// If the cache contains a NonRecursive encoding for the member type, the
7116/// cached encoding is used;
7117///
7118/// If the cache contains a Recursive encoding for the member type, the
7119/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7120///
7121/// If the member is a RecordType, an Incomplete encoding is placed into the
7122/// cache to break potential recursive inclusion of itself as a sub-member;
7123///
7124/// Once a member RecordType has been expanded, its temporary incomplete
7125/// entry is removed from the cache. If a Recursive encoding was swapped out
7126/// it is swapped back in;
7127///
7128/// If an incomplete entry is used to expand a sub-member, the incomplete
7129/// entry is marked as IncompleteUsed. The cache keeps count of how many
7130/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7131///
7132/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7133/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7134/// Else the member is part of a recursive type and thus the recursion has
7135/// been exited too soon for the encoding to be correct for the member.
7136///
7137class TypeStringCache {
7138 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7139 struct Entry {
7140 std::string Str; // The encoded TypeString for the type.
7141 enum Status State; // Information about the encoding in 'Str'.
7142 std::string Swapped; // A temporary place holder for a Recursive encoding
7143 // during the expansion of RecordType's members.
7144 };
7145 std::map<const IdentifierInfo *, struct Entry> Map;
7146 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7147 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7148public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007149 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007150 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7151 bool removeIncomplete(const IdentifierInfo *ID);
7152 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7153 bool IsRecursive);
7154 StringRef lookupStr(const IdentifierInfo *ID);
7155};
7156
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007157/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007158/// FieldEncoding is a helper for this ordering process.
7159class FieldEncoding {
7160 bool HasName;
7161 std::string Enc;
7162public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007163 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7164 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007165 bool operator<(const FieldEncoding &rhs) const {
7166 if (HasName != rhs.HasName) return HasName;
7167 return Enc < rhs.Enc;
7168 }
7169};
7170
Robert Lytton7d1db152013-08-19 09:46:39 +00007171class XCoreABIInfo : public DefaultABIInfo {
7172public:
7173 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007174 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7175 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007176};
7177
Robert Lyttond21e2d72014-03-03 13:45:29 +00007178class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007179 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007180public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007181 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007182 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007183 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7184 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007185};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007186
Robert Lytton2d196952013-10-11 10:29:34 +00007187} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007188
James Y Knight29b5f082016-02-24 02:59:33 +00007189// TODO: this implementation is likely now redundant with the default
7190// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007191Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7192 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007193 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007194
Robert Lytton2d196952013-10-11 10:29:34 +00007195 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007196 CharUnits SlotSize = CharUnits::fromQuantity(4);
7197 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007198
Robert Lytton2d196952013-10-11 10:29:34 +00007199 // Handle the argument.
7200 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007201 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007202 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7203 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7204 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007205 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007206
7207 Address Val = Address::invalid();
7208 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007209 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007210 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007211 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007212 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007213 llvm_unreachable("Unsupported ABI kind for va_arg");
7214 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007215 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7216 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007217 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007218 case ABIArgInfo::Extend:
7219 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007220 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7221 ArgSize = CharUnits::fromQuantity(
7222 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007223 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007224 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007225 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007226 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7227 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7228 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007229 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007230 }
Robert Lytton2d196952013-10-11 10:29:34 +00007231
7232 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007233 if (!ArgSize.isZero()) {
7234 llvm::Value *APN =
7235 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7236 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007237 }
John McCall7f416cc2015-09-08 08:05:57 +00007238
Robert Lytton2d196952013-10-11 10:29:34 +00007239 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007240}
Robert Lytton0e076492013-08-13 09:43:10 +00007241
Robert Lytton844aeeb2014-05-02 09:33:20 +00007242/// During the expansion of a RecordType, an incomplete TypeString is placed
7243/// into the cache as a means to identify and break recursion.
7244/// If there is a Recursive encoding in the cache, it is swapped out and will
7245/// be reinserted by removeIncomplete().
7246/// All other types of encoding should have been used rather than arriving here.
7247void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7248 std::string StubEnc) {
7249 if (!ID)
7250 return;
7251 Entry &E = Map[ID];
7252 assert( (E.Str.empty() || E.State == Recursive) &&
7253 "Incorrectly use of addIncomplete");
7254 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7255 E.Swapped.swap(E.Str); // swap out the Recursive
7256 E.Str.swap(StubEnc);
7257 E.State = Incomplete;
7258 ++IncompleteCount;
7259}
7260
7261/// Once the RecordType has been expanded, the temporary incomplete TypeString
7262/// must be removed from the cache.
7263/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7264/// Returns true if the RecordType was defined recursively.
7265bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7266 if (!ID)
7267 return false;
7268 auto I = Map.find(ID);
7269 assert(I != Map.end() && "Entry not present");
7270 Entry &E = I->second;
7271 assert( (E.State == Incomplete ||
7272 E.State == IncompleteUsed) &&
7273 "Entry must be an incomplete type");
7274 bool IsRecursive = false;
7275 if (E.State == IncompleteUsed) {
7276 // We made use of our Incomplete encoding, thus we are recursive.
7277 IsRecursive = true;
7278 --IncompleteUsedCount;
7279 }
7280 if (E.Swapped.empty())
7281 Map.erase(I);
7282 else {
7283 // Swap the Recursive back.
7284 E.Swapped.swap(E.Str);
7285 E.Swapped.clear();
7286 E.State = Recursive;
7287 }
7288 --IncompleteCount;
7289 return IsRecursive;
7290}
7291
7292/// Add the encoded TypeString to the cache only if it is NonRecursive or
7293/// Recursive (viz: all sub-members were expanded as fully as possible).
7294void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7295 bool IsRecursive) {
7296 if (!ID || IncompleteUsedCount)
7297 return; // No key or it is is an incomplete sub-type so don't add.
7298 Entry &E = Map[ID];
7299 if (IsRecursive && !E.Str.empty()) {
7300 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7301 "This is not the same Recursive entry");
7302 // The parent container was not recursive after all, so we could have used
7303 // this Recursive sub-member entry after all, but we assumed the worse when
7304 // we started viz: IncompleteCount!=0.
7305 return;
7306 }
7307 assert(E.Str.empty() && "Entry already present");
7308 E.Str = Str.str();
7309 E.State = IsRecursive? Recursive : NonRecursive;
7310}
7311
7312/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7313/// are recursively expanding a type (IncompleteCount != 0) and the cached
7314/// encoding is Recursive, return an empty StringRef.
7315StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7316 if (!ID)
7317 return StringRef(); // We have no key.
7318 auto I = Map.find(ID);
7319 if (I == Map.end())
7320 return StringRef(); // We have no encoding.
7321 Entry &E = I->second;
7322 if (E.State == Recursive && IncompleteCount)
7323 return StringRef(); // We don't use Recursive encodings for member types.
7324
7325 if (E.State == Incomplete) {
7326 // The incomplete type is being used to break out of recursion.
7327 E.State = IncompleteUsed;
7328 ++IncompleteUsedCount;
7329 }
7330 return E.Str.c_str();
7331}
7332
7333/// The XCore ABI includes a type information section that communicates symbol
7334/// type information to the linker. The linker uses this information to verify
7335/// safety/correctness of things such as array bound and pointers et al.
7336/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7337/// This type information (TypeString) is emitted into meta data for all global
7338/// symbols: definitions, declarations, functions & variables.
7339///
7340/// The TypeString carries type, qualifier, name, size & value details.
7341/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007342/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007343/// The output is tested by test/CodeGen/xcore-stringtype.c.
7344///
7345static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7346 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7347
7348/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7349void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7350 CodeGen::CodeGenModule &CGM) const {
7351 SmallStringEnc Enc;
7352 if (getTypeString(Enc, D, CGM, TSC)) {
7353 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007354 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7355 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007356 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7357 llvm::NamedMDNode *MD =
7358 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7359 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7360 }
7361}
7362
Xiuli Pan972bea82016-03-24 03:57:17 +00007363//===----------------------------------------------------------------------===//
7364// SPIR ABI Implementation
7365//===----------------------------------------------------------------------===//
7366
7367namespace {
7368class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7369public:
7370 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7371 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7372 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7373 CodeGen::CodeGenModule &M) const override;
7374};
7375} // End anonymous namespace.
7376
7377/// Emit SPIR specific metadata: OpenCL and SPIR version.
7378void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7379 CodeGen::CodeGenModule &CGM) const {
7380 assert(CGM.getLangOpts().OpenCL && "SPIR is only for OpenCL");
7381 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7382 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7383 llvm::Module &M = CGM.getModule();
7384 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7385 // opencl.spir.version named metadata.
7386 llvm::Metadata *SPIRVerElts[] = {
7387 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7388 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7389 llvm::NamedMDNode *SPIRVerMD =
7390 M.getOrInsertNamedMetadata("opencl.spir.version");
7391 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
7392 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7393 // opencl.ocl.version named metadata node.
7394 llvm::Metadata *OCLVerElts[] = {
7395 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7396 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7397 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7398 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7399 llvm::NamedMDNode *OCLVerMD =
7400 M.getOrInsertNamedMetadata("opencl.ocl.version");
7401 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7402}
7403
Robert Lytton844aeeb2014-05-02 09:33:20 +00007404static bool appendType(SmallStringEnc &Enc, QualType QType,
7405 const CodeGen::CodeGenModule &CGM,
7406 TypeStringCache &TSC);
7407
7408/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007409/// Builds a SmallVector containing the encoded field types in declaration
7410/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007411static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7412 const RecordDecl *RD,
7413 const CodeGen::CodeGenModule &CGM,
7414 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007415 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007416 SmallStringEnc Enc;
7417 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007418 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007419 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007420 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007421 Enc += "b(";
7422 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007423 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007424 Enc += ':';
7425 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007426 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007427 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007428 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007429 Enc += ')';
7430 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007431 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007432 }
7433 return true;
7434}
7435
7436/// Appends structure and union types to Enc and adds encoding to cache.
7437/// Recursively calls appendType (via extractFieldType) for each field.
7438/// Union types have their fields ordered according to the ABI.
7439static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7440 const CodeGen::CodeGenModule &CGM,
7441 TypeStringCache &TSC, const IdentifierInfo *ID) {
7442 // Append the cached TypeString if we have one.
7443 StringRef TypeString = TSC.lookupStr(ID);
7444 if (!TypeString.empty()) {
7445 Enc += TypeString;
7446 return true;
7447 }
7448
7449 // Start to emit an incomplete TypeString.
7450 size_t Start = Enc.size();
7451 Enc += (RT->isUnionType()? 'u' : 's');
7452 Enc += '(';
7453 if (ID)
7454 Enc += ID->getName();
7455 Enc += "){";
7456
7457 // We collect all encoded fields and order as necessary.
7458 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007459 const RecordDecl *RD = RT->getDecl()->getDefinition();
7460 if (RD && !RD->field_empty()) {
7461 // An incomplete TypeString stub is placed in the cache for this RecordType
7462 // so that recursive calls to this RecordType will use it whilst building a
7463 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007464 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007465 std::string StubEnc(Enc.substr(Start).str());
7466 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7467 TSC.addIncomplete(ID, std::move(StubEnc));
7468 if (!extractFieldType(FE, RD, CGM, TSC)) {
7469 (void) TSC.removeIncomplete(ID);
7470 return false;
7471 }
7472 IsRecursive = TSC.removeIncomplete(ID);
7473 // The ABI requires unions to be sorted but not structures.
7474 // See FieldEncoding::operator< for sort algorithm.
7475 if (RT->isUnionType())
7476 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007477 // We can now complete the TypeString.
7478 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007479 for (unsigned I = 0; I != E; ++I) {
7480 if (I)
7481 Enc += ',';
7482 Enc += FE[I].str();
7483 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007484 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007485 Enc += '}';
7486 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7487 return true;
7488}
7489
7490/// Appends enum types to Enc and adds the encoding to the cache.
7491static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7492 TypeStringCache &TSC,
7493 const IdentifierInfo *ID) {
7494 // Append the cached TypeString if we have one.
7495 StringRef TypeString = TSC.lookupStr(ID);
7496 if (!TypeString.empty()) {
7497 Enc += TypeString;
7498 return true;
7499 }
7500
7501 size_t Start = Enc.size();
7502 Enc += "e(";
7503 if (ID)
7504 Enc += ID->getName();
7505 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007506
7507 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007508 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007509 SmallVector<FieldEncoding, 16> FE;
7510 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7511 ++I) {
7512 SmallStringEnc EnumEnc;
7513 EnumEnc += "m(";
7514 EnumEnc += I->getName();
7515 EnumEnc += "){";
7516 I->getInitVal().toString(EnumEnc);
7517 EnumEnc += '}';
7518 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7519 }
7520 std::sort(FE.begin(), FE.end());
7521 unsigned E = FE.size();
7522 for (unsigned I = 0; I != E; ++I) {
7523 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007524 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007525 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007526 }
7527 }
7528 Enc += '}';
7529 TSC.addIfComplete(ID, Enc.substr(Start), false);
7530 return true;
7531}
7532
7533/// Appends type's qualifier to Enc.
7534/// This is done prior to appending the type's encoding.
7535static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7536 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007537 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007538 int Lookup = 0;
7539 if (QT.isConstQualified())
7540 Lookup += 1<<0;
7541 if (QT.isRestrictQualified())
7542 Lookup += 1<<1;
7543 if (QT.isVolatileQualified())
7544 Lookup += 1<<2;
7545 Enc += Table[Lookup];
7546}
7547
7548/// Appends built-in types to Enc.
7549static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7550 const char *EncType;
7551 switch (BT->getKind()) {
7552 case BuiltinType::Void:
7553 EncType = "0";
7554 break;
7555 case BuiltinType::Bool:
7556 EncType = "b";
7557 break;
7558 case BuiltinType::Char_U:
7559 EncType = "uc";
7560 break;
7561 case BuiltinType::UChar:
7562 EncType = "uc";
7563 break;
7564 case BuiltinType::SChar:
7565 EncType = "sc";
7566 break;
7567 case BuiltinType::UShort:
7568 EncType = "us";
7569 break;
7570 case BuiltinType::Short:
7571 EncType = "ss";
7572 break;
7573 case BuiltinType::UInt:
7574 EncType = "ui";
7575 break;
7576 case BuiltinType::Int:
7577 EncType = "si";
7578 break;
7579 case BuiltinType::ULong:
7580 EncType = "ul";
7581 break;
7582 case BuiltinType::Long:
7583 EncType = "sl";
7584 break;
7585 case BuiltinType::ULongLong:
7586 EncType = "ull";
7587 break;
7588 case BuiltinType::LongLong:
7589 EncType = "sll";
7590 break;
7591 case BuiltinType::Float:
7592 EncType = "ft";
7593 break;
7594 case BuiltinType::Double:
7595 EncType = "d";
7596 break;
7597 case BuiltinType::LongDouble:
7598 EncType = "ld";
7599 break;
7600 default:
7601 return false;
7602 }
7603 Enc += EncType;
7604 return true;
7605}
7606
7607/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7608static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7609 const CodeGen::CodeGenModule &CGM,
7610 TypeStringCache &TSC) {
7611 Enc += "p(";
7612 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7613 return false;
7614 Enc += ')';
7615 return true;
7616}
7617
7618/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007619static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7620 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007621 const CodeGen::CodeGenModule &CGM,
7622 TypeStringCache &TSC, StringRef NoSizeEnc) {
7623 if (AT->getSizeModifier() != ArrayType::Normal)
7624 return false;
7625 Enc += "a(";
7626 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7627 CAT->getSize().toStringUnsigned(Enc);
7628 else
7629 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7630 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007631 // The Qualifiers should be attached to the type rather than the array.
7632 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007633 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7634 return false;
7635 Enc += ')';
7636 return true;
7637}
7638
7639/// Appends a function encoding to Enc, calling appendType for the return type
7640/// and the arguments.
7641static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7642 const CodeGen::CodeGenModule &CGM,
7643 TypeStringCache &TSC) {
7644 Enc += "f{";
7645 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7646 return false;
7647 Enc += "}(";
7648 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7649 // N.B. we are only interested in the adjusted param types.
7650 auto I = FPT->param_type_begin();
7651 auto E = FPT->param_type_end();
7652 if (I != E) {
7653 do {
7654 if (!appendType(Enc, *I, CGM, TSC))
7655 return false;
7656 ++I;
7657 if (I != E)
7658 Enc += ',';
7659 } while (I != E);
7660 if (FPT->isVariadic())
7661 Enc += ",va";
7662 } else {
7663 if (FPT->isVariadic())
7664 Enc += "va";
7665 else
7666 Enc += '0';
7667 }
7668 }
7669 Enc += ')';
7670 return true;
7671}
7672
7673/// Handles the type's qualifier before dispatching a call to handle specific
7674/// type encodings.
7675static bool appendType(SmallStringEnc &Enc, QualType QType,
7676 const CodeGen::CodeGenModule &CGM,
7677 TypeStringCache &TSC) {
7678
7679 QualType QT = QType.getCanonicalType();
7680
Robert Lytton6adb20f2014-06-05 09:06:21 +00007681 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7682 // The Qualifiers should be attached to the type rather than the array.
7683 // Thus we don't call appendQualifier() here.
7684 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7685
Robert Lytton844aeeb2014-05-02 09:33:20 +00007686 appendQualifier(Enc, QT);
7687
7688 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7689 return appendBuiltinType(Enc, BT);
7690
Robert Lytton844aeeb2014-05-02 09:33:20 +00007691 if (const PointerType *PT = QT->getAs<PointerType>())
7692 return appendPointerType(Enc, PT, CGM, TSC);
7693
7694 if (const EnumType *ET = QT->getAs<EnumType>())
7695 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7696
7697 if (const RecordType *RT = QT->getAsStructureType())
7698 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7699
7700 if (const RecordType *RT = QT->getAsUnionType())
7701 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7702
7703 if (const FunctionType *FT = QT->getAs<FunctionType>())
7704 return appendFunctionType(Enc, FT, CGM, TSC);
7705
7706 return false;
7707}
7708
7709static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7710 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7711 if (!D)
7712 return false;
7713
7714 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7715 if (FD->getLanguageLinkage() != CLanguageLinkage)
7716 return false;
7717 return appendType(Enc, FD->getType(), CGM, TSC);
7718 }
7719
7720 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7721 if (VD->getLanguageLinkage() != CLanguageLinkage)
7722 return false;
7723 QualType QT = VD->getType().getCanonicalType();
7724 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7725 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007726 // The Qualifiers should be attached to the type rather than the array.
7727 // Thus we don't call appendQualifier() here.
7728 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007729 }
7730 return appendType(Enc, QT, CGM, TSC);
7731 }
7732 return false;
7733}
7734
7735
Robert Lytton0e076492013-08-13 09:43:10 +00007736//===----------------------------------------------------------------------===//
7737// Driver code
7738//===----------------------------------------------------------------------===//
7739
Rafael Espindola9f834732014-09-19 01:54:22 +00007740const llvm::Triple &CodeGenModule::getTriple() const {
7741 return getTarget().getTriple();
7742}
7743
7744bool CodeGenModule::supportsCOMDAT() const {
7745 return !getTriple().isOSBinFormatMachO();
7746}
7747
Chris Lattner2b037972010-07-29 02:01:43 +00007748const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007749 if (TheTargetCodeGenInfo)
7750 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007751
John McCallc8e01702013-04-16 22:48:15 +00007752 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007753 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007754 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007755 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007756
Derek Schuff09338a22012-09-06 17:37:28 +00007757 case llvm::Triple::le32:
7758 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007759 case llvm::Triple::mips:
7760 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007761 if (Triple.getOS() == llvm::Triple::NaCl)
7762 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007763 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7764
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007765 case llvm::Triple::mips64:
7766 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007767 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7768
Tim Northover25e8a672014-05-24 12:51:25 +00007769 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007770 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007771 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007772 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007773 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007774
Tim Northover573cbee2014-05-24 12:52:07 +00007775 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007776 }
7777
Dan Gohmanc2853072015-09-03 22:51:53 +00007778 case llvm::Triple::wasm32:
7779 case llvm::Triple::wasm64:
7780 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7781
Daniel Dunbard59655c2009-09-12 00:59:49 +00007782 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007783 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007784 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007785 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007786 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007787 if (Triple.getOS() == llvm::Triple::Win32) {
7788 TheTargetCodeGenInfo =
7789 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7790 return *TheTargetCodeGenInfo;
7791 }
7792
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007793 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Tim Northover5627d392015-10-30 16:30:45 +00007794 StringRef ABIStr = getTarget().getABI();
7795 if (ABIStr == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007796 Kind = ARMABIInfo::APCS;
Tim Northover5627d392015-10-30 16:30:45 +00007797 else if (ABIStr == "aapcs16")
7798 Kind = ARMABIInfo::AAPCS16_VFP;
David Tweed8f676532012-10-25 13:33:01 +00007799 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007800 (CodeGenOpts.FloatABI != "soft" &&
7801 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007802 Kind = ARMABIInfo::AAPCS_VFP;
7803
Derek Schuff71658bd2015-01-29 00:47:04 +00007804 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007805 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007806
John McCallea8d8bb2010-03-11 00:10:12 +00007807 case llvm::Triple::ppc:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00007808 return *(TheTargetCodeGenInfo =
7809 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007810 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007811 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007812 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007813 if (getTarget().getABI() == "elfv2")
7814 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007815 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007816
Ulrich Weigandb7122372014-07-21 00:48:09 +00007817 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007818 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007819 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007820 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007821 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007822 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007823 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007824 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007825 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007826 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007827
Ulrich Weigandb7122372014-07-21 00:48:09 +00007828 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007829 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007830 }
John McCallea8d8bb2010-03-11 00:10:12 +00007831
Peter Collingbournec947aae2012-05-20 23:28:41 +00007832 case llvm::Triple::nvptx:
7833 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007834 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007835
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007836 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007837 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007838
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007839 case llvm::Triple::systemz: {
7840 bool HasVector = getTarget().getABI() == "vector";
7841 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7842 HasVector));
7843 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007844
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007845 case llvm::Triple::tce:
7846 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7847
Eli Friedman33465822011-07-08 23:31:17 +00007848 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007849 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007850 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007851 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007852 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007853
John McCall1fe2a8c2013-06-18 02:46:29 +00007854 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007855 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007856 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Eric Christopher7565e0d2015-05-29 23:09:49 +00007857 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007858 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007859 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007860 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00007861 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7862 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007863 }
Eli Friedman33465822011-07-08 23:31:17 +00007864 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007865
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007866 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007867 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007868 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7869 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007870 X86AVXABILevel::None);
7871
Chris Lattner04dc9572010-08-31 16:44:54 +00007872 switch (Triple.getOS()) {
7873 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007874 return *(TheTargetCodeGenInfo =
7875 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007876 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007877 return *(TheTargetCodeGenInfo =
7878 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007879 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007880 return *(TheTargetCodeGenInfo =
7881 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007882 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007883 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007884 case llvm::Triple::hexagon:
7885 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00007886 case llvm::Triple::lanai:
7887 return *(TheTargetCodeGenInfo = new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007888 case llvm::Triple::r600:
7889 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007890 case llvm::Triple::amdgcn:
7891 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007892 case llvm::Triple::sparcv9:
7893 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007894 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007895 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00007896 case llvm::Triple::spir:
7897 case llvm::Triple::spir64:
7898 return *(TheTargetCodeGenInfo = new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007899 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007900}