blob: 9170d5884f64f50acb50406baad1bd91316f27cc [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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000030
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();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004123 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004124 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004125 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4126 // so make sure to widen it explicitly.
4127 if (const VectorType *VT = Base->getAs<VectorType>()) {
4128 QualType EltTy = VT->getElementType();
4129 unsigned NumElements =
4130 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4131 Base = getContext()
4132 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4133 .getTypePtr();
4134 }
4135 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004136
4137 if (Base->isVectorType() != TyPtr->isVectorType() ||
4138 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4139 return false;
4140 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004141 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4142}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004143
Reid Klecknere9f6a712014-10-31 17:10:41 +00004144bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4145 // Homogeneous aggregates for ELFv2 must have base types of float,
4146 // double, long double, or 128-bit vectors.
4147 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4148 if (BT->getKind() == BuiltinType::Float ||
4149 BT->getKind() == BuiltinType::Double ||
4150 BT->getKind() == BuiltinType::LongDouble)
4151 return true;
4152 }
4153 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004154 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004155 return true;
4156 }
4157 return false;
4158}
4159
4160bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4161 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004162 // Vector types require one register, floating point types require one
4163 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004164 uint32_t NumRegs =
4165 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004166
4167 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004168 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004169}
4170
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004171ABIArgInfo
4172PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004173 Ty = useFirstFieldIfTransparentUnion(Ty);
4174
Bill Schmidt90b22c92012-11-27 02:46:43 +00004175 if (Ty->isAnyComplexType())
4176 return ABIArgInfo::getDirect();
4177
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004178 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4179 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004180 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004181 uint64_t Size = getContext().getTypeSize(Ty);
4182 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004183 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004184 else if (Size < 128) {
4185 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4186 return ABIArgInfo::getDirect(CoerceTy);
4187 }
4188 }
4189
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004190 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004191 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004192 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004193
John McCall7f416cc2015-09-08 08:05:57 +00004194 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4195 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004196
4197 // ELFv2 homogeneous aggregates are passed as array types.
4198 const Type *Base = nullptr;
4199 uint64_t Members = 0;
4200 if (Kind == ELFv2 &&
4201 isHomogeneousAggregate(Ty, Base, Members)) {
4202 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4203 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4204 return ABIArgInfo::getDirect(CoerceTy);
4205 }
4206
Ulrich Weigand601957f2014-07-21 00:56:36 +00004207 // If an aggregate may end up fully in registers, we do not
4208 // use the ByVal method, but pass the aggregate as array.
4209 // This is usually beneficial since we avoid forcing the
4210 // back-end to store the argument to memory.
4211 uint64_t Bits = getContext().getTypeSize(Ty);
4212 if (Bits > 0 && Bits <= 8 * GPRBits) {
4213 llvm::Type *CoerceTy;
4214
4215 // Types up to 8 bytes are passed as integer type (which will be
4216 // properly aligned in the argument save area doubleword).
4217 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004218 CoerceTy =
4219 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004220 // Larger types are passed as arrays, with the base type selected
4221 // according to the required alignment in the save area.
4222 else {
4223 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004224 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004225 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4226 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4227 }
4228
4229 return ABIArgInfo::getDirect(CoerceTy);
4230 }
4231
Ulrich Weigandb7122372014-07-21 00:48:09 +00004232 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004233 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4234 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004235 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004236 }
4237
4238 return (isPromotableTypeForABI(Ty) ?
4239 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4240}
4241
4242ABIArgInfo
4243PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4244 if (RetTy->isVoidType())
4245 return ABIArgInfo::getIgnore();
4246
Bill Schmidta3d121c2012-12-17 04:20:17 +00004247 if (RetTy->isAnyComplexType())
4248 return ABIArgInfo::getDirect();
4249
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004250 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4251 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004252 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004253 uint64_t Size = getContext().getTypeSize(RetTy);
4254 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004255 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004256 else if (Size < 128) {
4257 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4258 return ABIArgInfo::getDirect(CoerceTy);
4259 }
4260 }
4261
Ulrich Weigandb7122372014-07-21 00:48:09 +00004262 if (isAggregateTypeForABI(RetTy)) {
4263 // ELFv2 homogeneous aggregates are returned as array types.
4264 const Type *Base = nullptr;
4265 uint64_t Members = 0;
4266 if (Kind == ELFv2 &&
4267 isHomogeneousAggregate(RetTy, Base, Members)) {
4268 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4269 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4270 return ABIArgInfo::getDirect(CoerceTy);
4271 }
4272
4273 // ELFv2 small aggregates are returned in up to two registers.
4274 uint64_t Bits = getContext().getTypeSize(RetTy);
4275 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4276 if (Bits == 0)
4277 return ABIArgInfo::getIgnore();
4278
4279 llvm::Type *CoerceTy;
4280 if (Bits > GPRBits) {
4281 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004282 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004283 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004284 CoerceTy =
4285 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004286 return ABIArgInfo::getDirect(CoerceTy);
4287 }
4288
4289 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004290 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004291 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004292
4293 return (isPromotableTypeForABI(RetTy) ?
4294 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4295}
4296
Bill Schmidt25cb3492012-10-03 19:18:57 +00004297// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004298Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4299 QualType Ty) const {
4300 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4301 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004302
John McCall7f416cc2015-09-08 08:05:57 +00004303 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004304
Bill Schmidt924c4782013-01-14 17:45:36 +00004305 // If we have a complex type and the base type is smaller than 8 bytes,
4306 // the ABI calls for the real and imaginary parts to be right-adjusted
4307 // in separate doublewords. However, Clang expects us to produce a
4308 // pointer to a structure with the two parts packed tightly. So generate
4309 // loads of the real and imaginary parts relative to the va_list pointer,
4310 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004311 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4312 CharUnits EltSize = TypeInfo.first / 2;
4313 if (EltSize < SlotSize) {
4314 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4315 SlotSize * 2, SlotSize,
4316 SlotSize, /*AllowHigher*/ true);
4317
4318 Address RealAddr = Addr;
4319 Address ImagAddr = RealAddr;
4320 if (CGF.CGM.getDataLayout().isBigEndian()) {
4321 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4322 SlotSize - EltSize);
4323 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4324 2 * SlotSize - EltSize);
4325 } else {
4326 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4327 }
4328
4329 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4330 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4331 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4332 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4333 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4334
4335 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4336 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4337 /*init*/ true);
4338 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004339 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004340 }
4341
John McCall7f416cc2015-09-08 08:05:57 +00004342 // Otherwise, just use the general rule.
4343 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4344 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004345}
4346
4347static bool
4348PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4349 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004350 // This is calculated from the LLVM and GCC tables and verified
4351 // against gcc output. AFAIK all ABIs use the same encoding.
4352
4353 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4354
4355 llvm::IntegerType *i8 = CGF.Int8Ty;
4356 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4357 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4358 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4359
4360 // 0-31: r0-31, the 8-byte general-purpose registers
4361 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4362
4363 // 32-63: fp0-31, the 8-byte floating-point registers
4364 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4365
4366 // 64-76 are various 4-byte special-purpose registers:
4367 // 64: mq
4368 // 65: lr
4369 // 66: ctr
4370 // 67: ap
4371 // 68-75 cr0-7
4372 // 76: xer
4373 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4374
4375 // 77-108: v0-31, the 16-byte vector registers
4376 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4377
4378 // 109: vrsave
4379 // 110: vscr
4380 // 111: spe_acc
4381 // 112: spefscr
4382 // 113: sfp
4383 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4384
4385 return false;
4386}
John McCallea8d8bb2010-03-11 00:10:12 +00004387
Bill Schmidt25cb3492012-10-03 19:18:57 +00004388bool
4389PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4390 CodeGen::CodeGenFunction &CGF,
4391 llvm::Value *Address) const {
4392
4393 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4394}
4395
4396bool
4397PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4398 llvm::Value *Address) const {
4399
4400 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4401}
4402
Chris Lattner0cf24192010-06-28 20:05:43 +00004403//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004404// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004405//===----------------------------------------------------------------------===//
4406
4407namespace {
4408
John McCall12f23522016-04-04 18:33:08 +00004409class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004410public:
4411 enum ABIKind {
4412 AAPCS = 0,
4413 DarwinPCS
4414 };
4415
4416private:
4417 ABIKind Kind;
4418
4419public:
John McCall12f23522016-04-04 18:33:08 +00004420 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4421 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004422
4423private:
4424 ABIKind getABIKind() const { return Kind; }
4425 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4426
4427 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004428 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004429 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4430 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4431 uint64_t Members) const override;
4432
Tim Northovera2ee4332014-03-29 15:09:45 +00004433 bool isIllegalVectorType(QualType Ty) const;
4434
David Blaikie1cbb9712014-11-14 19:09:44 +00004435 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004436 if (!getCXXABI().classifyReturnType(FI))
4437 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004438
Tim Northoverb047bfa2014-11-27 21:02:49 +00004439 for (auto &it : FI.arguments())
4440 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004441 }
4442
John McCall7f416cc2015-09-08 08:05:57 +00004443 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4444 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004445
John McCall7f416cc2015-09-08 08:05:57 +00004446 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4447 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004448
John McCall7f416cc2015-09-08 08:05:57 +00004449 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4450 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004451 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4452 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4453 }
John McCall12f23522016-04-04 18:33:08 +00004454
4455 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4456 ArrayRef<llvm::Type*> scalars,
4457 bool asReturnValue) const override {
4458 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4459 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004460};
4461
Tim Northover573cbee2014-05-24 12:52:07 +00004462class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004463public:
Tim Northover573cbee2014-05-24 12:52:07 +00004464 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4465 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004466
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004467 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004468 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4469 }
4470
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004471 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4472 return 31;
4473 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004474
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004475 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004476};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004477}
Tim Northovera2ee4332014-03-29 15:09:45 +00004478
Tim Northoverb047bfa2014-11-27 21:02:49 +00004479ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004480 Ty = useFirstFieldIfTransparentUnion(Ty);
4481
Tim Northovera2ee4332014-03-29 15:09:45 +00004482 // Handle illegal vector types here.
4483 if (isIllegalVectorType(Ty)) {
4484 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004485 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004486 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004487 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4488 return ABIArgInfo::getDirect(ResType);
4489 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004490 if (Size <= 32) {
4491 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004492 return ABIArgInfo::getDirect(ResType);
4493 }
4494 if (Size == 64) {
4495 llvm::Type *ResType =
4496 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004497 return ABIArgInfo::getDirect(ResType);
4498 }
4499 if (Size == 128) {
4500 llvm::Type *ResType =
4501 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004502 return ABIArgInfo::getDirect(ResType);
4503 }
John McCall7f416cc2015-09-08 08:05:57 +00004504 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004505 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004506
4507 if (!isAggregateTypeForABI(Ty)) {
4508 // Treat an enum type as its underlying type.
4509 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4510 Ty = EnumTy->getDecl()->getIntegerType();
4511
Tim Northovera2ee4332014-03-29 15:09:45 +00004512 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4513 ? ABIArgInfo::getExtend()
4514 : ABIArgInfo::getDirect());
4515 }
4516
4517 // Structures with either a non-trivial destructor or a non-trivial
4518 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004519 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004520 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4521 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004522 }
4523
4524 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4525 // elsewhere for GNU compatibility.
4526 if (isEmptyRecord(getContext(), Ty, true)) {
4527 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4528 return ABIArgInfo::getIgnore();
4529
Tim Northovera2ee4332014-03-29 15:09:45 +00004530 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4531 }
4532
4533 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004534 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004535 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004536 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004537 return ABIArgInfo::getDirect(
4538 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004539 }
4540
4541 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4542 uint64_t Size = getContext().getTypeSize(Ty);
4543 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004544 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004545 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004546
Tim Northovera2ee4332014-03-29 15:09:45 +00004547 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4548 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004549 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004550 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4551 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4552 }
4553 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4554 }
4555
John McCall7f416cc2015-09-08 08:05:57 +00004556 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004557}
4558
Tim Northover573cbee2014-05-24 12:52:07 +00004559ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004560 if (RetTy->isVoidType())
4561 return ABIArgInfo::getIgnore();
4562
4563 // Large vector types should be returned via memory.
4564 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004565 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004566
4567 if (!isAggregateTypeForABI(RetTy)) {
4568 // Treat an enum type as its underlying type.
4569 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4570 RetTy = EnumTy->getDecl()->getIntegerType();
4571
Tim Northover4dab6982014-04-18 13:46:08 +00004572 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4573 ? ABIArgInfo::getExtend()
4574 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004575 }
4576
Tim Northovera2ee4332014-03-29 15:09:45 +00004577 if (isEmptyRecord(getContext(), RetTy, true))
4578 return ABIArgInfo::getIgnore();
4579
Craig Topper8a13c412014-05-21 05:09:00 +00004580 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004581 uint64_t Members = 0;
4582 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004583 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4584 return ABIArgInfo::getDirect();
4585
4586 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4587 uint64_t Size = getContext().getTypeSize(RetTy);
4588 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004589 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004590 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004591
4592 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4593 // For aggregates with 16-byte alignment, we use i128.
4594 if (Alignment < 128 && Size == 128) {
4595 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4596 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4597 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004598 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4599 }
4600
John McCall7f416cc2015-09-08 08:05:57 +00004601 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004602}
4603
Tim Northover573cbee2014-05-24 12:52:07 +00004604/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4605bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004606 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4607 // Check whether VT is legal.
4608 unsigned NumElements = VT->getNumElements();
4609 uint64_t Size = getContext().getTypeSize(VT);
4610 // NumElements should be power of 2 between 1 and 16.
4611 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4612 return true;
4613 return Size != 64 && (Size != 128 || NumElements == 1);
4614 }
4615 return false;
4616}
4617
Reid Klecknere9f6a712014-10-31 17:10:41 +00004618bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4619 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4620 // point type or a short-vector type. This is the same as the 32-bit ABI,
4621 // but with the difference that any floating-point type is allowed,
4622 // including __fp16.
4623 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4624 if (BT->isFloatingPoint())
4625 return true;
4626 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4627 unsigned VecSize = getContext().getTypeSize(VT);
4628 if (VecSize == 64 || VecSize == 128)
4629 return true;
4630 }
4631 return false;
4632}
4633
4634bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4635 uint64_t Members) const {
4636 return Members <= 4;
4637}
4638
John McCall7f416cc2015-09-08 08:05:57 +00004639Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004640 QualType Ty,
4641 CodeGenFunction &CGF) const {
4642 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004643 bool IsIndirect = AI.isIndirect();
4644
Tim Northoverb047bfa2014-11-27 21:02:49 +00004645 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4646 if (IsIndirect)
4647 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4648 else if (AI.getCoerceToType())
4649 BaseTy = AI.getCoerceToType();
4650
4651 unsigned NumRegs = 1;
4652 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4653 BaseTy = ArrTy->getElementType();
4654 NumRegs = ArrTy->getNumElements();
4655 }
4656 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4657
Tim Northovera2ee4332014-03-29 15:09:45 +00004658 // The AArch64 va_list type and handling is specified in the Procedure Call
4659 // Standard, section B.4:
4660 //
4661 // struct {
4662 // void *__stack;
4663 // void *__gr_top;
4664 // void *__vr_top;
4665 // int __gr_offs;
4666 // int __vr_offs;
4667 // };
4668
4669 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4670 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4671 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4672 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004673
John McCall7f416cc2015-09-08 08:05:57 +00004674 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4675 CharUnits TyAlign = TyInfo.second;
4676
4677 Address reg_offs_p = Address::invalid();
4678 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004679 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004680 CharUnits reg_top_offset;
4681 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004682 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004683 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004684 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004685 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4686 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004687 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4688 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004689 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004690 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004691 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004692 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004693 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004694 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4695 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004696 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4697 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004698 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004699 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004700 }
4701
4702 //=======================================
4703 // Find out where argument was passed
4704 //=======================================
4705
4706 // If reg_offs >= 0 we're already using the stack for this type of
4707 // argument. We don't want to keep updating reg_offs (in case it overflows,
4708 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4709 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004710 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004711 UsingStack = CGF.Builder.CreateICmpSGE(
4712 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4713
4714 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4715
4716 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004717 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004718 CGF.EmitBlock(MaybeRegBlock);
4719
4720 // Integer arguments may need to correct register alignment (for example a
4721 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4722 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004723 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4724 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004725
4726 reg_offs = CGF.Builder.CreateAdd(
4727 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4728 "align_regoffs");
4729 reg_offs = CGF.Builder.CreateAnd(
4730 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4731 "aligned_regoffs");
4732 }
4733
4734 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004735 // The fact that this is done unconditionally reflects the fact that
4736 // allocating an argument to the stack also uses up all the remaining
4737 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004738 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004739 NewOffset = CGF.Builder.CreateAdd(
4740 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4741 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4742
4743 // Now we're in a position to decide whether this argument really was in
4744 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004745 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004746 InRegs = CGF.Builder.CreateICmpSLE(
4747 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4748
4749 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4750
4751 //=======================================
4752 // Argument was in registers
4753 //=======================================
4754
4755 // Now we emit the code for if the argument was originally passed in
4756 // registers. First start the appropriate block:
4757 CGF.EmitBlock(InRegBlock);
4758
John McCall7f416cc2015-09-08 08:05:57 +00004759 llvm::Value *reg_top = nullptr;
4760 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4761 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004762 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004763 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4764 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4765 Address RegAddr = Address::invalid();
4766 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004767
4768 if (IsIndirect) {
4769 // If it's been passed indirectly (actually a struct), whatever we find from
4770 // stored registers or on the stack will actually be a struct **.
4771 MemTy = llvm::PointerType::getUnqual(MemTy);
4772 }
4773
Craig Topper8a13c412014-05-21 05:09:00 +00004774 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004775 uint64_t NumMembers = 0;
4776 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004777 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004778 // Homogeneous aggregates passed in registers will have their elements split
4779 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4780 // qN+1, ...). We reload and store into a temporary local variable
4781 // contiguously.
4782 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004783 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004784 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4785 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004786 Address Tmp = CGF.CreateTempAlloca(HFATy,
4787 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004788
John McCall7f416cc2015-09-08 08:05:57 +00004789 // On big-endian platforms, the value will be right-aligned in its slot.
4790 int Offset = 0;
4791 if (CGF.CGM.getDataLayout().isBigEndian() &&
4792 BaseTyInfo.first.getQuantity() < 16)
4793 Offset = 16 - BaseTyInfo.first.getQuantity();
4794
Tim Northovera2ee4332014-03-29 15:09:45 +00004795 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004796 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4797 Address LoadAddr =
4798 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4799 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4800
4801 Address StoreAddr =
4802 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004803
4804 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4805 CGF.Builder.CreateStore(Elem, StoreAddr);
4806 }
4807
John McCall7f416cc2015-09-08 08:05:57 +00004808 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004809 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004810 // Otherwise the object is contiguous in memory.
4811
4812 // It might be right-aligned in its slot.
4813 CharUnits SlotSize = BaseAddr.getAlignment();
4814 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004815 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004816 TyInfo.first < SlotSize) {
4817 CharUnits Offset = SlotSize - TyInfo.first;
4818 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004819 }
4820
John McCall7f416cc2015-09-08 08:05:57 +00004821 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004822 }
4823
4824 CGF.EmitBranch(ContBlock);
4825
4826 //=======================================
4827 // Argument was on the stack
4828 //=======================================
4829 CGF.EmitBlock(OnStackBlock);
4830
John McCall7f416cc2015-09-08 08:05:57 +00004831 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4832 CharUnits::Zero(), "stack_p");
4833 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004834
John McCall7f416cc2015-09-08 08:05:57 +00004835 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004836 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004837 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4838 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004839
John McCall7f416cc2015-09-08 08:05:57 +00004840 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004841
John McCall7f416cc2015-09-08 08:05:57 +00004842 OnStackPtr = CGF.Builder.CreateAdd(
4843 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004844 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004845 OnStackPtr = CGF.Builder.CreateAnd(
4846 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004847 "align_stack");
4848
John McCall7f416cc2015-09-08 08:05:57 +00004849 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004850 }
John McCall7f416cc2015-09-08 08:05:57 +00004851 Address OnStackAddr(OnStackPtr,
4852 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004853
John McCall7f416cc2015-09-08 08:05:57 +00004854 // All stack slots are multiples of 8 bytes.
4855 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4856 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004857 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004858 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004859 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004860 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004861
John McCall7f416cc2015-09-08 08:05:57 +00004862 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004863 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004864 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004865
4866 // Write the new value of __stack for the next call to va_arg
4867 CGF.Builder.CreateStore(NewStack, stack_p);
4868
4869 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004870 TyInfo.first < StackSlotSize) {
4871 CharUnits Offset = StackSlotSize - TyInfo.first;
4872 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004873 }
4874
John McCall7f416cc2015-09-08 08:05:57 +00004875 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004876
4877 CGF.EmitBranch(ContBlock);
4878
4879 //=======================================
4880 // Tidy up
4881 //=======================================
4882 CGF.EmitBlock(ContBlock);
4883
John McCall7f416cc2015-09-08 08:05:57 +00004884 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4885 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004886
4887 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004888 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4889 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004890
4891 return ResAddr;
4892}
4893
John McCall7f416cc2015-09-08 08:05:57 +00004894Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4895 CodeGenFunction &CGF) const {
4896 // The backend's lowering doesn't support va_arg for aggregates or
4897 // illegal vector types. Lower VAArg here for these cases and use
4898 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004899 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00004900 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004901
John McCall7f416cc2015-09-08 08:05:57 +00004902 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004903
John McCall7f416cc2015-09-08 08:05:57 +00004904 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004905 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004906 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4907 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4908 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004909 }
4910
John McCall7f416cc2015-09-08 08:05:57 +00004911 // The size of the actual thing passed, which might end up just
4912 // being a pointer for indirect types.
4913 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4914
4915 // Arguments bigger than 16 bytes which aren't homogeneous
4916 // aggregates should be passed indirectly.
4917 bool IsIndirect = false;
4918 if (TyInfo.first.getQuantity() > 16) {
4919 const Type *Base = nullptr;
4920 uint64_t Members = 0;
4921 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004922 }
4923
John McCall7f416cc2015-09-08 08:05:57 +00004924 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4925 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004926}
4927
4928//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004929// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004930//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004931
4932namespace {
4933
John McCall12f23522016-04-04 18:33:08 +00004934class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004935public:
4936 enum ABIKind {
4937 APCS = 0,
4938 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004939 AAPCS_VFP = 2,
4940 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004941 };
4942
4943private:
4944 ABIKind Kind;
4945
4946public:
John McCall12f23522016-04-04 18:33:08 +00004947 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
4948 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004949 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004950 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004951
John McCall3480ef22011-08-30 01:42:09 +00004952 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004953 switch (getTarget().getTriple().getEnvironment()) {
4954 case llvm::Triple::Android:
4955 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004956 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004957 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004958 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004959 return true;
4960 default:
4961 return false;
4962 }
John McCall3480ef22011-08-30 01:42:09 +00004963 }
4964
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004965 bool isEABIHF() const {
4966 switch (getTarget().getTriple().getEnvironment()) {
4967 case llvm::Triple::EABIHF:
4968 case llvm::Triple::GNUEABIHF:
4969 return true;
4970 default:
4971 return false;
4972 }
4973 }
4974
Daniel Dunbar020daa92009-09-12 01:00:39 +00004975 ABIKind getABIKind() const { return Kind; }
4976
Tim Northovera484bc02013-10-01 14:34:25 +00004977private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004978 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004979 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004980 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004981
Reid Klecknere9f6a712014-10-31 17:10:41 +00004982 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4983 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4984 uint64_t Members) const override;
4985
Craig Topper4f12f102014-03-12 06:41:41 +00004986 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004987
John McCall7f416cc2015-09-08 08:05:57 +00004988 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4989 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004990
4991 llvm::CallingConv::ID getLLVMDefaultCC() const;
4992 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004993 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00004994
4995 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4996 ArrayRef<llvm::Type*> scalars,
4997 bool asReturnValue) const override {
4998 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4999 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005000};
5001
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005002class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5003public:
Chris Lattner2b037972010-07-29 02:01:43 +00005004 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5005 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005006
John McCall3480ef22011-08-30 01:42:09 +00005007 const ARMABIInfo &getABIInfo() const {
5008 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5009 }
5010
Craig Topper4f12f102014-03-12 06:41:41 +00005011 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005012 return 13;
5013 }
Roman Divackyc1617352011-05-18 19:36:54 +00005014
Craig Topper4f12f102014-03-12 06:41:41 +00005015 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005016 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5017 }
5018
Roman Divackyc1617352011-05-18 19:36:54 +00005019 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005020 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005021 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005022
5023 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005024 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005025 return false;
5026 }
John McCall3480ef22011-08-30 01:42:09 +00005027
Craig Topper4f12f102014-03-12 06:41:41 +00005028 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005029 if (getABIInfo().isEABI()) return 88;
5030 return TargetCodeGenInfo::getSizeOfUnwindException();
5031 }
Tim Northovera484bc02013-10-01 14:34:25 +00005032
Eric Christopher162c91c2015-06-05 22:03:00 +00005033 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005034 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005035 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005036 if (!FD)
5037 return;
5038
5039 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5040 if (!Attr)
5041 return;
5042
5043 const char *Kind;
5044 switch (Attr->getInterrupt()) {
5045 case ARMInterruptAttr::Generic: Kind = ""; break;
5046 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5047 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5048 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5049 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5050 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5051 }
5052
5053 llvm::Function *Fn = cast<llvm::Function>(GV);
5054
5055 Fn->addFnAttr("interrupt", Kind);
5056
Tim Northover5627d392015-10-30 16:30:45 +00005057 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5058 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005059 return;
5060
5061 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5062 // however this is not necessarily true on taking any interrupt. Instruct
5063 // the backend to perform a realignment as part of the function prologue.
5064 llvm::AttrBuilder B;
5065 B.addStackAlignmentAttr(8);
5066 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5067 llvm::AttributeSet::get(CGM.getLLVMContext(),
5068 llvm::AttributeSet::FunctionIndex,
5069 B));
5070 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005071};
5072
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005073class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005074public:
5075 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5076 : ARMTargetCodeGenInfo(CGT, K) {}
5077
Eric Christopher162c91c2015-06-05 22:03:00 +00005078 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005079 CodeGen::CodeGenModule &CGM) const override;
5080};
5081
Eric Christopher162c91c2015-06-05 22:03:00 +00005082void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005083 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005084 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005085 addStackProbeSizeTargetAttribute(D, GV, CGM);
5086}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005087}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005088
Chris Lattner22326a12010-07-29 02:31:05 +00005089void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005090 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005091 FI.getReturnInfo() =
5092 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005093
Tim Northoverbc784d12015-02-24 17:22:40 +00005094 for (auto &I : FI.arguments())
5095 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005096
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005097 // Always honor user-specified calling convention.
5098 if (FI.getCallingConvention() != llvm::CallingConv::C)
5099 return;
5100
John McCall882987f2013-02-28 19:01:20 +00005101 llvm::CallingConv::ID cc = getRuntimeCC();
5102 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005103 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005104}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005105
John McCall882987f2013-02-28 19:01:20 +00005106/// Return the default calling convention that LLVM will use.
5107llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5108 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005109 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005110 return llvm::CallingConv::ARM_AAPCS_VFP;
5111 else if (isEABI())
5112 return llvm::CallingConv::ARM_AAPCS;
5113 else
5114 return llvm::CallingConv::ARM_APCS;
5115}
5116
5117/// Return the calling convention that our ABI would like us to use
5118/// as the C calling convention.
5119llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005120 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005121 case APCS: return llvm::CallingConv::ARM_APCS;
5122 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5123 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005124 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005125 }
John McCall882987f2013-02-28 19:01:20 +00005126 llvm_unreachable("bad ABI kind");
5127}
5128
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005129void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005130 assert(getRuntimeCC() == llvm::CallingConv::C);
5131
5132 // Don't muddy up the IR with a ton of explicit annotations if
5133 // they'd just match what LLVM will infer from the triple.
5134 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5135 if (abiCC != getLLVMDefaultCC())
5136 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005137
Tim Northover5627d392015-10-30 16:30:45 +00005138 // AAPCS apparently requires runtime support functions to be soft-float, but
5139 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5140 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5141 switch (getABIKind()) {
5142 case APCS:
5143 case AAPCS16_VFP:
5144 if (abiCC != getLLVMDefaultCC())
5145 BuiltinCC = abiCC;
5146 break;
5147 case AAPCS:
5148 case AAPCS_VFP:
5149 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5150 break;
5151 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005152}
5153
Tim Northoverbc784d12015-02-24 17:22:40 +00005154ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5155 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005156 // 6.1.2.1 The following argument types are VFP CPRCs:
5157 // A single-precision floating-point type (including promoted
5158 // half-precision types); A double-precision floating-point type;
5159 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5160 // with a Base Type of a single- or double-precision floating-point type,
5161 // 64-bit containerized vectors or 128-bit containerized vectors with one
5162 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005163 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005164
Reid Klecknerb1be6832014-11-15 01:41:41 +00005165 Ty = useFirstFieldIfTransparentUnion(Ty);
5166
Manman Renfef9e312012-10-16 19:18:39 +00005167 // Handle illegal vector types here.
5168 if (isIllegalVectorType(Ty)) {
5169 uint64_t Size = getContext().getTypeSize(Ty);
5170 if (Size <= 32) {
5171 llvm::Type *ResType =
5172 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005173 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005174 }
5175 if (Size == 64) {
5176 llvm::Type *ResType = llvm::VectorType::get(
5177 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005178 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005179 }
5180 if (Size == 128) {
5181 llvm::Type *ResType = llvm::VectorType::get(
5182 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005183 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005184 }
John McCall7f416cc2015-09-08 08:05:57 +00005185 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005186 }
5187
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005188 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5189 // unspecified. This is not done for OpenCL as it handles the half type
5190 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005191 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005192 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5193 llvm::Type::getFloatTy(getVMContext()) :
5194 llvm::Type::getInt32Ty(getVMContext());
5195 return ABIArgInfo::getDirect(ResType);
5196 }
5197
John McCalla1dee5302010-08-22 10:59:02 +00005198 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005199 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005200 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005201 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005202 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005203
Tim Northover5a1558e2014-11-07 22:30:50 +00005204 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5205 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005206 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005207
Oliver Stannard405bded2014-02-11 09:25:50 +00005208 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005209 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005210 }
Tim Northover1060eae2013-06-21 22:49:34 +00005211
Daniel Dunbar09d33622009-09-14 21:54:03 +00005212 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005213 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005214 return ABIArgInfo::getIgnore();
5215
Tim Northover5a1558e2014-11-07 22:30:50 +00005216 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005217 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5218 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005219 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005220 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005221 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005222 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005223 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005224 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005225 }
Tim Northover5627d392015-10-30 16:30:45 +00005226 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5227 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5228 // this convention even for a variadic function: the backend will use GPRs
5229 // if needed.
5230 const Type *Base = nullptr;
5231 uint64_t Members = 0;
5232 if (isHomogeneousAggregate(Ty, Base, Members)) {
5233 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5234 llvm::Type *Ty =
5235 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5236 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5237 }
5238 }
5239
5240 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5241 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5242 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5243 // bigger than 128-bits, they get placed in space allocated by the caller,
5244 // and a pointer is passed.
5245 return ABIArgInfo::getIndirect(
5246 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005247 }
5248
Manman Ren6c30e132012-08-13 21:23:55 +00005249 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005250 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5251 // most 8-byte. We realign the indirect argument if type alignment is bigger
5252 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005253 uint64_t ABIAlign = 4;
5254 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5255 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005256 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005257 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005258
Manman Ren8cd99812012-11-06 04:58:01 +00005259 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005260 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005261 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5262 /*ByVal=*/true,
5263 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005264 }
5265
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005266 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005267 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005268 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005269 // FIXME: Try to match the types of the arguments more accurately where
5270 // we can.
5271 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005272 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5273 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005274 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005275 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5276 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005277 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005278
Tim Northover5a1558e2014-11-07 22:30:50 +00005279 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005280}
5281
Chris Lattner458b2aa2010-07-29 02:16:43 +00005282static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005283 llvm::LLVMContext &VMContext) {
5284 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5285 // is called integer-like if its size is less than or equal to one word, and
5286 // the offset of each of its addressable sub-fields is zero.
5287
5288 uint64_t Size = Context.getTypeSize(Ty);
5289
5290 // Check that the type fits in a word.
5291 if (Size > 32)
5292 return false;
5293
5294 // FIXME: Handle vector types!
5295 if (Ty->isVectorType())
5296 return false;
5297
Daniel Dunbard53bac72009-09-14 02:20:34 +00005298 // Float types are never treated as "integer like".
5299 if (Ty->isRealFloatingType())
5300 return false;
5301
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005302 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005303 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005304 return true;
5305
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005306 // Small complex integer types are "integer like".
5307 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5308 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005309
5310 // Single element and zero sized arrays should be allowed, by the definition
5311 // above, but they are not.
5312
5313 // Otherwise, it must be a record type.
5314 const RecordType *RT = Ty->getAs<RecordType>();
5315 if (!RT) return false;
5316
5317 // Ignore records with flexible arrays.
5318 const RecordDecl *RD = RT->getDecl();
5319 if (RD->hasFlexibleArrayMember())
5320 return false;
5321
5322 // Check that all sub-fields are at offset 0, and are themselves "integer
5323 // like".
5324 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5325
5326 bool HadField = false;
5327 unsigned idx = 0;
5328 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5329 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005330 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005331
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005332 // Bit-fields are not addressable, we only need to verify they are "integer
5333 // like". We still have to disallow a subsequent non-bitfield, for example:
5334 // struct { int : 0; int x }
5335 // is non-integer like according to gcc.
5336 if (FD->isBitField()) {
5337 if (!RD->isUnion())
5338 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005339
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005340 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5341 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005342
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005343 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005344 }
5345
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005346 // Check if this field is at offset 0.
5347 if (Layout.getFieldOffset(idx) != 0)
5348 return false;
5349
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005350 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5351 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005352
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005353 // Only allow at most one field in a structure. This doesn't match the
5354 // wording above, but follows gcc in situations with a field following an
5355 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005356 if (!RD->isUnion()) {
5357 if (HadField)
5358 return false;
5359
5360 HadField = true;
5361 }
5362 }
5363
5364 return true;
5365}
5366
Oliver Stannard405bded2014-02-11 09:25:50 +00005367ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5368 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005369 bool IsEffectivelyAAPCS_VFP =
5370 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005371
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005372 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005373 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005374
Daniel Dunbar19964db2010-09-23 01:54:32 +00005375 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005376 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005377 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005378 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005379
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005380 // __fp16 gets returned as if it were an int or float, but with the top 16
5381 // bits unspecified. This is not done for OpenCL as it handles the half type
5382 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005383 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005384 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5385 llvm::Type::getFloatTy(getVMContext()) :
5386 llvm::Type::getInt32Ty(getVMContext());
5387 return ABIArgInfo::getDirect(ResType);
5388 }
5389
John McCalla1dee5302010-08-22 10:59:02 +00005390 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005391 // Treat an enum type as its underlying type.
5392 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5393 RetTy = EnumTy->getDecl()->getIntegerType();
5394
Tim Northover5a1558e2014-11-07 22:30:50 +00005395 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5396 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005397 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005398
5399 // Are we following APCS?
5400 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005401 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005402 return ABIArgInfo::getIgnore();
5403
Daniel Dunbareedf1512010-02-01 23:31:19 +00005404 // Complex types are all returned as packed integers.
5405 //
5406 // FIXME: Consider using 2 x vector types if the back end handles them
5407 // correctly.
5408 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005409 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5410 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005411
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005412 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005413 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005414 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005415 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005416 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005417 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005418 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005419 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5420 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005421 }
5422
5423 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005424 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005425 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005426
5427 // Otherwise this is an AAPCS variant.
5428
Chris Lattner458b2aa2010-07-29 02:16:43 +00005429 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005430 return ABIArgInfo::getIgnore();
5431
Bob Wilson1d9269a2011-11-02 04:51:36 +00005432 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005433 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005434 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005435 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005436 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005437 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005438 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005439 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005440 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005441 }
5442
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005443 // Aggregates <= 4 bytes are returned in r0; other aggregates
5444 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005445 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005446 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005447 if (getDataLayout().isBigEndian())
5448 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005449 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005450
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005451 // Return in the smallest viable integer type.
5452 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005453 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005454 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005455 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5456 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005457 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5458 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5459 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005460 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005461 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005462 }
5463
John McCall7f416cc2015-09-08 08:05:57 +00005464 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005465}
5466
Manman Renfef9e312012-10-16 19:18:39 +00005467/// isIllegalVector - check whether Ty is an illegal vector type.
5468bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005469 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5470 if (isAndroid()) {
5471 // Android shipped using Clang 3.1, which supported a slightly different
5472 // vector ABI. The primary differences were that 3-element vector types
5473 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5474 // accepts that legacy behavior for Android only.
5475 // Check whether VT is legal.
5476 unsigned NumElements = VT->getNumElements();
5477 // NumElements should be power of 2 or equal to 3.
5478 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5479 return true;
5480 } else {
5481 // Check whether VT is legal.
5482 unsigned NumElements = VT->getNumElements();
5483 uint64_t Size = getContext().getTypeSize(VT);
5484 // NumElements should be power of 2.
5485 if (!llvm::isPowerOf2_32(NumElements))
5486 return true;
5487 // Size should be greater than 32 bits.
5488 return Size <= 32;
5489 }
Manman Renfef9e312012-10-16 19:18:39 +00005490 }
5491 return false;
5492}
5493
Reid Klecknere9f6a712014-10-31 17:10:41 +00005494bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5495 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5496 // double, or 64-bit or 128-bit vectors.
5497 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5498 if (BT->getKind() == BuiltinType::Float ||
5499 BT->getKind() == BuiltinType::Double ||
5500 BT->getKind() == BuiltinType::LongDouble)
5501 return true;
5502 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5503 unsigned VecSize = getContext().getTypeSize(VT);
5504 if (VecSize == 64 || VecSize == 128)
5505 return true;
5506 }
5507 return false;
5508}
5509
5510bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5511 uint64_t Members) const {
5512 return Members <= 4;
5513}
5514
John McCall7f416cc2015-09-08 08:05:57 +00005515Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5516 QualType Ty) const {
5517 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005518
John McCall7f416cc2015-09-08 08:05:57 +00005519 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005520 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005521 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5522 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5523 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005524 }
5525
John McCall7f416cc2015-09-08 08:05:57 +00005526 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5527 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005528
John McCall7f416cc2015-09-08 08:05:57 +00005529 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5530 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005531 const Type *Base = nullptr;
5532 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005533 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5534 IsIndirect = true;
5535
Tim Northover5627d392015-10-30 16:30:45 +00005536 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5537 // allocated by the caller.
5538 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5539 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5540 !isHomogeneousAggregate(Ty, Base, Members)) {
5541 IsIndirect = true;
5542
John McCall7f416cc2015-09-08 08:05:57 +00005543 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005544 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5545 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005546 // Our callers should be prepared to handle an under-aligned address.
5547 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5548 getABIKind() == ARMABIInfo::AAPCS) {
5549 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5550 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005551 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5552 // ARMv7k allows type alignment up to 16 bytes.
5553 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5554 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005555 } else {
5556 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005557 }
John McCall7f416cc2015-09-08 08:05:57 +00005558 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005559
John McCall7f416cc2015-09-08 08:05:57 +00005560 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5561 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005562}
5563
Chris Lattner0cf24192010-06-28 20:05:43 +00005564//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005565// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005566//===----------------------------------------------------------------------===//
5567
5568namespace {
5569
Justin Holewinski83e96682012-05-24 17:43:12 +00005570class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005571public:
Justin Holewinski36837432013-03-30 14:38:24 +00005572 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005573
5574 ABIArgInfo classifyReturnType(QualType RetTy) const;
5575 ABIArgInfo classifyArgumentType(QualType Ty) const;
5576
Craig Topper4f12f102014-03-12 06:41:41 +00005577 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005578 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5579 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005580};
5581
Justin Holewinski83e96682012-05-24 17:43:12 +00005582class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005583public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005584 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5585 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005586
Eric Christopher162c91c2015-06-05 22:03:00 +00005587 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005588 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005589private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005590 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5591 // resulting MDNode to the nvvm.annotations MDNode.
5592 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005593};
5594
Justin Holewinski83e96682012-05-24 17:43:12 +00005595ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005596 if (RetTy->isVoidType())
5597 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005598
5599 // note: this is different from default ABI
5600 if (!RetTy->isScalarType())
5601 return ABIArgInfo::getDirect();
5602
5603 // Treat an enum type as its underlying type.
5604 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5605 RetTy = EnumTy->getDecl()->getIntegerType();
5606
5607 return (RetTy->isPromotableIntegerType() ?
5608 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005609}
5610
Justin Holewinski83e96682012-05-24 17:43:12 +00005611ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005612 // Treat an enum type as its underlying type.
5613 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5614 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005615
Eli Bendersky95338a02014-10-29 13:43:21 +00005616 // Return aggregates type as indirect by value
5617 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005618 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005619
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005620 return (Ty->isPromotableIntegerType() ?
5621 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005622}
5623
Justin Holewinski83e96682012-05-24 17:43:12 +00005624void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005625 if (!getCXXABI().classifyReturnType(FI))
5626 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005627 for (auto &I : FI.arguments())
5628 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005629
5630 // Always honor user-specified calling convention.
5631 if (FI.getCallingConvention() != llvm::CallingConv::C)
5632 return;
5633
John McCall882987f2013-02-28 19:01:20 +00005634 FI.setEffectiveCallingConvention(getRuntimeCC());
5635}
5636
John McCall7f416cc2015-09-08 08:05:57 +00005637Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5638 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005639 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005640}
5641
Justin Holewinski83e96682012-05-24 17:43:12 +00005642void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005643setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005644 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005645 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005646 if (!FD) return;
5647
5648 llvm::Function *F = cast<llvm::Function>(GV);
5649
5650 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005651 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005652 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005653 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005654 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005655 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005656 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5657 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005658 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005659 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005660 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005661 }
Justin Holewinski38031972011-10-05 17:58:44 +00005662
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005663 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005664 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005665 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005666 // __global__ functions cannot be called from the device, we do not
5667 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005668 if (FD->hasAttr<CUDAGlobalAttr>()) {
5669 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5670 addNVVMMetadata(F, "kernel", 1);
5671 }
Artem Belevich7093e402015-04-21 22:55:54 +00005672 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005673 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005674 llvm::APSInt MaxThreads(32);
5675 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5676 if (MaxThreads > 0)
5677 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5678
5679 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5680 // not specified in __launch_bounds__ or if the user specified a 0 value,
5681 // we don't have to add a PTX directive.
5682 if (Attr->getMinBlocks()) {
5683 llvm::APSInt MinBlocks(32);
5684 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5685 if (MinBlocks > 0)
5686 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5687 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005688 }
5689 }
Justin Holewinski38031972011-10-05 17:58:44 +00005690 }
5691}
5692
Eli Benderskye06a2c42014-04-15 16:57:05 +00005693void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5694 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005695 llvm::Module *M = F->getParent();
5696 llvm::LLVMContext &Ctx = M->getContext();
5697
5698 // Get "nvvm.annotations" metadata node
5699 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5700
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005701 llvm::Metadata *MDVals[] = {
5702 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5703 llvm::ConstantAsMetadata::get(
5704 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005705 // Append metadata to nvvm.annotations
5706 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5707}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005708}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005709
5710//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005711// SystemZ ABI Implementation
5712//===----------------------------------------------------------------------===//
5713
5714namespace {
5715
5716class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005717 bool HasVector;
5718
Ulrich Weigand47445072013-05-06 16:26:41 +00005719public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005720 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5721 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005722
5723 bool isPromotableIntegerType(QualType Ty) const;
5724 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005725 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005726 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005727 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005728
5729 ABIArgInfo classifyReturnType(QualType RetTy) const;
5730 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5731
Craig Topper4f12f102014-03-12 06:41:41 +00005732 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005733 if (!getCXXABI().classifyReturnType(FI))
5734 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005735 for (auto &I : FI.arguments())
5736 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005737 }
5738
John McCall7f416cc2015-09-08 08:05:57 +00005739 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5740 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005741};
5742
5743class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5744public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005745 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5746 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005747};
5748
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005749}
Ulrich Weigand47445072013-05-06 16:26:41 +00005750
5751bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5752 // Treat an enum type as its underlying type.
5753 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5754 Ty = EnumTy->getDecl()->getIntegerType();
5755
5756 // Promotable integer types are required to be promoted by the ABI.
5757 if (Ty->isPromotableIntegerType())
5758 return true;
5759
5760 // 32-bit values must also be promoted.
5761 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5762 switch (BT->getKind()) {
5763 case BuiltinType::Int:
5764 case BuiltinType::UInt:
5765 return true;
5766 default:
5767 return false;
5768 }
5769 return false;
5770}
5771
5772bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005773 return (Ty->isAnyComplexType() ||
5774 Ty->isVectorType() ||
5775 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005776}
5777
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005778bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5779 return (HasVector &&
5780 Ty->isVectorType() &&
5781 getContext().getTypeSize(Ty) <= 128);
5782}
5783
Ulrich Weigand47445072013-05-06 16:26:41 +00005784bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5785 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5786 switch (BT->getKind()) {
5787 case BuiltinType::Float:
5788 case BuiltinType::Double:
5789 return true;
5790 default:
5791 return false;
5792 }
5793
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005794 return false;
5795}
5796
5797QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005798 if (const RecordType *RT = Ty->getAsStructureType()) {
5799 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005800 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005801
5802 // If this is a C++ record, check the bases first.
5803 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005804 for (const auto &I : CXXRD->bases()) {
5805 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005806
5807 // Empty bases don't affect things either way.
5808 if (isEmptyRecord(getContext(), Base, true))
5809 continue;
5810
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005811 if (!Found.isNull())
5812 return Ty;
5813 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005814 }
5815
5816 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005817 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005818 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005819 // Unlike isSingleElementStruct(), empty structure and array fields
5820 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005821 if (getContext().getLangOpts().CPlusPlus &&
5822 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5823 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005824
5825 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005826 // Nested structures still do though.
5827 if (!Found.isNull())
5828 return Ty;
5829 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005830 }
5831
5832 // Unlike isSingleElementStruct(), trailing padding is allowed.
5833 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005834 if (!Found.isNull())
5835 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005836 }
5837
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005838 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005839}
5840
John McCall7f416cc2015-09-08 08:05:57 +00005841Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5842 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005843 // Assume that va_list type is correct; should be pointer to LLVM type:
5844 // struct {
5845 // i64 __gpr;
5846 // i64 __fpr;
5847 // i8 *__overflow_arg_area;
5848 // i8 *__reg_save_area;
5849 // };
5850
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005851 // Every non-vector argument occupies 8 bytes and is passed by preference
5852 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5853 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005854 Ty = getContext().getCanonicalType(Ty);
5855 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005856 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005857 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005858 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005859 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005860 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005861 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005862 CharUnits UnpaddedSize;
5863 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005864 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005865 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5866 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005867 } else {
5868 if (AI.getCoerceToType())
5869 ArgTy = AI.getCoerceToType();
5870 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005871 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005872 UnpaddedSize = TyInfo.first;
5873 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005874 }
John McCall7f416cc2015-09-08 08:05:57 +00005875 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5876 if (IsVector && UnpaddedSize > PaddedSize)
5877 PaddedSize = CharUnits::fromQuantity(16);
5878 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005879
John McCall7f416cc2015-09-08 08:05:57 +00005880 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005881
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005882 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005883 llvm::Value *PaddedSizeV =
5884 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005885
5886 if (IsVector) {
5887 // Work out the address of a vector argument on the stack.
5888 // Vector arguments are always passed in the high bits of a
5889 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005890 Address OverflowArgAreaPtr =
5891 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005892 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005893 Address OverflowArgArea =
5894 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5895 TyInfo.second);
5896 Address MemAddr =
5897 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005898
5899 // Update overflow_arg_area_ptr pointer
5900 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005901 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5902 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005903 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5904
5905 return MemAddr;
5906 }
5907
John McCall7f416cc2015-09-08 08:05:57 +00005908 assert(PaddedSize.getQuantity() == 8);
5909
5910 unsigned MaxRegs, RegCountField, RegSaveIndex;
5911 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005912 if (InFPRs) {
5913 MaxRegs = 4; // Maximum of 4 FPR arguments
5914 RegCountField = 1; // __fpr
5915 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005916 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005917 } else {
5918 MaxRegs = 5; // Maximum of 5 GPR arguments
5919 RegCountField = 0; // __gpr
5920 RegSaveIndex = 2; // save offset for r2
5921 RegPadding = Padding; // values are passed in the low bits of a GPR
5922 }
5923
John McCall7f416cc2015-09-08 08:05:57 +00005924 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5925 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5926 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005927 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005928 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5929 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005930 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005931
5932 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5933 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5934 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5935 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5936
5937 // Emit code to load the value if it was passed in registers.
5938 CGF.EmitBlock(InRegBlock);
5939
5940 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005941 llvm::Value *ScaledRegCount =
5942 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5943 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005944 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5945 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005946 llvm::Value *RegOffset =
5947 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005948 Address RegSaveAreaPtr =
5949 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5950 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005951 llvm::Value *RegSaveArea =
5952 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005953 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5954 "raw_reg_addr"),
5955 PaddedSize);
5956 Address RegAddr =
5957 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005958
5959 // Update the register count
5960 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5961 llvm::Value *NewRegCount =
5962 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5963 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5964 CGF.EmitBranch(ContBlock);
5965
5966 // Emit code to load the value if it was passed in memory.
5967 CGF.EmitBlock(InMemBlock);
5968
5969 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005970 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5971 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5972 Address OverflowArgArea =
5973 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5974 PaddedSize);
5975 Address RawMemAddr =
5976 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5977 Address MemAddr =
5978 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005979
5980 // Update overflow_arg_area_ptr pointer
5981 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005982 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5983 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005984 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5985 CGF.EmitBranch(ContBlock);
5986
5987 // Return the appropriate result.
5988 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005989 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5990 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005991
5992 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005993 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5994 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005995
5996 return ResAddr;
5997}
5998
Ulrich Weigand47445072013-05-06 16:26:41 +00005999ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6000 if (RetTy->isVoidType())
6001 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006002 if (isVectorArgumentType(RetTy))
6003 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006004 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006005 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006006 return (isPromotableIntegerType(RetTy) ?
6007 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6008}
6009
6010ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6011 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006012 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006013 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006014
6015 // Integers and enums are extended to full register width.
6016 if (isPromotableIntegerType(Ty))
6017 return ABIArgInfo::getExtend();
6018
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006019 // Handle vector types and vector-like structure types. Note that
6020 // as opposed to float-like structure types, we do not allow any
6021 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006022 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006023 QualType SingleElementTy = GetSingleElementType(Ty);
6024 if (isVectorArgumentType(SingleElementTy) &&
6025 getContext().getTypeSize(SingleElementTy) == Size)
6026 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6027
6028 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006029 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006030 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006031
6032 // Handle small structures.
6033 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6034 // Structures with flexible arrays have variable length, so really
6035 // fail the size test above.
6036 const RecordDecl *RD = RT->getDecl();
6037 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006038 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006039
6040 // The structure is passed as an unextended integer, a float, or a double.
6041 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006042 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006043 assert(Size == 32 || Size == 64);
6044 if (Size == 32)
6045 PassTy = llvm::Type::getFloatTy(getVMContext());
6046 else
6047 PassTy = llvm::Type::getDoubleTy(getVMContext());
6048 } else
6049 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6050 return ABIArgInfo::getDirect(PassTy);
6051 }
6052
6053 // Non-structure compounds are passed indirectly.
6054 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006055 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006056
Craig Topper8a13c412014-05-21 05:09:00 +00006057 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006058}
6059
6060//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006061// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006062//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006063
6064namespace {
6065
6066class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6067public:
Chris Lattner2b037972010-07-29 02:01:43 +00006068 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6069 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006070 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006071 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006072};
6073
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006074}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006075
Eric Christopher162c91c2015-06-05 22:03:00 +00006076void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006077 llvm::GlobalValue *GV,
6078 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006079 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006080 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6081 // Handle 'interrupt' attribute:
6082 llvm::Function *F = cast<llvm::Function>(GV);
6083
6084 // Step 1: Set ISR calling convention.
6085 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6086
6087 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006088 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006089
6090 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006091 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006092 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6093 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006094 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006095 }
6096}
6097
Chris Lattner0cf24192010-06-28 20:05:43 +00006098//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006099// MIPS ABI Implementation. This works for both little-endian and
6100// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006101//===----------------------------------------------------------------------===//
6102
John McCall943fae92010-05-27 06:19:26 +00006103namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006104class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006105 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006106 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6107 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006108 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006109 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006110 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006111 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006112public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006113 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006114 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006115 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006116
6117 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006118 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006119 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006120 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6121 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006122 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006123};
6124
John McCall943fae92010-05-27 06:19:26 +00006125class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006126 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006127public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006128 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6129 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006130 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006131
Craig Topper4f12f102014-03-12 06:41:41 +00006132 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006133 return 29;
6134 }
6135
Eric Christopher162c91c2015-06-05 22:03:00 +00006136 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006137 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006138 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006139 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006140 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006141 if (FD->hasAttr<Mips16Attr>()) {
6142 Fn->addFnAttr("mips16");
6143 }
6144 else if (FD->hasAttr<NoMips16Attr>()) {
6145 Fn->addFnAttr("nomips16");
6146 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006147
6148 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6149 if (!Attr)
6150 return;
6151
6152 const char *Kind;
6153 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006154 case MipsInterruptAttr::eic: Kind = "eic"; break;
6155 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6156 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6157 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6158 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6159 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6160 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6161 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6162 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6163 }
6164
6165 Fn->addFnAttr("interrupt", Kind);
6166
Reed Kotler373feca2013-01-16 17:10:28 +00006167 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006168
John McCall943fae92010-05-27 06:19:26 +00006169 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006170 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006171
Craig Topper4f12f102014-03-12 06:41:41 +00006172 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006173 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006174 }
John McCall943fae92010-05-27 06:19:26 +00006175};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006176}
John McCall943fae92010-05-27 06:19:26 +00006177
Eric Christopher7565e0d2015-05-29 23:09:49 +00006178void MipsABIInfo::CoerceToIntArgs(
6179 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006180 llvm::IntegerType *IntTy =
6181 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006182
6183 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6184 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6185 ArgList.push_back(IntTy);
6186
6187 // If necessary, add one more integer type to ArgList.
6188 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6189
6190 if (R)
6191 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006192}
6193
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006194// In N32/64, an aligned double precision floating point field is passed in
6195// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006196llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006197 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6198
6199 if (IsO32) {
6200 CoerceToIntArgs(TySize, ArgList);
6201 return llvm::StructType::get(getVMContext(), ArgList);
6202 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006203
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006204 if (Ty->isComplexType())
6205 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006206
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006207 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006208
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006209 // Unions/vectors are passed in integer registers.
6210 if (!RT || !RT->isStructureOrClassType()) {
6211 CoerceToIntArgs(TySize, ArgList);
6212 return llvm::StructType::get(getVMContext(), ArgList);
6213 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006214
6215 const RecordDecl *RD = RT->getDecl();
6216 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006217 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006218
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006219 uint64_t LastOffset = 0;
6220 unsigned idx = 0;
6221 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6222
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006223 // Iterate over fields in the struct/class and check if there are any aligned
6224 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006225 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6226 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006227 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006228 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6229
6230 if (!BT || BT->getKind() != BuiltinType::Double)
6231 continue;
6232
6233 uint64_t Offset = Layout.getFieldOffset(idx);
6234 if (Offset % 64) // Ignore doubles that are not aligned.
6235 continue;
6236
6237 // Add ((Offset - LastOffset) / 64) args of type i64.
6238 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6239 ArgList.push_back(I64);
6240
6241 // Add double type.
6242 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6243 LastOffset = Offset + 64;
6244 }
6245
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006246 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6247 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006248
6249 return llvm::StructType::get(getVMContext(), ArgList);
6250}
6251
Akira Hatanakaddd66342013-10-29 18:41:15 +00006252llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6253 uint64_t Offset) const {
6254 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006255 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006256
Akira Hatanakaddd66342013-10-29 18:41:15 +00006257 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006258}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006259
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006260ABIArgInfo
6261MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006262 Ty = useFirstFieldIfTransparentUnion(Ty);
6263
Akira Hatanaka1632af62012-01-09 19:31:25 +00006264 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006265 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006266 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006267
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006268 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6269 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006270 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6271 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006272
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006273 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006274 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006275 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006276 return ABIArgInfo::getIgnore();
6277
Mark Lacey3825e832013-10-06 01:33:34 +00006278 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006279 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006280 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006281 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006282
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006283 // If we have reached here, aggregates are passed directly by coercing to
6284 // another structure type. Padding is inserted if the offset of the
6285 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006286 ABIArgInfo ArgInfo =
6287 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6288 getPaddingType(OrigOffset, CurrOffset));
6289 ArgInfo.setInReg(true);
6290 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006291 }
6292
6293 // Treat an enum type as its underlying type.
6294 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6295 Ty = EnumTy->getDecl()->getIntegerType();
6296
Daniel Sanders5b445b32014-10-24 14:42:42 +00006297 // All integral types are promoted to the GPR width.
6298 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006299 return ABIArgInfo::getExtend();
6300
Akira Hatanakaddd66342013-10-29 18:41:15 +00006301 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006302 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006303}
6304
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006305llvm::Type*
6306MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006307 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006308 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006309
Akira Hatanakab6f74432012-02-09 18:49:26 +00006310 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006311 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006312 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6313 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006314
Akira Hatanakab6f74432012-02-09 18:49:26 +00006315 // N32/64 returns struct/classes in floating point registers if the
6316 // following conditions are met:
6317 // 1. The size of the struct/class is no larger than 128-bit.
6318 // 2. The struct/class has one or two fields all of which are floating
6319 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006320 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006321 //
6322 // Any other composite results are returned in integer registers.
6323 //
6324 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6325 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6326 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006327 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006328
Akira Hatanakab6f74432012-02-09 18:49:26 +00006329 if (!BT || !BT->isFloatingPoint())
6330 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006331
David Blaikie2d7c57e2012-04-30 02:36:29 +00006332 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006333 }
6334
6335 if (b == e)
6336 return llvm::StructType::get(getVMContext(), RTList,
6337 RD->hasAttr<PackedAttr>());
6338
6339 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006340 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006341 }
6342
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006343 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006344 return llvm::StructType::get(getVMContext(), RTList);
6345}
6346
Akira Hatanakab579fe52011-06-02 00:09:17 +00006347ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006348 uint64_t Size = getContext().getTypeSize(RetTy);
6349
Daniel Sandersed39f582014-09-04 13:28:14 +00006350 if (RetTy->isVoidType())
6351 return ABIArgInfo::getIgnore();
6352
6353 // O32 doesn't treat zero-sized structs differently from other structs.
6354 // However, N32/N64 ignores zero sized return values.
6355 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006356 return ABIArgInfo::getIgnore();
6357
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006358 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006359 if (Size <= 128) {
6360 if (RetTy->isAnyComplexType())
6361 return ABIArgInfo::getDirect();
6362
Daniel Sanderse5018b62014-09-04 15:05:39 +00006363 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006364 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006365 if (!IsO32 ||
6366 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6367 ABIArgInfo ArgInfo =
6368 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6369 ArgInfo.setInReg(true);
6370 return ArgInfo;
6371 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006372 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006373
John McCall7f416cc2015-09-08 08:05:57 +00006374 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006375 }
6376
6377 // Treat an enum type as its underlying type.
6378 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6379 RetTy = EnumTy->getDecl()->getIntegerType();
6380
6381 return (RetTy->isPromotableIntegerType() ?
6382 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6383}
6384
6385void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006386 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006387 if (!getCXXABI().classifyReturnType(FI))
6388 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006389
Eric Christopher7565e0d2015-05-29 23:09:49 +00006390 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006391 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006392
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006393 for (auto &I : FI.arguments())
6394 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006395}
6396
John McCall7f416cc2015-09-08 08:05:57 +00006397Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6398 QualType OrigTy) const {
6399 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006400
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006401 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6402 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006403 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006404 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006405 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006406 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006407 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006408 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006409 DidPromote = true;
6410 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6411 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006412 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006413
John McCall7f416cc2015-09-08 08:05:57 +00006414 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006415
John McCall7f416cc2015-09-08 08:05:57 +00006416 // The alignment of things in the argument area is never larger than
6417 // StackAlignInBytes.
6418 TyInfo.second =
6419 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6420
6421 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6422 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6423
6424 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6425 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6426
6427
6428 // If there was a promotion, "unpromote" into a temporary.
6429 // TODO: can we just use a pointer into a subset of the original slot?
6430 if (DidPromote) {
6431 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6432 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6433
6434 // Truncate down to the right width.
6435 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6436 : CGF.IntPtrTy);
6437 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6438 if (OrigTy->isPointerType())
6439 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6440
6441 CGF.Builder.CreateStore(V, Temp);
6442 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006443 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006444
John McCall7f416cc2015-09-08 08:05:57 +00006445 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006446}
6447
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006448bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6449 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006450
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006451 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6452 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6453 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006454
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006455 return false;
6456}
6457
John McCall943fae92010-05-27 06:19:26 +00006458bool
6459MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6460 llvm::Value *Address) const {
6461 // This information comes from gcc's implementation, which seems to
6462 // as canonical as it gets.
6463
John McCall943fae92010-05-27 06:19:26 +00006464 // Everything on MIPS is 4 bytes. Double-precision FP registers
6465 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006466 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006467
6468 // 0-31 are the general purpose registers, $0 - $31.
6469 // 32-63 are the floating-point registers, $f0 - $f31.
6470 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6471 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006472 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006473
6474 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6475 // They are one bit wide and ignored here.
6476
6477 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6478 // (coprocessor 1 is the FP unit)
6479 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6480 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6481 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006482 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006483 return false;
6484}
6485
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006486//===----------------------------------------------------------------------===//
6487// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006488// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006489// handling.
6490//===----------------------------------------------------------------------===//
6491
6492namespace {
6493
6494class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6495public:
6496 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6497 : DefaultTargetCodeGenInfo(CGT) {}
6498
Eric Christopher162c91c2015-06-05 22:03:00 +00006499 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006500 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006501};
6502
Eric Christopher162c91c2015-06-05 22:03:00 +00006503void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006504 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006505 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006506 if (!FD) return;
6507
6508 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006509
David Blaikiebbafb8a2012-03-11 07:00:24 +00006510 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006511 if (FD->hasAttr<OpenCLKernelAttr>()) {
6512 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006513 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006514 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6515 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006516 // Convert the reqd_work_group_size() attributes to metadata.
6517 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006518 llvm::NamedMDNode *OpenCLMetadata =
6519 M.getModule().getOrInsertNamedMetadata(
6520 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006521
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006522 SmallVector<llvm::Metadata *, 5> Operands;
6523 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006524
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006525 Operands.push_back(
6526 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6527 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6528 Operands.push_back(
6529 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6530 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6531 Operands.push_back(
6532 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6533 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006534
Eric Christopher7565e0d2015-05-29 23:09:49 +00006535 // Add a boolean constant operand for "required" (true) or "hint"
6536 // (false) for implementing the work_group_size_hint attr later.
6537 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006538 Operands.push_back(
6539 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006540 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6541 }
6542 }
6543 }
6544}
6545
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006546}
John McCall943fae92010-05-27 06:19:26 +00006547
Tony Linthicum76329bf2011-12-12 21:14:55 +00006548//===----------------------------------------------------------------------===//
6549// Hexagon ABI Implementation
6550//===----------------------------------------------------------------------===//
6551
6552namespace {
6553
6554class HexagonABIInfo : public ABIInfo {
6555
6556
6557public:
6558 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6559
6560private:
6561
6562 ABIArgInfo classifyReturnType(QualType RetTy) const;
6563 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6564
Craig Topper4f12f102014-03-12 06:41:41 +00006565 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006566
John McCall7f416cc2015-09-08 08:05:57 +00006567 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6568 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006569};
6570
6571class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6572public:
6573 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6574 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6575
Craig Topper4f12f102014-03-12 06:41:41 +00006576 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006577 return 29;
6578 }
6579};
6580
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006581}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006582
6583void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006584 if (!getCXXABI().classifyReturnType(FI))
6585 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006586 for (auto &I : FI.arguments())
6587 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006588}
6589
6590ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6591 if (!isAggregateTypeForABI(Ty)) {
6592 // Treat an enum type as its underlying type.
6593 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6594 Ty = EnumTy->getDecl()->getIntegerType();
6595
6596 return (Ty->isPromotableIntegerType() ?
6597 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6598 }
6599
6600 // Ignore empty records.
6601 if (isEmptyRecord(getContext(), Ty, true))
6602 return ABIArgInfo::getIgnore();
6603
Mark Lacey3825e832013-10-06 01:33:34 +00006604 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006605 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006606
6607 uint64_t Size = getContext().getTypeSize(Ty);
6608 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006609 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006610 // Pass in the smallest viable integer type.
6611 else if (Size > 32)
6612 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6613 else if (Size > 16)
6614 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6615 else if (Size > 8)
6616 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6617 else
6618 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6619}
6620
6621ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6622 if (RetTy->isVoidType())
6623 return ABIArgInfo::getIgnore();
6624
6625 // Large vector types should be returned via memory.
6626 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006627 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006628
6629 if (!isAggregateTypeForABI(RetTy)) {
6630 // Treat an enum type as its underlying type.
6631 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6632 RetTy = EnumTy->getDecl()->getIntegerType();
6633
6634 return (RetTy->isPromotableIntegerType() ?
6635 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6636 }
6637
Tony Linthicum76329bf2011-12-12 21:14:55 +00006638 if (isEmptyRecord(getContext(), RetTy, true))
6639 return ABIArgInfo::getIgnore();
6640
6641 // Aggregates <= 8 bytes are returned in r0; other aggregates
6642 // are returned indirectly.
6643 uint64_t Size = getContext().getTypeSize(RetTy);
6644 if (Size <= 64) {
6645 // Return in the smallest viable integer type.
6646 if (Size <= 8)
6647 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6648 if (Size <= 16)
6649 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6650 if (Size <= 32)
6651 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6652 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6653 }
6654
John McCall7f416cc2015-09-08 08:05:57 +00006655 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006656}
6657
John McCall7f416cc2015-09-08 08:05:57 +00006658Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6659 QualType Ty) const {
6660 // FIXME: Someone needs to audit that this handle alignment correctly.
6661 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6662 getContext().getTypeInfoInChars(Ty),
6663 CharUnits::fromQuantity(4),
6664 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006665}
6666
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006667//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006668// Lanai ABI Implementation
6669//===----------------------------------------------------------------------===//
6670
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006671namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006672class LanaiABIInfo : public DefaultABIInfo {
6673public:
6674 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6675
6676 bool shouldUseInReg(QualType Ty, CCState &State) const;
6677
6678 void computeInfo(CGFunctionInfo &FI) const override {
6679 CCState State(FI.getCallingConvention());
6680 // Lanai uses 4 registers to pass arguments unless the function has the
6681 // regparm attribute set.
6682 if (FI.getHasRegParm()) {
6683 State.FreeRegs = FI.getRegParm();
6684 } else {
6685 State.FreeRegs = 4;
6686 }
6687
6688 if (!getCXXABI().classifyReturnType(FI))
6689 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6690 for (auto &I : FI.arguments())
6691 I.info = classifyArgumentType(I.type, State);
6692 }
6693
Jacques Pienaare74d9132016-04-26 00:09:29 +00006694 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006695 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6696};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006697} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006698
6699bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6700 unsigned Size = getContext().getTypeSize(Ty);
6701 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6702
6703 if (SizeInRegs == 0)
6704 return false;
6705
6706 if (SizeInRegs > State.FreeRegs) {
6707 State.FreeRegs = 0;
6708 return false;
6709 }
6710
6711 State.FreeRegs -= SizeInRegs;
6712
6713 return true;
6714}
6715
Jacques Pienaare74d9132016-04-26 00:09:29 +00006716ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6717 CCState &State) const {
6718 if (!ByVal) {
6719 if (State.FreeRegs) {
6720 --State.FreeRegs; // Non-byval indirects just use one pointer.
6721 return getNaturalAlignIndirectInReg(Ty);
6722 }
6723 return getNaturalAlignIndirect(Ty, false);
6724 }
6725
6726 // Compute the byval alignment.
6727 constexpr unsigned MinABIStackAlignInBytes = 4;
6728 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6729 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6730 /*Realign=*/TypeAlign >
6731 MinABIStackAlignInBytes);
6732}
6733
Jacques Pienaard964cc22016-03-28 21:02:54 +00006734ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6735 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006736 // Check with the C++ ABI first.
6737 const RecordType *RT = Ty->getAs<RecordType>();
6738 if (RT) {
6739 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6740 if (RAA == CGCXXABI::RAA_Indirect) {
6741 return getIndirectResult(Ty, /*ByVal=*/false, State);
6742 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6743 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6744 }
6745 }
6746
6747 if (isAggregateTypeForABI(Ty)) {
6748 // Structures with flexible arrays are always indirect.
6749 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6750 return getIndirectResult(Ty, /*ByVal=*/true, State);
6751
6752 // Ignore empty structs/unions.
6753 if (isEmptyRecord(getContext(), Ty, true))
6754 return ABIArgInfo::getIgnore();
6755
6756 llvm::LLVMContext &LLVMContext = getVMContext();
6757 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6758 if (SizeInRegs <= State.FreeRegs) {
6759 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6760 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6761 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6762 State.FreeRegs -= SizeInRegs;
6763 return ABIArgInfo::getDirectInReg(Result);
6764 } else {
6765 State.FreeRegs = 0;
6766 }
6767 return getIndirectResult(Ty, true, State);
6768 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00006769
6770 // Treat an enum type as its underlying type.
6771 if (const auto *EnumTy = Ty->getAs<EnumType>())
6772 Ty = EnumTy->getDecl()->getIntegerType();
6773
Jacques Pienaare74d9132016-04-26 00:09:29 +00006774 bool InReg = shouldUseInReg(Ty, State);
6775 if (Ty->isPromotableIntegerType()) {
6776 if (InReg)
6777 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006778 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00006779 }
6780 if (InReg)
6781 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006782 return ABIArgInfo::getDirect();
6783}
6784
6785namespace {
6786class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6787public:
6788 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
6789 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
6790};
6791}
6792
6793//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006794// AMDGPU ABI Implementation
6795//===----------------------------------------------------------------------===//
6796
6797namespace {
6798
6799class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6800public:
6801 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6802 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006803 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006804 CodeGen::CodeGenModule &M) const override;
6805};
6806
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006807}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006808
Eric Christopher162c91c2015-06-05 22:03:00 +00006809void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006810 const Decl *D,
6811 llvm::GlobalValue *GV,
6812 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006813 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006814 if (!FD)
6815 return;
6816
6817 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6818 llvm::Function *F = cast<llvm::Function>(GV);
6819 uint32_t NumVGPR = Attr->getNumVGPR();
6820 if (NumVGPR != 0)
6821 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6822 }
6823
6824 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6825 llvm::Function *F = cast<llvm::Function>(GV);
6826 unsigned NumSGPR = Attr->getNumSGPR();
6827 if (NumSGPR != 0)
6828 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6829 }
6830}
6831
Tony Linthicum76329bf2011-12-12 21:14:55 +00006832
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006833//===----------------------------------------------------------------------===//
6834// SPARC v9 ABI Implementation.
6835// Based on the SPARC Compliance Definition version 2.4.1.
6836//
6837// Function arguments a mapped to a nominal "parameter array" and promoted to
6838// registers depending on their type. Each argument occupies 8 or 16 bytes in
6839// the array, structs larger than 16 bytes are passed indirectly.
6840//
6841// One case requires special care:
6842//
6843// struct mixed {
6844// int i;
6845// float f;
6846// };
6847//
6848// When a struct mixed is passed by value, it only occupies 8 bytes in the
6849// parameter array, but the int is passed in an integer register, and the float
6850// is passed in a floating point register. This is represented as two arguments
6851// with the LLVM IR inreg attribute:
6852//
6853// declare void f(i32 inreg %i, float inreg %f)
6854//
6855// The code generator will only allocate 4 bytes from the parameter array for
6856// the inreg arguments. All other arguments are allocated a multiple of 8
6857// bytes.
6858//
6859namespace {
6860class SparcV9ABIInfo : public ABIInfo {
6861public:
6862 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6863
6864private:
6865 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006866 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006867 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6868 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006869
6870 // Coercion type builder for structs passed in registers. The coercion type
6871 // serves two purposes:
6872 //
6873 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6874 // in registers.
6875 // 2. Expose aligned floating point elements as first-level elements, so the
6876 // code generator knows to pass them in floating point registers.
6877 //
6878 // We also compute the InReg flag which indicates that the struct contains
6879 // aligned 32-bit floats.
6880 //
6881 struct CoerceBuilder {
6882 llvm::LLVMContext &Context;
6883 const llvm::DataLayout &DL;
6884 SmallVector<llvm::Type*, 8> Elems;
6885 uint64_t Size;
6886 bool InReg;
6887
6888 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6889 : Context(c), DL(dl), Size(0), InReg(false) {}
6890
6891 // Pad Elems with integers until Size is ToSize.
6892 void pad(uint64_t ToSize) {
6893 assert(ToSize >= Size && "Cannot remove elements");
6894 if (ToSize == Size)
6895 return;
6896
6897 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006898 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006899 if (Aligned > Size && Aligned <= ToSize) {
6900 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6901 Size = Aligned;
6902 }
6903
6904 // Add whole 64-bit words.
6905 while (Size + 64 <= ToSize) {
6906 Elems.push_back(llvm::Type::getInt64Ty(Context));
6907 Size += 64;
6908 }
6909
6910 // Final in-word padding.
6911 if (Size < ToSize) {
6912 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6913 Size = ToSize;
6914 }
6915 }
6916
6917 // Add a floating point element at Offset.
6918 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6919 // Unaligned floats are treated as integers.
6920 if (Offset % Bits)
6921 return;
6922 // The InReg flag is only required if there are any floats < 64 bits.
6923 if (Bits < 64)
6924 InReg = true;
6925 pad(Offset);
6926 Elems.push_back(Ty);
6927 Size = Offset + Bits;
6928 }
6929
6930 // Add a struct type to the coercion type, starting at Offset (in bits).
6931 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6932 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6933 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6934 llvm::Type *ElemTy = StrTy->getElementType(i);
6935 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6936 switch (ElemTy->getTypeID()) {
6937 case llvm::Type::StructTyID:
6938 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6939 break;
6940 case llvm::Type::FloatTyID:
6941 addFloat(ElemOffset, ElemTy, 32);
6942 break;
6943 case llvm::Type::DoubleTyID:
6944 addFloat(ElemOffset, ElemTy, 64);
6945 break;
6946 case llvm::Type::FP128TyID:
6947 addFloat(ElemOffset, ElemTy, 128);
6948 break;
6949 case llvm::Type::PointerTyID:
6950 if (ElemOffset % 64 == 0) {
6951 pad(ElemOffset);
6952 Elems.push_back(ElemTy);
6953 Size += 64;
6954 }
6955 break;
6956 default:
6957 break;
6958 }
6959 }
6960 }
6961
6962 // Check if Ty is a usable substitute for the coercion type.
6963 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006964 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006965 }
6966
6967 // Get the coercion type as a literal struct type.
6968 llvm::Type *getType() const {
6969 if (Elems.size() == 1)
6970 return Elems.front();
6971 else
6972 return llvm::StructType::get(Context, Elems);
6973 }
6974 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006975};
6976} // end anonymous namespace
6977
6978ABIArgInfo
6979SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6980 if (Ty->isVoidType())
6981 return ABIArgInfo::getIgnore();
6982
6983 uint64_t Size = getContext().getTypeSize(Ty);
6984
6985 // Anything too big to fit in registers is passed with an explicit indirect
6986 // pointer / sret pointer.
6987 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006988 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006989
6990 // Treat an enum type as its underlying type.
6991 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6992 Ty = EnumTy->getDecl()->getIntegerType();
6993
6994 // Integer types smaller than a register are extended.
6995 if (Size < 64 && Ty->isIntegerType())
6996 return ABIArgInfo::getExtend();
6997
6998 // Other non-aggregates go in registers.
6999 if (!isAggregateTypeForABI(Ty))
7000 return ABIArgInfo::getDirect();
7001
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007002 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7003 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7004 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007005 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007006
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007007 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007008 // Build a coercion type from the LLVM struct type.
7009 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7010 if (!StrTy)
7011 return ABIArgInfo::getDirect();
7012
7013 CoerceBuilder CB(getVMContext(), getDataLayout());
7014 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007015 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007016
7017 // Try to use the original type for coercion.
7018 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7019
7020 if (CB.InReg)
7021 return ABIArgInfo::getDirectInReg(CoerceTy);
7022 else
7023 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007024}
7025
John McCall7f416cc2015-09-08 08:05:57 +00007026Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7027 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007028 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7029 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7030 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7031 AI.setCoerceToType(ArgTy);
7032
John McCall7f416cc2015-09-08 08:05:57 +00007033 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007034
John McCall7f416cc2015-09-08 08:05:57 +00007035 CGBuilderTy &Builder = CGF.Builder;
7036 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7037 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7038
7039 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7040
7041 Address ArgAddr = Address::invalid();
7042 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007043 switch (AI.getKind()) {
7044 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007045 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007046 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007047 llvm_unreachable("Unsupported ABI kind for va_arg");
7048
John McCall7f416cc2015-09-08 08:05:57 +00007049 case ABIArgInfo::Extend: {
7050 Stride = SlotSize;
7051 CharUnits Offset = SlotSize - TypeInfo.first;
7052 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007053 break;
John McCall7f416cc2015-09-08 08:05:57 +00007054 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007055
John McCall7f416cc2015-09-08 08:05:57 +00007056 case ABIArgInfo::Direct: {
7057 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007058 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007059 ArgAddr = Addr;
7060 break;
John McCall7f416cc2015-09-08 08:05:57 +00007061 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007062
7063 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007064 Stride = SlotSize;
7065 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7066 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7067 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007068 break;
7069
7070 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007071 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007072 }
7073
7074 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007075 llvm::Value *NextPtr =
7076 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7077 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007078
John McCall7f416cc2015-09-08 08:05:57 +00007079 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007080}
7081
7082void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7083 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007084 for (auto &I : FI.arguments())
7085 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007086}
7087
7088namespace {
7089class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7090public:
7091 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7092 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007093
Craig Topper4f12f102014-03-12 06:41:41 +00007094 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007095 return 14;
7096 }
7097
7098 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007099 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007100};
7101} // end anonymous namespace
7102
Roman Divackyf02c9942014-02-24 18:46:27 +00007103bool
7104SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7105 llvm::Value *Address) const {
7106 // This is calculated from the LLVM and GCC tables and verified
7107 // against gcc output. AFAIK all ABIs use the same encoding.
7108
7109 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7110
7111 llvm::IntegerType *i8 = CGF.Int8Ty;
7112 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7113 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7114
7115 // 0-31: the 8-byte general-purpose registers
7116 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7117
7118 // 32-63: f0-31, the 4-byte floating-point registers
7119 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7120
7121 // Y = 64
7122 // PSR = 65
7123 // WIM = 66
7124 // TBR = 67
7125 // PC = 68
7126 // NPC = 69
7127 // FSR = 70
7128 // CSR = 71
7129 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007130
Roman Divackyf02c9942014-02-24 18:46:27 +00007131 // 72-87: d0-15, the 8-byte floating-point registers
7132 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7133
7134 return false;
7135}
7136
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007137
Robert Lytton0e076492013-08-13 09:43:10 +00007138//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007139// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007140//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007141
Robert Lytton0e076492013-08-13 09:43:10 +00007142namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007143
7144/// A SmallStringEnc instance is used to build up the TypeString by passing
7145/// it by reference between functions that append to it.
7146typedef llvm::SmallString<128> SmallStringEnc;
7147
7148/// TypeStringCache caches the meta encodings of Types.
7149///
7150/// The reason for caching TypeStrings is two fold:
7151/// 1. To cache a type's encoding for later uses;
7152/// 2. As a means to break recursive member type inclusion.
7153///
7154/// A cache Entry can have a Status of:
7155/// NonRecursive: The type encoding is not recursive;
7156/// Recursive: The type encoding is recursive;
7157/// Incomplete: An incomplete TypeString;
7158/// IncompleteUsed: An incomplete TypeString that has been used in a
7159/// Recursive type encoding.
7160///
7161/// A NonRecursive entry will have all of its sub-members expanded as fully
7162/// as possible. Whilst it may contain types which are recursive, the type
7163/// itself is not recursive and thus its encoding may be safely used whenever
7164/// the type is encountered.
7165///
7166/// A Recursive entry will have all of its sub-members expanded as fully as
7167/// possible. The type itself is recursive and it may contain other types which
7168/// are recursive. The Recursive encoding must not be used during the expansion
7169/// of a recursive type's recursive branch. For simplicity the code uses
7170/// IncompleteCount to reject all usage of Recursive encodings for member types.
7171///
7172/// An Incomplete entry is always a RecordType and only encodes its
7173/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7174/// are placed into the cache during type expansion as a means to identify and
7175/// handle recursive inclusion of types as sub-members. If there is recursion
7176/// the entry becomes IncompleteUsed.
7177///
7178/// During the expansion of a RecordType's members:
7179///
7180/// If the cache contains a NonRecursive encoding for the member type, the
7181/// cached encoding is used;
7182///
7183/// If the cache contains a Recursive encoding for the member type, the
7184/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7185///
7186/// If the member is a RecordType, an Incomplete encoding is placed into the
7187/// cache to break potential recursive inclusion of itself as a sub-member;
7188///
7189/// Once a member RecordType has been expanded, its temporary incomplete
7190/// entry is removed from the cache. If a Recursive encoding was swapped out
7191/// it is swapped back in;
7192///
7193/// If an incomplete entry is used to expand a sub-member, the incomplete
7194/// entry is marked as IncompleteUsed. The cache keeps count of how many
7195/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7196///
7197/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7198/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7199/// Else the member is part of a recursive type and thus the recursion has
7200/// been exited too soon for the encoding to be correct for the member.
7201///
7202class TypeStringCache {
7203 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7204 struct Entry {
7205 std::string Str; // The encoded TypeString for the type.
7206 enum Status State; // Information about the encoding in 'Str'.
7207 std::string Swapped; // A temporary place holder for a Recursive encoding
7208 // during the expansion of RecordType's members.
7209 };
7210 std::map<const IdentifierInfo *, struct Entry> Map;
7211 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7212 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7213public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007214 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007215 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7216 bool removeIncomplete(const IdentifierInfo *ID);
7217 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7218 bool IsRecursive);
7219 StringRef lookupStr(const IdentifierInfo *ID);
7220};
7221
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007222/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007223/// FieldEncoding is a helper for this ordering process.
7224class FieldEncoding {
7225 bool HasName;
7226 std::string Enc;
7227public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007228 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7229 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007230 bool operator<(const FieldEncoding &rhs) const {
7231 if (HasName != rhs.HasName) return HasName;
7232 return Enc < rhs.Enc;
7233 }
7234};
7235
Robert Lytton7d1db152013-08-19 09:46:39 +00007236class XCoreABIInfo : public DefaultABIInfo {
7237public:
7238 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007239 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7240 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007241};
7242
Robert Lyttond21e2d72014-03-03 13:45:29 +00007243class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007244 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007245public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007246 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007247 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007248 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7249 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007250};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007251
Robert Lytton2d196952013-10-11 10:29:34 +00007252} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007253
James Y Knight29b5f082016-02-24 02:59:33 +00007254// TODO: this implementation is likely now redundant with the default
7255// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007256Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7257 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007258 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007259
Robert Lytton2d196952013-10-11 10:29:34 +00007260 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007261 CharUnits SlotSize = CharUnits::fromQuantity(4);
7262 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007263
Robert Lytton2d196952013-10-11 10:29:34 +00007264 // Handle the argument.
7265 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007266 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007267 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7268 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7269 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007270 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007271
7272 Address Val = Address::invalid();
7273 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007274 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007275 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007276 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007277 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007278 llvm_unreachable("Unsupported ABI kind for va_arg");
7279 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007280 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7281 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007282 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007283 case ABIArgInfo::Extend:
7284 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007285 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7286 ArgSize = CharUnits::fromQuantity(
7287 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007288 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007289 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007290 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007291 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7292 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7293 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007294 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007295 }
Robert Lytton2d196952013-10-11 10:29:34 +00007296
7297 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007298 if (!ArgSize.isZero()) {
7299 llvm::Value *APN =
7300 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7301 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007302 }
John McCall7f416cc2015-09-08 08:05:57 +00007303
Robert Lytton2d196952013-10-11 10:29:34 +00007304 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007305}
Robert Lytton0e076492013-08-13 09:43:10 +00007306
Robert Lytton844aeeb2014-05-02 09:33:20 +00007307/// During the expansion of a RecordType, an incomplete TypeString is placed
7308/// into the cache as a means to identify and break recursion.
7309/// If there is a Recursive encoding in the cache, it is swapped out and will
7310/// be reinserted by removeIncomplete().
7311/// All other types of encoding should have been used rather than arriving here.
7312void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7313 std::string StubEnc) {
7314 if (!ID)
7315 return;
7316 Entry &E = Map[ID];
7317 assert( (E.Str.empty() || E.State == Recursive) &&
7318 "Incorrectly use of addIncomplete");
7319 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7320 E.Swapped.swap(E.Str); // swap out the Recursive
7321 E.Str.swap(StubEnc);
7322 E.State = Incomplete;
7323 ++IncompleteCount;
7324}
7325
7326/// Once the RecordType has been expanded, the temporary incomplete TypeString
7327/// must be removed from the cache.
7328/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7329/// Returns true if the RecordType was defined recursively.
7330bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7331 if (!ID)
7332 return false;
7333 auto I = Map.find(ID);
7334 assert(I != Map.end() && "Entry not present");
7335 Entry &E = I->second;
7336 assert( (E.State == Incomplete ||
7337 E.State == IncompleteUsed) &&
7338 "Entry must be an incomplete type");
7339 bool IsRecursive = false;
7340 if (E.State == IncompleteUsed) {
7341 // We made use of our Incomplete encoding, thus we are recursive.
7342 IsRecursive = true;
7343 --IncompleteUsedCount;
7344 }
7345 if (E.Swapped.empty())
7346 Map.erase(I);
7347 else {
7348 // Swap the Recursive back.
7349 E.Swapped.swap(E.Str);
7350 E.Swapped.clear();
7351 E.State = Recursive;
7352 }
7353 --IncompleteCount;
7354 return IsRecursive;
7355}
7356
7357/// Add the encoded TypeString to the cache only if it is NonRecursive or
7358/// Recursive (viz: all sub-members were expanded as fully as possible).
7359void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7360 bool IsRecursive) {
7361 if (!ID || IncompleteUsedCount)
7362 return; // No key or it is is an incomplete sub-type so don't add.
7363 Entry &E = Map[ID];
7364 if (IsRecursive && !E.Str.empty()) {
7365 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7366 "This is not the same Recursive entry");
7367 // The parent container was not recursive after all, so we could have used
7368 // this Recursive sub-member entry after all, but we assumed the worse when
7369 // we started viz: IncompleteCount!=0.
7370 return;
7371 }
7372 assert(E.Str.empty() && "Entry already present");
7373 E.Str = Str.str();
7374 E.State = IsRecursive? Recursive : NonRecursive;
7375}
7376
7377/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7378/// are recursively expanding a type (IncompleteCount != 0) and the cached
7379/// encoding is Recursive, return an empty StringRef.
7380StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7381 if (!ID)
7382 return StringRef(); // We have no key.
7383 auto I = Map.find(ID);
7384 if (I == Map.end())
7385 return StringRef(); // We have no encoding.
7386 Entry &E = I->second;
7387 if (E.State == Recursive && IncompleteCount)
7388 return StringRef(); // We don't use Recursive encodings for member types.
7389
7390 if (E.State == Incomplete) {
7391 // The incomplete type is being used to break out of recursion.
7392 E.State = IncompleteUsed;
7393 ++IncompleteUsedCount;
7394 }
7395 return E.Str.c_str();
7396}
7397
7398/// The XCore ABI includes a type information section that communicates symbol
7399/// type information to the linker. The linker uses this information to verify
7400/// safety/correctness of things such as array bound and pointers et al.
7401/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7402/// This type information (TypeString) is emitted into meta data for all global
7403/// symbols: definitions, declarations, functions & variables.
7404///
7405/// The TypeString carries type, qualifier, name, size & value details.
7406/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007407/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007408/// The output is tested by test/CodeGen/xcore-stringtype.c.
7409///
7410static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7411 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7412
7413/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7414void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7415 CodeGen::CodeGenModule &CGM) const {
7416 SmallStringEnc Enc;
7417 if (getTypeString(Enc, D, CGM, TSC)) {
7418 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007419 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7420 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007421 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7422 llvm::NamedMDNode *MD =
7423 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7424 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7425 }
7426}
7427
Xiuli Pan972bea82016-03-24 03:57:17 +00007428//===----------------------------------------------------------------------===//
7429// SPIR ABI Implementation
7430//===----------------------------------------------------------------------===//
7431
7432namespace {
7433class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7434public:
7435 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7436 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7437 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7438 CodeGen::CodeGenModule &M) const override;
7439};
7440} // End anonymous namespace.
7441
7442/// Emit SPIR specific metadata: OpenCL and SPIR version.
7443void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7444 CodeGen::CodeGenModule &CGM) const {
7445 assert(CGM.getLangOpts().OpenCL && "SPIR is only for OpenCL");
7446 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7447 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7448 llvm::Module &M = CGM.getModule();
7449 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7450 // opencl.spir.version named metadata.
7451 llvm::Metadata *SPIRVerElts[] = {
7452 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7453 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7454 llvm::NamedMDNode *SPIRVerMD =
7455 M.getOrInsertNamedMetadata("opencl.spir.version");
7456 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
7457 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7458 // opencl.ocl.version named metadata node.
7459 llvm::Metadata *OCLVerElts[] = {
7460 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7461 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7462 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7463 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7464 llvm::NamedMDNode *OCLVerMD =
7465 M.getOrInsertNamedMetadata("opencl.ocl.version");
7466 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7467}
7468
Robert Lytton844aeeb2014-05-02 09:33:20 +00007469static bool appendType(SmallStringEnc &Enc, QualType QType,
7470 const CodeGen::CodeGenModule &CGM,
7471 TypeStringCache &TSC);
7472
7473/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007474/// Builds a SmallVector containing the encoded field types in declaration
7475/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007476static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7477 const RecordDecl *RD,
7478 const CodeGen::CodeGenModule &CGM,
7479 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007480 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007481 SmallStringEnc Enc;
7482 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007483 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007484 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007485 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007486 Enc += "b(";
7487 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007488 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007489 Enc += ':';
7490 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007491 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007492 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007493 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007494 Enc += ')';
7495 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007496 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007497 }
7498 return true;
7499}
7500
7501/// Appends structure and union types to Enc and adds encoding to cache.
7502/// Recursively calls appendType (via extractFieldType) for each field.
7503/// Union types have their fields ordered according to the ABI.
7504static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7505 const CodeGen::CodeGenModule &CGM,
7506 TypeStringCache &TSC, const IdentifierInfo *ID) {
7507 // Append the cached TypeString if we have one.
7508 StringRef TypeString = TSC.lookupStr(ID);
7509 if (!TypeString.empty()) {
7510 Enc += TypeString;
7511 return true;
7512 }
7513
7514 // Start to emit an incomplete TypeString.
7515 size_t Start = Enc.size();
7516 Enc += (RT->isUnionType()? 'u' : 's');
7517 Enc += '(';
7518 if (ID)
7519 Enc += ID->getName();
7520 Enc += "){";
7521
7522 // We collect all encoded fields and order as necessary.
7523 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007524 const RecordDecl *RD = RT->getDecl()->getDefinition();
7525 if (RD && !RD->field_empty()) {
7526 // An incomplete TypeString stub is placed in the cache for this RecordType
7527 // so that recursive calls to this RecordType will use it whilst building a
7528 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007529 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007530 std::string StubEnc(Enc.substr(Start).str());
7531 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7532 TSC.addIncomplete(ID, std::move(StubEnc));
7533 if (!extractFieldType(FE, RD, CGM, TSC)) {
7534 (void) TSC.removeIncomplete(ID);
7535 return false;
7536 }
7537 IsRecursive = TSC.removeIncomplete(ID);
7538 // The ABI requires unions to be sorted but not structures.
7539 // See FieldEncoding::operator< for sort algorithm.
7540 if (RT->isUnionType())
7541 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007542 // We can now complete the TypeString.
7543 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007544 for (unsigned I = 0; I != E; ++I) {
7545 if (I)
7546 Enc += ',';
7547 Enc += FE[I].str();
7548 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007549 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007550 Enc += '}';
7551 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7552 return true;
7553}
7554
7555/// Appends enum types to Enc and adds the encoding to the cache.
7556static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7557 TypeStringCache &TSC,
7558 const IdentifierInfo *ID) {
7559 // Append the cached TypeString if we have one.
7560 StringRef TypeString = TSC.lookupStr(ID);
7561 if (!TypeString.empty()) {
7562 Enc += TypeString;
7563 return true;
7564 }
7565
7566 size_t Start = Enc.size();
7567 Enc += "e(";
7568 if (ID)
7569 Enc += ID->getName();
7570 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007571
7572 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007573 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007574 SmallVector<FieldEncoding, 16> FE;
7575 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7576 ++I) {
7577 SmallStringEnc EnumEnc;
7578 EnumEnc += "m(";
7579 EnumEnc += I->getName();
7580 EnumEnc += "){";
7581 I->getInitVal().toString(EnumEnc);
7582 EnumEnc += '}';
7583 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7584 }
7585 std::sort(FE.begin(), FE.end());
7586 unsigned E = FE.size();
7587 for (unsigned I = 0; I != E; ++I) {
7588 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007589 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007590 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007591 }
7592 }
7593 Enc += '}';
7594 TSC.addIfComplete(ID, Enc.substr(Start), false);
7595 return true;
7596}
7597
7598/// Appends type's qualifier to Enc.
7599/// This is done prior to appending the type's encoding.
7600static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7601 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007602 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007603 int Lookup = 0;
7604 if (QT.isConstQualified())
7605 Lookup += 1<<0;
7606 if (QT.isRestrictQualified())
7607 Lookup += 1<<1;
7608 if (QT.isVolatileQualified())
7609 Lookup += 1<<2;
7610 Enc += Table[Lookup];
7611}
7612
7613/// Appends built-in types to Enc.
7614static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7615 const char *EncType;
7616 switch (BT->getKind()) {
7617 case BuiltinType::Void:
7618 EncType = "0";
7619 break;
7620 case BuiltinType::Bool:
7621 EncType = "b";
7622 break;
7623 case BuiltinType::Char_U:
7624 EncType = "uc";
7625 break;
7626 case BuiltinType::UChar:
7627 EncType = "uc";
7628 break;
7629 case BuiltinType::SChar:
7630 EncType = "sc";
7631 break;
7632 case BuiltinType::UShort:
7633 EncType = "us";
7634 break;
7635 case BuiltinType::Short:
7636 EncType = "ss";
7637 break;
7638 case BuiltinType::UInt:
7639 EncType = "ui";
7640 break;
7641 case BuiltinType::Int:
7642 EncType = "si";
7643 break;
7644 case BuiltinType::ULong:
7645 EncType = "ul";
7646 break;
7647 case BuiltinType::Long:
7648 EncType = "sl";
7649 break;
7650 case BuiltinType::ULongLong:
7651 EncType = "ull";
7652 break;
7653 case BuiltinType::LongLong:
7654 EncType = "sll";
7655 break;
7656 case BuiltinType::Float:
7657 EncType = "ft";
7658 break;
7659 case BuiltinType::Double:
7660 EncType = "d";
7661 break;
7662 case BuiltinType::LongDouble:
7663 EncType = "ld";
7664 break;
7665 default:
7666 return false;
7667 }
7668 Enc += EncType;
7669 return true;
7670}
7671
7672/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7673static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7674 const CodeGen::CodeGenModule &CGM,
7675 TypeStringCache &TSC) {
7676 Enc += "p(";
7677 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7678 return false;
7679 Enc += ')';
7680 return true;
7681}
7682
7683/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007684static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7685 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007686 const CodeGen::CodeGenModule &CGM,
7687 TypeStringCache &TSC, StringRef NoSizeEnc) {
7688 if (AT->getSizeModifier() != ArrayType::Normal)
7689 return false;
7690 Enc += "a(";
7691 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7692 CAT->getSize().toStringUnsigned(Enc);
7693 else
7694 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7695 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007696 // The Qualifiers should be attached to the type rather than the array.
7697 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007698 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7699 return false;
7700 Enc += ')';
7701 return true;
7702}
7703
7704/// Appends a function encoding to Enc, calling appendType for the return type
7705/// and the arguments.
7706static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7707 const CodeGen::CodeGenModule &CGM,
7708 TypeStringCache &TSC) {
7709 Enc += "f{";
7710 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7711 return false;
7712 Enc += "}(";
7713 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7714 // N.B. we are only interested in the adjusted param types.
7715 auto I = FPT->param_type_begin();
7716 auto E = FPT->param_type_end();
7717 if (I != E) {
7718 do {
7719 if (!appendType(Enc, *I, CGM, TSC))
7720 return false;
7721 ++I;
7722 if (I != E)
7723 Enc += ',';
7724 } while (I != E);
7725 if (FPT->isVariadic())
7726 Enc += ",va";
7727 } else {
7728 if (FPT->isVariadic())
7729 Enc += "va";
7730 else
7731 Enc += '0';
7732 }
7733 }
7734 Enc += ')';
7735 return true;
7736}
7737
7738/// Handles the type's qualifier before dispatching a call to handle specific
7739/// type encodings.
7740static bool appendType(SmallStringEnc &Enc, QualType QType,
7741 const CodeGen::CodeGenModule &CGM,
7742 TypeStringCache &TSC) {
7743
7744 QualType QT = QType.getCanonicalType();
7745
Robert Lytton6adb20f2014-06-05 09:06:21 +00007746 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7747 // The Qualifiers should be attached to the type rather than the array.
7748 // Thus we don't call appendQualifier() here.
7749 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7750
Robert Lytton844aeeb2014-05-02 09:33:20 +00007751 appendQualifier(Enc, QT);
7752
7753 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7754 return appendBuiltinType(Enc, BT);
7755
Robert Lytton844aeeb2014-05-02 09:33:20 +00007756 if (const PointerType *PT = QT->getAs<PointerType>())
7757 return appendPointerType(Enc, PT, CGM, TSC);
7758
7759 if (const EnumType *ET = QT->getAs<EnumType>())
7760 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7761
7762 if (const RecordType *RT = QT->getAsStructureType())
7763 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7764
7765 if (const RecordType *RT = QT->getAsUnionType())
7766 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7767
7768 if (const FunctionType *FT = QT->getAs<FunctionType>())
7769 return appendFunctionType(Enc, FT, CGM, TSC);
7770
7771 return false;
7772}
7773
7774static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7775 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7776 if (!D)
7777 return false;
7778
7779 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7780 if (FD->getLanguageLinkage() != CLanguageLinkage)
7781 return false;
7782 return appendType(Enc, FD->getType(), CGM, TSC);
7783 }
7784
7785 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7786 if (VD->getLanguageLinkage() != CLanguageLinkage)
7787 return false;
7788 QualType QT = VD->getType().getCanonicalType();
7789 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7790 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007791 // The Qualifiers should be attached to the type rather than the array.
7792 // Thus we don't call appendQualifier() here.
7793 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007794 }
7795 return appendType(Enc, QT, CGM, TSC);
7796 }
7797 return false;
7798}
7799
7800
Robert Lytton0e076492013-08-13 09:43:10 +00007801//===----------------------------------------------------------------------===//
7802// Driver code
7803//===----------------------------------------------------------------------===//
7804
Rafael Espindola9f834732014-09-19 01:54:22 +00007805const llvm::Triple &CodeGenModule::getTriple() const {
7806 return getTarget().getTriple();
7807}
7808
7809bool CodeGenModule::supportsCOMDAT() const {
7810 return !getTriple().isOSBinFormatMachO();
7811}
7812
Chris Lattner2b037972010-07-29 02:01:43 +00007813const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007814 if (TheTargetCodeGenInfo)
7815 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007816
Reid Kleckner9305fd12016-04-13 23:37:17 +00007817 // Helper to set the unique_ptr while still keeping the return value.
7818 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
7819 this->TheTargetCodeGenInfo.reset(P);
7820 return *P;
7821 };
7822
John McCallc8e01702013-04-16 22:48:15 +00007823 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007824 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007825 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007826 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007827
Derek Schuff09338a22012-09-06 17:37:28 +00007828 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007829 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007830 case llvm::Triple::mips:
7831 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007832 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00007833 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
7834 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007835
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007836 case llvm::Triple::mips64:
7837 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007838 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007839
Tim Northover25e8a672014-05-24 12:51:25 +00007840 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007841 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007842 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007843 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007844 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007845
Reid Kleckner9305fd12016-04-13 23:37:17 +00007846 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007847 }
7848
Dan Gohmanc2853072015-09-03 22:51:53 +00007849 case llvm::Triple::wasm32:
7850 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007851 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00007852
Daniel Dunbard59655c2009-09-12 00:59:49 +00007853 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007854 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007855 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007856 case llvm::Triple::thumbeb: {
7857 if (Triple.getOS() == llvm::Triple::Win32) {
7858 return SetCGInfo(
7859 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007860 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007861
Reid Kleckner9305fd12016-04-13 23:37:17 +00007862 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
7863 StringRef ABIStr = getTarget().getABI();
7864 if (ABIStr == "apcs-gnu")
7865 Kind = ARMABIInfo::APCS;
7866 else if (ABIStr == "aapcs16")
7867 Kind = ARMABIInfo::AAPCS16_VFP;
7868 else if (CodeGenOpts.FloatABI == "hard" ||
7869 (CodeGenOpts.FloatABI != "soft" &&
7870 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
7871 Kind = ARMABIInfo::AAPCS_VFP;
7872
7873 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
7874 }
7875
John McCallea8d8bb2010-03-11 00:10:12 +00007876 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007877 return SetCGInfo(
7878 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007879 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007880 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007881 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007882 if (getTarget().getABI() == "elfv2")
7883 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007884 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007885
Reid Kleckner9305fd12016-04-13 23:37:17 +00007886 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007887 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00007888 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007889 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007890 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007891 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007892 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007893 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007894 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007895
Reid Kleckner9305fd12016-04-13 23:37:17 +00007896 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007897 }
John McCallea8d8bb2010-03-11 00:10:12 +00007898
Peter Collingbournec947aae2012-05-20 23:28:41 +00007899 case llvm::Triple::nvptx:
7900 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007901 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007902
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007903 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007904 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007905
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007906 case llvm::Triple::systemz: {
7907 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00007908 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007909 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007910
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007911 case llvm::Triple::tce:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007912 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007913
Eli Friedman33465822011-07-08 23:31:17 +00007914 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007915 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007916 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007917 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007918 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007919
John McCall1fe2a8c2013-06-18 02:46:29 +00007920 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00007921 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
7922 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
7923 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007924 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00007925 return SetCGInfo(new X86_32TargetCodeGenInfo(
7926 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
7927 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7928 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007929 }
Eli Friedman33465822011-07-08 23:31:17 +00007930 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007931
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007932 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007933 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00007934 X86AVXABILevel AVXLevel =
7935 (ABI == "avx512"
7936 ? X86AVXABILevel::AVX512
7937 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007938
Chris Lattner04dc9572010-08-31 16:44:54 +00007939 switch (Triple.getOS()) {
7940 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007941 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007942 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007943 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007944 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007945 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007946 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007947 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007948 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007949 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00007950 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007951 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007952 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007953 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007954 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007955 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007956 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007957 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007958 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007959 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00007960 case llvm::Triple::spir:
7961 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007962 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007963 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007964}