blob: 52bc6bb34d627e2a5c33b9bfc02d9eedb1f9a5af [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.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000275 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
276 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000277 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
278 }
279
280 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
281 return Addr;
282}
283
284/// Emit va_arg for a platform using the common void* representation,
285/// where arguments are simply emitted in an array of slots on the stack.
286///
287/// \param IsIndirect - Values of this type are passed indirectly.
288/// \param ValueInfo - The size and alignment of this type, generally
289/// computed with getContext().getTypeInfoInChars(ValueTy).
290/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
291/// Each argument will be allocated to a multiple of this number of
292/// slots, and all the slots will be aligned to this value.
293/// \param AllowHigherAlign - The slot alignment is not a cap;
294/// an argument type with an alignment greater than the slot size
295/// will be emitted on a higher-alignment address, potentially
296/// leaving one or more empty slots behind as padding.
297static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
298 QualType ValueTy, bool IsIndirect,
299 std::pair<CharUnits, CharUnits> ValueInfo,
300 CharUnits SlotSizeAndAlign,
301 bool AllowHigherAlign) {
302 // The size and alignment of the value that was passed directly.
303 CharUnits DirectSize, DirectAlign;
304 if (IsIndirect) {
305 DirectSize = CGF.getPointerSize();
306 DirectAlign = CGF.getPointerAlign();
307 } else {
308 DirectSize = ValueInfo.first;
309 DirectAlign = ValueInfo.second;
310 }
311
312 // Cast the address we've calculated to the right type.
313 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
314 if (IsIndirect)
315 DirectTy = DirectTy->getPointerTo(0);
316
317 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
318 DirectSize, DirectAlign,
319 SlotSizeAndAlign,
320 AllowHigherAlign);
321
322 if (IsIndirect) {
323 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
324 }
325
326 return Addr;
327
328}
329
330static Address emitMergePHI(CodeGenFunction &CGF,
331 Address Addr1, llvm::BasicBlock *Block1,
332 Address Addr2, llvm::BasicBlock *Block2,
333 const llvm::Twine &Name = "") {
334 assert(Addr1.getType() == Addr2.getType());
335 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
336 PHI->addIncoming(Addr1.getPointer(), Block1);
337 PHI->addIncoming(Addr2.getPointer(), Block2);
338 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
339 return Address(PHI, Align);
340}
341
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000342TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
343
John McCall3480ef22011-08-30 01:42:09 +0000344// If someone can figure out a general rule for this, that would be great.
345// It's probably just doomed to be platform-dependent, though.
346unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
347 // Verified for:
348 // x86-64 FreeBSD, Linux, Darwin
349 // x86-32 FreeBSD, Linux, Darwin
350 // PowerPC Linux, Darwin
351 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000352 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000353 return 32;
354}
355
John McCalla729c622012-02-17 03:33:10 +0000356bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
357 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000358 // The following conventions are known to require this to be false:
359 // x86_stdcall
360 // MIPS
361 // For everything else, we just prefer false unless we opt out.
362 return false;
363}
364
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000365void
366TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
367 llvm::SmallString<24> &Opt) const {
368 // This assumes the user is passing a library name like "rt" instead of a
369 // filename like "librt.a/so", and that they don't care whether it's static or
370 // dynamic.
371 Opt = "-l";
372 Opt += Lib;
373}
374
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000375static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000376
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000377/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000378/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000379static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
380 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000381 if (FD->isUnnamedBitfield())
382 return true;
383
384 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000385
Eli Friedman0b3f2012011-11-18 03:47:20 +0000386 // Constant arrays of empty records count as empty, strip them off.
387 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000388 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000389 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
390 if (AT->getSize() == 0)
391 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000392 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000393 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000394
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000395 const RecordType *RT = FT->getAs<RecordType>();
396 if (!RT)
397 return false;
398
399 // C++ record fields are never empty, at least in the Itanium ABI.
400 //
401 // FIXME: We should use a predicate for whether this behavior is true in the
402 // current ABI.
403 if (isa<CXXRecordDecl>(RT->getDecl()))
404 return false;
405
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000406 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000407}
408
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000409/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000410/// fields. Note that a structure with a flexible array member is not
411/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000412static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000413 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000414 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000415 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000416 const RecordDecl *RD = RT->getDecl();
417 if (RD->hasFlexibleArrayMember())
418 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000419
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000420 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000421 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000422 for (const auto &I : CXXRD->bases())
423 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000424 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000425
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000426 for (const auto *I : RD->fields())
427 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000428 return false;
429 return true;
430}
431
432/// isSingleElementStruct - Determine if a structure is a "single
433/// element struct", i.e. it has exactly one non-empty field or
434/// exactly one field which is itself a single element
435/// struct. Structures with flexible array members are never
436/// considered single element structs.
437///
438/// \return The field declaration for the single non-empty field, if
439/// it exists.
440static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000441 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000442 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000443 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000444
445 const RecordDecl *RD = RT->getDecl();
446 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000447 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000448
Craig Topper8a13c412014-05-21 05:09:00 +0000449 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000450
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000451 // If this is a C++ record, check the bases first.
452 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000453 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000454 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000455 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000456 continue;
457
458 // If we already found an element then this isn't a single-element struct.
459 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000460 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000461
462 // If this is non-empty and not a single element struct, the composite
463 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000464 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000465 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000466 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000467 }
468 }
469
470 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000471 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000472 QualType FT = FD->getType();
473
474 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000475 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000476 continue;
477
478 // If we already found an element then this isn't a single-element
479 // struct.
480 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000481 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000482
483 // Treat single element arrays as the element.
484 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
485 if (AT->getSize().getZExtValue() != 1)
486 break;
487 FT = AT->getElementType();
488 }
489
John McCalla1dee5302010-08-22 10:59:02 +0000490 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000491 Found = FT.getTypePtr();
492 } else {
493 Found = isSingleElementStruct(FT, Context);
494 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000495 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000496 }
497 }
498
Eli Friedmanee945342011-11-18 01:25:50 +0000499 // We don't consider a struct a single-element struct if it has
500 // padding beyond the element type.
501 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000502 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000503
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000504 return Found;
505}
506
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000507namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000508Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
509 const ABIArgInfo &AI) {
510 // This default implementation defers to the llvm backend's va_arg
511 // instruction. It can handle only passing arguments directly
512 // (typically only handled in the backend for primitive types), or
513 // aggregates passed indirectly by pointer (NOTE: if the "byval"
514 // flag has ABI impact in the callee, this implementation cannot
515 // work.)
516
517 // Only a few cases are covered here at the moment -- those needed
518 // by the default abi.
519 llvm::Value *Val;
520
521 if (AI.isIndirect()) {
522 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000523 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000524 assert(
525 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000526 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000527
528 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
529 CharUnits TyAlignForABI = TyInfo.second;
530
531 llvm::Type *BaseTy =
532 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
533 llvm::Value *Addr =
534 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
535 return Address(Addr, TyAlignForABI);
536 } else {
537 assert((AI.isDirect() || AI.isExtend()) &&
538 "Unexpected ArgInfo Kind in generic VAArg emitter!");
539
540 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000541 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000542 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000543 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000544 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000545 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000546 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000547 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000548
549 Address Temp = CGF.CreateMemTemp(Ty, "varet");
550 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
551 CGF.Builder.CreateStore(Val, Temp);
552 return Temp;
553 }
554}
555
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000556/// DefaultABIInfo - The default implementation for ABI specific
557/// details. This implementation provides information which results in
558/// self-consistent and sensible LLVM IR generation, but does not
559/// conform to any particular ABI.
560class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000561public:
562 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000563
Chris Lattner458b2aa2010-07-29 02:16:43 +0000564 ABIArgInfo classifyReturnType(QualType RetTy) const;
565 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000566
Craig Topper4f12f102014-03-12 06:41:41 +0000567 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000568 if (!getCXXABI().classifyReturnType(FI))
569 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000570 for (auto &I : FI.arguments())
571 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000572 }
573
John McCall7f416cc2015-09-08 08:05:57 +0000574 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000575 QualType Ty) const override {
576 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
577 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578};
579
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000580class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
581public:
Chris Lattner2b037972010-07-29 02:01:43 +0000582 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
583 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000584};
585
Chris Lattner458b2aa2010-07-29 02:16:43 +0000586ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000587 Ty = useFirstFieldIfTransparentUnion(Ty);
588
589 if (isAggregateTypeForABI(Ty)) {
590 // Records with non-trivial destructors/copy-constructors should not be
591 // passed by value.
592 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000593 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000594
John McCall7f416cc2015-09-08 08:05:57 +0000595 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000596 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000597
Chris Lattner9723d6c2010-03-11 18:19:55 +0000598 // Treat an enum type as its underlying type.
599 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
600 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000601
Chris Lattner9723d6c2010-03-11 18:19:55 +0000602 return (Ty->isPromotableIntegerType() ?
603 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000604}
605
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000606ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
607 if (RetTy->isVoidType())
608 return ABIArgInfo::getIgnore();
609
610 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000611 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000612
613 // Treat an enum type as its underlying type.
614 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
615 RetTy = EnumTy->getDecl()->getIntegerType();
616
617 return (RetTy->isPromotableIntegerType() ?
618 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
619}
620
Derek Schuff09338a22012-09-06 17:37:28 +0000621//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000622// WebAssembly ABI Implementation
623//
624// This is a very simple ABI that relies a lot on DefaultABIInfo.
625//===----------------------------------------------------------------------===//
626
627class WebAssemblyABIInfo final : public DefaultABIInfo {
628public:
629 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
630 : DefaultABIInfo(CGT) {}
631
632private:
633 ABIArgInfo classifyReturnType(QualType RetTy) const;
634 ABIArgInfo classifyArgumentType(QualType Ty) const;
635
636 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000637 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000638 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000639 void computeInfo(CGFunctionInfo &FI) const override {
640 if (!getCXXABI().classifyReturnType(FI))
641 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
642 for (auto &Arg : FI.arguments())
643 Arg.info = classifyArgumentType(Arg.type);
644 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000645
646 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
647 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000648};
649
650class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
651public:
652 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
653 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
654};
655
656/// \brief Classify argument of given type \p Ty.
657ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
658 Ty = useFirstFieldIfTransparentUnion(Ty);
659
660 if (isAggregateTypeForABI(Ty)) {
661 // Records with non-trivial destructors/copy-constructors should not be
662 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000663 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000664 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000665 // Ignore empty structs/unions.
666 if (isEmptyRecord(getContext(), Ty, true))
667 return ABIArgInfo::getIgnore();
668 // Lower single-element structs to just pass a regular value. TODO: We
669 // could do reasonable-size multiple-element structs too, using getExpand(),
670 // though watch out for things like bitfields.
671 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
672 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000673 }
674
675 // Otherwise just do the default thing.
676 return DefaultABIInfo::classifyArgumentType(Ty);
677}
678
679ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
680 if (isAggregateTypeForABI(RetTy)) {
681 // Records with non-trivial destructors/copy-constructors should not be
682 // returned by value.
683 if (!getRecordArgABI(RetTy, getCXXABI())) {
684 // Ignore empty structs/unions.
685 if (isEmptyRecord(getContext(), RetTy, true))
686 return ABIArgInfo::getIgnore();
687 // Lower single-element structs to just return a regular value. TODO: We
688 // could do reasonable-size multiple-element structs too, using
689 // ABIArgInfo::getDirect().
690 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
691 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
692 }
693 }
694
695 // Otherwise just do the default thing.
696 return DefaultABIInfo::classifyReturnType(RetTy);
697}
698
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000699Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
700 QualType Ty) const {
701 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
702 getContext().getTypeInfoInChars(Ty),
703 CharUnits::fromQuantity(4),
704 /*AllowHigherAlign=*/ true);
705}
706
Dan Gohmanc2853072015-09-03 22:51:53 +0000707//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000708// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000709//
710// This is a simplified version of the x86_32 ABI. Arguments and return values
711// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000712//===----------------------------------------------------------------------===//
713
714class PNaClABIInfo : public ABIInfo {
715 public:
716 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
717
718 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000719 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000720
Craig Topper4f12f102014-03-12 06:41:41 +0000721 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000722 Address EmitVAArg(CodeGenFunction &CGF,
723 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000724};
725
726class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
727 public:
728 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
729 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
730};
731
732void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000733 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000734 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
735
Reid Kleckner40ca9132014-05-13 22:05:45 +0000736 for (auto &I : FI.arguments())
737 I.info = classifyArgumentType(I.type);
738}
Derek Schuff09338a22012-09-06 17:37:28 +0000739
John McCall7f416cc2015-09-08 08:05:57 +0000740Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
741 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000742 // The PNaCL ABI is a bit odd, in that varargs don't use normal
743 // function classification. Structs get passed directly for varargs
744 // functions, through a rewriting transform in
745 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
746 // this target to actually support a va_arg instructions with an
747 // aggregate type, unlike other targets.
748 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000749}
750
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000751/// \brief Classify argument of given type \p Ty.
752ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000753 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000754 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000755 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
756 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000757 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
758 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000759 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000760 } else if (Ty->isFloatingType()) {
761 // Floating-point types don't go inreg.
762 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000763 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000764
765 return (Ty->isPromotableIntegerType() ?
766 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000767}
768
769ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
770 if (RetTy->isVoidType())
771 return ABIArgInfo::getIgnore();
772
Eli Benderskye20dad62013-04-04 22:49:35 +0000773 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000774 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000775 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000776
777 // Treat an enum type as its underlying type.
778 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
779 RetTy = EnumTy->getDecl()->getIntegerType();
780
781 return (RetTy->isPromotableIntegerType() ?
782 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
783}
784
Chad Rosier651c1832013-03-25 21:00:27 +0000785/// IsX86_MMXType - Return true if this is an MMX type.
786bool IsX86_MMXType(llvm::Type *IRType) {
787 // 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 +0000788 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
789 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
790 IRType->getScalarSizeInBits() != 64;
791}
792
Jay Foad7c57be32011-07-11 09:56:20 +0000793static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000794 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000795 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000796 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
797 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
798 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000799 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000800 }
801
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000802 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000803 }
804
805 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000806 return Ty;
807}
808
Reid Kleckner80944df2014-10-31 22:00:51 +0000809/// Returns true if this type can be passed in SSE registers with the
810/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
811static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
812 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
813 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
814 return true;
815 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
816 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
817 // registers specially.
818 unsigned VecSize = Context.getTypeSize(VT);
819 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
820 return true;
821 }
822 return false;
823}
824
825/// Returns true if this aggregate is small enough to be passed in SSE registers
826/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
827static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
828 return NumMembers <= 4;
829}
830
Chris Lattner0cf24192010-06-28 20:05:43 +0000831//===----------------------------------------------------------------------===//
832// X86-32 ABI Implementation
833//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000834
Reid Kleckner661f35b2014-01-18 01:12:41 +0000835/// \brief Similar to llvm::CCState, but for Clang.
836struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000837 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000838
839 unsigned CC;
840 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000841 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000842};
843
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000844/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000845class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000846 enum Class {
847 Integer,
848 Float
849 };
850
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000851 static const unsigned MinABIStackAlignInBytes = 4;
852
David Chisnallde3a0692009-08-17 23:08:21 +0000853 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000854 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000855 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000856 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000857 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000858 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000859
860 static bool isRegisterSize(unsigned Size) {
861 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
862 }
863
Reid Kleckner80944df2014-10-31 22:00:51 +0000864 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
865 // FIXME: Assumes vectorcall is in use.
866 return isX86VectorTypeForVectorCall(getContext(), Ty);
867 }
868
869 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
870 uint64_t NumMembers) const override {
871 // FIXME: Assumes vectorcall is in use.
872 return isX86VectorCallAggregateSmallEnough(NumMembers);
873 }
874
Reid Kleckner40ca9132014-05-13 22:05:45 +0000875 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000876
Daniel Dunbar557893d2010-04-21 19:10:51 +0000877 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
878 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000879 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
880
John McCall7f416cc2015-09-08 08:05:57 +0000881 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000882
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000883 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000884 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000885
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000886 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000887 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000888 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000889 /// \brief Updates the number of available free registers, returns
890 /// true if any registers were allocated.
891 bool updateFreeRegs(QualType Ty, CCState &State) const;
892
893 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
894 bool &NeedsPadding) const;
895 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000896
Reid Kleckner04046052016-05-02 17:41:07 +0000897 bool canExpandIndirectArgument(QualType Ty) const;
898
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000899 /// \brief Rewrite the function info so that all memory arguments use
900 /// inalloca.
901 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
902
903 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000904 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000905 QualType Type) const;
906
Rafael Espindola75419dc2012-07-23 23:30:29 +0000907public:
908
Craig Topper4f12f102014-03-12 06:41:41 +0000909 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000910 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
911 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000912
Michael Kupersteindc745202015-10-19 07:52:25 +0000913 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
914 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000915 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000916 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000917 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
918 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000919 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000920 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000921 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000922
923 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
924 ArrayRef<llvm::Type*> scalars,
925 bool asReturnValue) const override {
926 // LLVM's x86-32 lowering currently only assigns up to three
927 // integer registers and three fp registers. Oddly, it'll use up to
928 // four vector registers for vectors, but those can overlap with the
929 // scalar registers.
930 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
931 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000932};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000933
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000934class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
935public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000936 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
937 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000938 unsigned NumRegisterParameters, bool SoftFloatABI)
939 : TargetCodeGenInfo(new X86_32ABIInfo(
940 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
941 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000942
John McCall1fe2a8c2013-06-18 02:46:29 +0000943 static bool isStructReturnInRegABI(
944 const llvm::Triple &Triple, const CodeGenOptions &Opts);
945
Eric Christopher162c91c2015-06-05 22:03:00 +0000946 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000947 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000948
Craig Topper4f12f102014-03-12 06:41:41 +0000949 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000950 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000951 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000952 return 4;
953 }
954
955 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000956 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000957
Jay Foad7c57be32011-07-11 09:56:20 +0000958 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000959 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000960 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000961 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
962 }
963
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000964 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
965 std::string &Constraints,
966 std::vector<llvm::Type *> &ResultRegTypes,
967 std::vector<llvm::Type *> &ResultTruncRegTypes,
968 std::vector<LValue> &ResultRegDests,
969 std::string &AsmString,
970 unsigned NumOutputs) const override;
971
Craig Topper4f12f102014-03-12 06:41:41 +0000972 llvm::Constant *
973 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000974 unsigned Sig = (0xeb << 0) | // jmp rel8
975 (0x06 << 8) | // .+0x08
976 ('F' << 16) |
977 ('T' << 24);
978 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
979 }
John McCall01391782016-02-05 21:37:38 +0000980
981 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
982 return "movl\t%ebp, %ebp"
983 "\t\t## marker for objc_retainAutoreleaseReturnValue";
984 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000985};
986
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000987}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000988
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000989/// Rewrite input constraint references after adding some output constraints.
990/// In the case where there is one output and one input and we add one output,
991/// we need to replace all operand references greater than or equal to 1:
992/// mov $0, $1
993/// mov eax, $1
994/// The result will be:
995/// mov $0, $2
996/// mov eax, $2
997static void rewriteInputConstraintReferences(unsigned FirstIn,
998 unsigned NumNewOuts,
999 std::string &AsmString) {
1000 std::string Buf;
1001 llvm::raw_string_ostream OS(Buf);
1002 size_t Pos = 0;
1003 while (Pos < AsmString.size()) {
1004 size_t DollarStart = AsmString.find('$', Pos);
1005 if (DollarStart == std::string::npos)
1006 DollarStart = AsmString.size();
1007 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1008 if (DollarEnd == std::string::npos)
1009 DollarEnd = AsmString.size();
1010 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1011 Pos = DollarEnd;
1012 size_t NumDollars = DollarEnd - DollarStart;
1013 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1014 // We have an operand reference.
1015 size_t DigitStart = Pos;
1016 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1017 if (DigitEnd == std::string::npos)
1018 DigitEnd = AsmString.size();
1019 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1020 unsigned OperandIndex;
1021 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1022 if (OperandIndex >= FirstIn)
1023 OperandIndex += NumNewOuts;
1024 OS << OperandIndex;
1025 } else {
1026 OS << OperandStr;
1027 }
1028 Pos = DigitEnd;
1029 }
1030 }
1031 AsmString = std::move(OS.str());
1032}
1033
1034/// Add output constraints for EAX:EDX because they are return registers.
1035void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1036 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1037 std::vector<llvm::Type *> &ResultRegTypes,
1038 std::vector<llvm::Type *> &ResultTruncRegTypes,
1039 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1040 unsigned NumOutputs) const {
1041 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1042
1043 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1044 // larger.
1045 if (!Constraints.empty())
1046 Constraints += ',';
1047 if (RetWidth <= 32) {
1048 Constraints += "={eax}";
1049 ResultRegTypes.push_back(CGF.Int32Ty);
1050 } else {
1051 // Use the 'A' constraint for EAX:EDX.
1052 Constraints += "=A";
1053 ResultRegTypes.push_back(CGF.Int64Ty);
1054 }
1055
1056 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1057 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1058 ResultTruncRegTypes.push_back(CoerceTy);
1059
1060 // Coerce the integer by bitcasting the return slot pointer.
1061 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1062 CoerceTy->getPointerTo()));
1063 ResultRegDests.push_back(ReturnSlot);
1064
1065 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1066}
1067
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001068/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001069/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001070bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1071 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001072 uint64_t Size = Context.getTypeSize(Ty);
1073
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001074 // For i386, type must be register sized.
1075 // For the MCU ABI, it only needs to be <= 8-byte
1076 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1077 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001078
1079 if (Ty->isVectorType()) {
1080 // 64- and 128- bit vectors inside structures are not returned in
1081 // registers.
1082 if (Size == 64 || Size == 128)
1083 return false;
1084
1085 return true;
1086 }
1087
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001088 // If this is a builtin, pointer, enum, complex type, member pointer, or
1089 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001090 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001091 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001092 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001093 return true;
1094
1095 // Arrays are treated like records.
1096 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001097 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001098
1099 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001100 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101 if (!RT) return false;
1102
Anders Carlsson40446e82010-01-27 03:25:19 +00001103 // FIXME: Traverse bases here too.
1104
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001105 // Structure types are passed in register if all fields would be
1106 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001107 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001108 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001109 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001110 continue;
1111
1112 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001113 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001114 return false;
1115 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116 return true;
1117}
1118
Reid Kleckner04046052016-05-02 17:41:07 +00001119static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1120 // Treat complex types as the element type.
1121 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1122 Ty = CTy->getElementType();
1123
1124 // Check for a type which we know has a simple scalar argument-passing
1125 // convention without any padding. (We're specifically looking for 32
1126 // and 64-bit integer and integer-equivalents, float, and double.)
1127 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1128 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1129 return false;
1130
1131 uint64_t Size = Context.getTypeSize(Ty);
1132 return Size == 32 || Size == 64;
1133}
1134
1135/// Test whether an argument type which is to be passed indirectly (on the
1136/// stack) would have the equivalent layout if it was expanded into separate
1137/// arguments. If so, we prefer to do the latter to avoid inhibiting
1138/// optimizations.
1139bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1140 // We can only expand structure types.
1141 const RecordType *RT = Ty->getAs<RecordType>();
1142 if (!RT)
1143 return false;
1144 const RecordDecl *RD = RT->getDecl();
1145 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1146 if (!IsWin32StructABI ) {
1147 // On non-Windows, we have to conservatively match our old bitcode
1148 // prototypes in order to be ABI-compatible at the bitcode level.
1149 if (!CXXRD->isCLike())
1150 return false;
1151 } else {
1152 // Don't do this for dynamic classes.
1153 if (CXXRD->isDynamicClass())
1154 return false;
1155 // Don't do this if there are any non-empty bases.
1156 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
1157 if (!isEmptyRecord(getContext(), Base.getType(), /*AllowArrays=*/true))
1158 return false;
1159 }
1160 }
1161 }
1162
1163 uint64_t Size = 0;
1164
1165 for (const auto *FD : RD->fields()) {
1166 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1167 // argument is smaller than 32-bits, expanding the struct will create
1168 // alignment padding.
1169 if (!is32Or64BitBasicType(FD->getType(), getContext()))
1170 return false;
1171
1172 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1173 // how to expand them yet, and the predicate for telling if a bitfield still
1174 // counts as "basic" is more complicated than what we were doing previously.
1175 if (FD->isBitField())
1176 return false;
1177
1178 Size += getContext().getTypeSize(FD->getType());
1179 }
1180
1181 // We can do this if there was no alignment padding.
1182 return Size == getContext().getTypeSize(Ty);
1183}
1184
John McCall7f416cc2015-09-08 08:05:57 +00001185ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001186 // If the return value is indirect, then the hidden argument is consuming one
1187 // integer register.
1188 if (State.FreeRegs) {
1189 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001190 if (!IsMCUABI)
1191 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001192 }
John McCall7f416cc2015-09-08 08:05:57 +00001193 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001194}
1195
Eric Christopher7565e0d2015-05-29 23:09:49 +00001196ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1197 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001198 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001199 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001200
Reid Kleckner80944df2014-10-31 22:00:51 +00001201 const Type *Base = nullptr;
1202 uint64_t NumElts = 0;
1203 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1204 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1205 // The LLVM struct type for such an aggregate should lower properly.
1206 return ABIArgInfo::getDirect();
1207 }
1208
Chris Lattner458b2aa2010-07-29 02:16:43 +00001209 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001210 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001211 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001212 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001213
1214 // 128-bit vectors are a special case; they are returned in
1215 // registers and we need to make sure to pick a type the LLVM
1216 // backend will like.
1217 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001218 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001219 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001220
1221 // Always return in register if it fits in a general purpose
1222 // register, or if it is 64 bits and has a single element.
1223 if ((Size == 8 || Size == 16 || Size == 32) ||
1224 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001225 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001226 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001227
John McCall7f416cc2015-09-08 08:05:57 +00001228 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001229 }
1230
1231 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001232 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001233
John McCalla1dee5302010-08-22 10:59:02 +00001234 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001235 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001236 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001237 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001238 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001239 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001240
David Chisnallde3a0692009-08-17 23:08:21 +00001241 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001242 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001243 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001244
Denis Zobnin380b2242016-02-11 11:26:03 +00001245 // Ignore empty structs/unions.
1246 if (isEmptyRecord(getContext(), RetTy, true))
1247 return ABIArgInfo::getIgnore();
1248
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001249 // Small structures which are register sized are generally returned
1250 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001251 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001252 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001253
1254 // As a special-case, if the struct is a "single-element" struct, and
1255 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001256 // floating-point register. (MSVC does not apply this special case.)
1257 // We apply a similar transformation for pointer types to improve the
1258 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001259 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001260 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001261 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001262 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1263
1264 // FIXME: We should be able to narrow this integer in cases with dead
1265 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001266 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001267 }
1268
John McCall7f416cc2015-09-08 08:05:57 +00001269 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001270 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001271
Chris Lattner458b2aa2010-07-29 02:16:43 +00001272 // Treat an enum type as its underlying type.
1273 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1274 RetTy = EnumTy->getDecl()->getIntegerType();
1275
1276 return (RetTy->isPromotableIntegerType() ?
1277 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001278}
1279
Eli Friedman7919bea2012-06-05 19:40:46 +00001280static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1281 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1282}
1283
Daniel Dunbared23de32010-09-16 20:42:00 +00001284static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1285 const RecordType *RT = Ty->getAs<RecordType>();
1286 if (!RT)
1287 return 0;
1288 const RecordDecl *RD = RT->getDecl();
1289
1290 // If this is a C++ record, check the bases first.
1291 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001292 for (const auto &I : CXXRD->bases())
1293 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001294 return false;
1295
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001296 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001297 QualType FT = i->getType();
1298
Eli Friedman7919bea2012-06-05 19:40:46 +00001299 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001300 return true;
1301
1302 if (isRecordWithSSEVectorType(Context, FT))
1303 return true;
1304 }
1305
1306 return false;
1307}
1308
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001309unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1310 unsigned Align) const {
1311 // Otherwise, if the alignment is less than or equal to the minimum ABI
1312 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001313 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001314 return 0; // Use default alignment.
1315
1316 // On non-Darwin, the stack type alignment is always 4.
1317 if (!IsDarwinVectorABI) {
1318 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001319 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001320 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001321
Daniel Dunbared23de32010-09-16 20:42:00 +00001322 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001323 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1324 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001325 return 16;
1326
1327 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001328}
1329
Rafael Espindola703c47f2012-10-19 05:04:37 +00001330ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001331 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001332 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001333 if (State.FreeRegs) {
1334 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001335 if (!IsMCUABI)
1336 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001337 }
John McCall7f416cc2015-09-08 08:05:57 +00001338 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001339 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001340
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001341 // Compute the byval alignment.
1342 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1343 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1344 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001345 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001346
1347 // If the stack alignment is less than the type alignment, realign the
1348 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001349 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001350 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1351 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001352}
1353
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001354X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1355 const Type *T = isSingleElementStruct(Ty, getContext());
1356 if (!T)
1357 T = Ty.getTypePtr();
1358
1359 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1360 BuiltinType::Kind K = BT->getKind();
1361 if (K == BuiltinType::Float || K == BuiltinType::Double)
1362 return Float;
1363 }
1364 return Integer;
1365}
1366
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001367bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001368 if (!IsSoftFloatABI) {
1369 Class C = classify(Ty);
1370 if (C == Float)
1371 return false;
1372 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001373
Rafael Espindola077dd592012-10-24 01:58:58 +00001374 unsigned Size = getContext().getTypeSize(Ty);
1375 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001376
1377 if (SizeInRegs == 0)
1378 return false;
1379
Michael Kuperstein68901882015-10-25 08:18:20 +00001380 if (!IsMCUABI) {
1381 if (SizeInRegs > State.FreeRegs) {
1382 State.FreeRegs = 0;
1383 return false;
1384 }
1385 } else {
1386 // The MCU psABI allows passing parameters in-reg even if there are
1387 // earlier parameters that are passed on the stack. Also,
1388 // it does not allow passing >8-byte structs in-register,
1389 // even if there are 3 free registers available.
1390 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1391 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001392 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001393
Reid Kleckner661f35b2014-01-18 01:12:41 +00001394 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001395 return true;
1396}
1397
1398bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1399 bool &InReg,
1400 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001401 // On Windows, aggregates other than HFAs are never passed in registers, and
1402 // they do not consume register slots. Homogenous floating-point aggregates
1403 // (HFAs) have already been dealt with at this point.
1404 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1405 return false;
1406
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001407 NeedsPadding = false;
1408 InReg = !IsMCUABI;
1409
1410 if (!updateFreeRegs(Ty, State))
1411 return false;
1412
1413 if (IsMCUABI)
1414 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001415
Reid Kleckner80944df2014-10-31 22:00:51 +00001416 if (State.CC == llvm::CallingConv::X86_FastCall ||
1417 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001418 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001419 NeedsPadding = true;
1420
Rafael Espindola077dd592012-10-24 01:58:58 +00001421 return false;
1422 }
1423
Rafael Espindola703c47f2012-10-19 05:04:37 +00001424 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001425}
1426
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001427bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1428 if (!updateFreeRegs(Ty, State))
1429 return false;
1430
1431 if (IsMCUABI)
1432 return false;
1433
1434 if (State.CC == llvm::CallingConv::X86_FastCall ||
1435 State.CC == llvm::CallingConv::X86_VectorCall) {
1436 if (getContext().getTypeSize(Ty) > 32)
1437 return false;
1438
1439 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1440 Ty->isReferenceType());
1441 }
1442
1443 return true;
1444}
1445
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001446ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1447 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001448 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001449
Reid Klecknerb1be6832014-11-15 01:41:41 +00001450 Ty = useFirstFieldIfTransparentUnion(Ty);
1451
Reid Kleckner80944df2014-10-31 22:00:51 +00001452 // Check with the C++ ABI first.
1453 const RecordType *RT = Ty->getAs<RecordType>();
1454 if (RT) {
1455 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1456 if (RAA == CGCXXABI::RAA_Indirect) {
1457 return getIndirectResult(Ty, false, State);
1458 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1459 // The field index doesn't matter, we'll fix it up later.
1460 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1461 }
1462 }
1463
1464 // vectorcall adds the concept of a homogenous vector aggregate, similar
1465 // to other targets.
1466 const Type *Base = nullptr;
1467 uint64_t NumElts = 0;
1468 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1469 isHomogeneousAggregate(Ty, Base, NumElts)) {
1470 if (State.FreeSSERegs >= NumElts) {
1471 State.FreeSSERegs -= NumElts;
1472 if (Ty->isBuiltinType() || Ty->isVectorType())
1473 return ABIArgInfo::getDirect();
1474 return ABIArgInfo::getExpand();
1475 }
1476 return getIndirectResult(Ty, /*ByVal=*/false, State);
1477 }
1478
1479 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001480 // Structures with flexible arrays are always indirect.
1481 // FIXME: This should not be byval!
1482 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1483 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001484
Reid Kleckner04046052016-05-02 17:41:07 +00001485 // Ignore empty structs/unions on non-Windows.
1486 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001487 return ABIArgInfo::getIgnore();
1488
Rafael Espindolafad28de2012-10-24 01:59:00 +00001489 llvm::LLVMContext &LLVMContext = getVMContext();
1490 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001491 bool NeedsPadding = false;
1492 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001493 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001494 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001495 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001496 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001497 if (InReg)
1498 return ABIArgInfo::getDirectInReg(Result);
1499 else
1500 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001501 }
Craig Topper8a13c412014-05-21 05:09:00 +00001502 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001503
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001504 // Expand small (<= 128-bit) record types when we know that the stack layout
1505 // of those arguments will match the struct. This is important because the
1506 // LLVM backend isn't smart enough to remove byval, which inhibits many
1507 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001508 // Don't do this for the MCU if there are still free integer registers
1509 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001510 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1511 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001512 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001513 State.CC == llvm::CallingConv::X86_FastCall ||
1514 State.CC == llvm::CallingConv::X86_VectorCall,
1515 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001516
Reid Kleckner661f35b2014-01-18 01:12:41 +00001517 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001518 }
1519
Chris Lattnerd774ae92010-08-26 20:05:13 +00001520 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001521 // On Darwin, some vectors are passed in memory, we handle this by passing
1522 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001523 if (IsDarwinVectorABI) {
1524 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001525 if ((Size == 8 || Size == 16 || Size == 32) ||
1526 (Size == 64 && VT->getNumElements() == 1))
1527 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1528 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001529 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001530
Chad Rosier651c1832013-03-25 21:00:27 +00001531 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1532 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001533
Chris Lattnerd774ae92010-08-26 20:05:13 +00001534 return ABIArgInfo::getDirect();
1535 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001536
1537
Chris Lattner458b2aa2010-07-29 02:16:43 +00001538 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1539 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001540
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001541 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001542
1543 if (Ty->isPromotableIntegerType()) {
1544 if (InReg)
1545 return ABIArgInfo::getExtendInReg();
1546 return ABIArgInfo::getExtend();
1547 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001548
Rafael Espindola703c47f2012-10-19 05:04:37 +00001549 if (InReg)
1550 return ABIArgInfo::getDirectInReg();
1551 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001552}
1553
Rafael Espindolaa6472962012-07-24 00:01:07 +00001554void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001555 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001556 if (IsMCUABI)
1557 State.FreeRegs = 3;
1558 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001559 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001560 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1561 State.FreeRegs = 2;
1562 State.FreeSSERegs = 6;
1563 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001564 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001565 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001566 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001567
Reid Kleckner677539d2014-07-10 01:58:55 +00001568 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001569 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001570 } else if (FI.getReturnInfo().isIndirect()) {
1571 // The C++ ABI is not aware of register usage, so we have to check if the
1572 // return value was sret and put it in a register ourselves if appropriate.
1573 if (State.FreeRegs) {
1574 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001575 if (!IsMCUABI)
1576 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001577 }
1578 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001579
Peter Collingbournef7706832014-12-12 23:41:25 +00001580 // The chain argument effectively gives us another free register.
1581 if (FI.isChainCall())
1582 ++State.FreeRegs;
1583
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001584 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001585 for (auto &I : FI.arguments()) {
1586 I.info = classifyArgumentType(I.type, State);
1587 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001588 }
1589
1590 // If we needed to use inalloca for any argument, do a second pass and rewrite
1591 // all the memory arguments to use inalloca.
1592 if (UsedInAlloca)
1593 rewriteWithInAlloca(FI);
1594}
1595
1596void
1597X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001598 CharUnits &StackOffset, ABIArgInfo &Info,
1599 QualType Type) const {
1600 // Arguments are always 4-byte-aligned.
1601 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1602
1603 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001604 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1605 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001606 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001607
John McCall7f416cc2015-09-08 08:05:57 +00001608 // Insert padding bytes to respect alignment.
1609 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001610 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001611 if (StackOffset != FieldEnd) {
1612 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001613 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001614 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001615 FrameFields.push_back(Ty);
1616 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001617}
1618
Reid Kleckner852361d2014-07-26 00:12:26 +00001619static bool isArgInAlloca(const ABIArgInfo &Info) {
1620 // Leave ignored and inreg arguments alone.
1621 switch (Info.getKind()) {
1622 case ABIArgInfo::InAlloca:
1623 return true;
1624 case ABIArgInfo::Indirect:
1625 assert(Info.getIndirectByVal());
1626 return true;
1627 case ABIArgInfo::Ignore:
1628 return false;
1629 case ABIArgInfo::Direct:
1630 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001631 if (Info.getInReg())
1632 return false;
1633 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001634 case ABIArgInfo::Expand:
1635 case ABIArgInfo::CoerceAndExpand:
1636 // These are aggregate types which are never passed in registers when
1637 // inalloca is involved.
1638 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001639 }
1640 llvm_unreachable("invalid enum");
1641}
1642
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001643void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1644 assert(IsWin32StructABI && "inalloca only supported on win32");
1645
1646 // Build a packed struct type for all of the arguments in memory.
1647 SmallVector<llvm::Type *, 6> FrameFields;
1648
John McCall7f416cc2015-09-08 08:05:57 +00001649 // The stack alignment is always 4.
1650 CharUnits StackAlign = CharUnits::fromQuantity(4);
1651
1652 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001653 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1654
1655 // Put 'this' into the struct before 'sret', if necessary.
1656 bool IsThisCall =
1657 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1658 ABIArgInfo &Ret = FI.getReturnInfo();
1659 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1660 isArgInAlloca(I->info)) {
1661 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1662 ++I;
1663 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001664
1665 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001666 if (Ret.isIndirect() && !Ret.getInReg()) {
1667 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1668 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001669 // On Windows, the hidden sret parameter is always returned in eax.
1670 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001671 }
1672
1673 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001674 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001675 ++I;
1676
1677 // Put arguments passed in memory into the struct.
1678 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001679 if (isArgInAlloca(I->info))
1680 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001681 }
1682
1683 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001684 /*isPacked=*/true),
1685 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001686}
1687
John McCall7f416cc2015-09-08 08:05:57 +00001688Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1689 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001690
John McCall7f416cc2015-09-08 08:05:57 +00001691 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001692
John McCall7f416cc2015-09-08 08:05:57 +00001693 // x86-32 changes the alignment of certain arguments on the stack.
1694 //
1695 // Just messing with TypeInfo like this works because we never pass
1696 // anything indirectly.
1697 TypeInfo.second = CharUnits::fromQuantity(
1698 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001699
John McCall7f416cc2015-09-08 08:05:57 +00001700 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1701 TypeInfo, CharUnits::fromQuantity(4),
1702 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001703}
1704
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001705bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1706 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1707 assert(Triple.getArch() == llvm::Triple::x86);
1708
1709 switch (Opts.getStructReturnConvention()) {
1710 case CodeGenOptions::SRCK_Default:
1711 break;
1712 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1713 return false;
1714 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1715 return true;
1716 }
1717
Michael Kupersteind749f232015-10-27 07:46:22 +00001718 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001719 return true;
1720
1721 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001722 case llvm::Triple::DragonFly:
1723 case llvm::Triple::FreeBSD:
1724 case llvm::Triple::OpenBSD:
1725 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001726 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001727 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001728 default:
1729 return false;
1730 }
1731}
1732
Eric Christopher162c91c2015-06-05 22:03:00 +00001733void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001734 llvm::GlobalValue *GV,
1735 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001736 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001737 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1738 // Get the LLVM function.
1739 llvm::Function *Fn = cast<llvm::Function>(GV);
1740
1741 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001742 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001743 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001744 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1745 llvm::AttributeSet::get(CGM.getLLVMContext(),
1746 llvm::AttributeSet::FunctionIndex,
1747 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001748 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001749 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1750 llvm::Function *Fn = cast<llvm::Function>(GV);
1751 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1752 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001753 }
1754}
1755
John McCallbeec5a02010-03-06 00:35:14 +00001756bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1757 CodeGen::CodeGenFunction &CGF,
1758 llvm::Value *Address) const {
1759 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001760
Chris Lattnerece04092012-02-07 00:39:47 +00001761 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001762
John McCallbeec5a02010-03-06 00:35:14 +00001763 // 0-7 are the eight integer registers; the order is different
1764 // on Darwin (for EH), but the range is the same.
1765 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001766 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001767
John McCallc8e01702013-04-16 22:48:15 +00001768 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001769 // 12-16 are st(0..4). Not sure why we stop at 4.
1770 // These have size 16, which is sizeof(long double) on
1771 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001772 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001773 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001774
John McCallbeec5a02010-03-06 00:35:14 +00001775 } else {
1776 // 9 is %eflags, which doesn't get a size on Darwin for some
1777 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001778 Builder.CreateAlignedStore(
1779 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1780 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001781
1782 // 11-16 are st(0..5). Not sure why we stop at 5.
1783 // These have size 12, which is sizeof(long double) on
1784 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001785 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001786 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1787 }
John McCallbeec5a02010-03-06 00:35:14 +00001788
1789 return false;
1790}
1791
Chris Lattner0cf24192010-06-28 20:05:43 +00001792//===----------------------------------------------------------------------===//
1793// X86-64 ABI Implementation
1794//===----------------------------------------------------------------------===//
1795
1796
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001797namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001798/// The AVX ABI level for X86 targets.
1799enum class X86AVXABILevel {
1800 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001801 AVX,
1802 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001803};
1804
1805/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1806static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1807 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001808 case X86AVXABILevel::AVX512:
1809 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001810 case X86AVXABILevel::AVX:
1811 return 256;
1812 case X86AVXABILevel::None:
1813 return 128;
1814 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001815 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001816}
1817
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001818/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001819class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001820 enum Class {
1821 Integer = 0,
1822 SSE,
1823 SSEUp,
1824 X87,
1825 X87Up,
1826 ComplexX87,
1827 NoClass,
1828 Memory
1829 };
1830
1831 /// merge - Implement the X86_64 ABI merging algorithm.
1832 ///
1833 /// Merge an accumulating classification \arg Accum with a field
1834 /// classification \arg Field.
1835 ///
1836 /// \param Accum - The accumulating classification. This should
1837 /// always be either NoClass or the result of a previous merge
1838 /// call. In addition, this should never be Memory (the caller
1839 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001840 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001841
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001842 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1843 ///
1844 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1845 /// final MEMORY or SSE classes when necessary.
1846 ///
1847 /// \param AggregateSize - The size of the current aggregate in
1848 /// the classification process.
1849 ///
1850 /// \param Lo - The classification for the parts of the type
1851 /// residing in the low word of the containing object.
1852 ///
1853 /// \param Hi - The classification for the parts of the type
1854 /// residing in the higher words of the containing object.
1855 ///
1856 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1857
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001858 /// classify - Determine the x86_64 register classes in which the
1859 /// given type T should be passed.
1860 ///
1861 /// \param Lo - The classification for the parts of the type
1862 /// residing in the low word of the containing object.
1863 ///
1864 /// \param Hi - The classification for the parts of the type
1865 /// residing in the high word of the containing object.
1866 ///
1867 /// \param OffsetBase - The bit offset of this type in the
1868 /// containing object. Some parameters are classified different
1869 /// depending on whether they straddle an eightbyte boundary.
1870 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001871 /// \param isNamedArg - Whether the argument in question is a "named"
1872 /// argument, as used in AMD64-ABI 3.5.7.
1873 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001874 /// If a word is unused its result will be NoClass; if a type should
1875 /// be passed in Memory then at least the classification of \arg Lo
1876 /// will be Memory.
1877 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001878 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001879 ///
1880 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1881 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001882 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1883 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001884
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001885 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001886 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1887 unsigned IROffset, QualType SourceTy,
1888 unsigned SourceOffset) const;
1889 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1890 unsigned IROffset, QualType SourceTy,
1891 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001892
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001893 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001894 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001895 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001896
1897 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001898 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001899 ///
1900 /// \param freeIntRegs - The number of free integer registers remaining
1901 /// available.
1902 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001903
Chris Lattner458b2aa2010-07-29 02:16:43 +00001904 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001905
Bill Wendling5cd41c42010-10-18 03:41:31 +00001906 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001907 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001908 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001909 unsigned &neededSSE,
1910 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001911
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001912 bool IsIllegalVectorType(QualType Ty) const;
1913
John McCalle0fda732011-04-21 01:20:55 +00001914 /// The 0.98 ABI revision clarified a lot of ambiguities,
1915 /// unfortunately in ways that were not always consistent with
1916 /// certain previous compilers. In particular, platforms which
1917 /// required strict binary compatibility with older versions of GCC
1918 /// may need to exempt themselves.
1919 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001920 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001921 }
1922
David Majnemere2ae2282016-03-04 05:26:16 +00001923 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1924 // compilers require us to classify it as INTEGER.
1925 bool classifyIntegerMMXAsSSE() const {
1926 const llvm::Triple &Triple = getTarget().getTriple();
1927 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1928 return false;
1929 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1930 return false;
1931 return true;
1932 }
1933
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001934 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001935 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1936 // 64-bit hardware.
1937 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001938
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001939public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001940 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00001941 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001942 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001943 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001944
John McCalla729c622012-02-17 03:33:10 +00001945 bool isPassedUsingAVXType(QualType type) const {
1946 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001947 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001948 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1949 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001950 if (info.isDirect()) {
1951 llvm::Type *ty = info.getCoerceToType();
1952 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1953 return (vectorTy->getBitWidth() > 128);
1954 }
1955 return false;
1956 }
1957
Craig Topper4f12f102014-03-12 06:41:41 +00001958 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001959
John McCall7f416cc2015-09-08 08:05:57 +00001960 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1961 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001962 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1963 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001964
1965 bool has64BitPointers() const {
1966 return Has64BitPointers;
1967 }
John McCall12f23522016-04-04 18:33:08 +00001968
1969 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1970 ArrayRef<llvm::Type*> scalars,
1971 bool asReturnValue) const override {
1972 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
1973 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001974};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001975
Chris Lattner04dc9572010-08-31 16:44:54 +00001976/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001977class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001978public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001979 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1980 : ABIInfo(CGT),
1981 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001982
Craig Topper4f12f102014-03-12 06:41:41 +00001983 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001984
John McCall7f416cc2015-09-08 08:05:57 +00001985 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1986 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001987
1988 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1989 // FIXME: Assumes vectorcall is in use.
1990 return isX86VectorTypeForVectorCall(getContext(), Ty);
1991 }
1992
1993 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1994 uint64_t NumMembers) const override {
1995 // FIXME: Assumes vectorcall is in use.
1996 return isX86VectorCallAggregateSmallEnough(NumMembers);
1997 }
Reid Kleckner11a17192015-10-28 22:29:52 +00001998
1999private:
2000 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
2001 bool IsReturnType) const;
2002
2003 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002004};
2005
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002006class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2007public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002008 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002009 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002010
John McCalla729c622012-02-17 03:33:10 +00002011 const X86_64ABIInfo &getABIInfo() const {
2012 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2013 }
2014
Craig Topper4f12f102014-03-12 06:41:41 +00002015 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002016 return 7;
2017 }
2018
2019 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002020 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002021 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002022
John McCall943fae92010-05-27 06:19:26 +00002023 // 0-15 are the 16 integer registers.
2024 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002025 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002026 return false;
2027 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002028
Jay Foad7c57be32011-07-11 09:56:20 +00002029 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002030 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002031 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002032 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2033 }
2034
John McCalla729c622012-02-17 03:33:10 +00002035 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002036 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002037 // The default CC on x86-64 sets %al to the number of SSA
2038 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002039 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002040 // that when AVX types are involved: the ABI explicitly states it is
2041 // undefined, and it doesn't work in practice because of how the ABI
2042 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002043 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002044 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002045 for (CallArgList::const_iterator
2046 it = args.begin(), ie = args.end(); it != ie; ++it) {
2047 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2048 HasAVXType = true;
2049 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002050 }
2051 }
John McCalla729c622012-02-17 03:33:10 +00002052
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002053 if (!HasAVXType)
2054 return true;
2055 }
John McCallcbc038a2011-09-21 08:08:30 +00002056
John McCalla729c622012-02-17 03:33:10 +00002057 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002058 }
2059
Craig Topper4f12f102014-03-12 06:41:41 +00002060 llvm::Constant *
2061 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002062 unsigned Sig;
2063 if (getABIInfo().has64BitPointers())
2064 Sig = (0xeb << 0) | // jmp rel8
2065 (0x0a << 8) | // .+0x0c
2066 ('F' << 16) |
2067 ('T' << 24);
2068 else
2069 Sig = (0xeb << 0) | // jmp rel8
2070 (0x06 << 8) | // .+0x08
2071 ('F' << 16) |
2072 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002073 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2074 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002075
2076 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2077 CodeGen::CodeGenModule &CGM) const override {
2078 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2079 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2080 llvm::Function *Fn = cast<llvm::Function>(GV);
2081 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2082 }
2083 }
2084 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002085};
2086
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002087class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2088public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002089 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2090 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002091
2092 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002093 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002094 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002095 // If the argument contains a space, enclose it in quotes.
2096 if (Lib.find(" ") != StringRef::npos)
2097 Opt += "\"" + Lib.str() + "\"";
2098 else
2099 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002100 }
2101};
2102
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002103static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002104 // If the argument does not end in .lib, automatically add the suffix.
2105 // If the argument contains a space, enclose it in quotes.
2106 // This matches the behavior of MSVC.
2107 bool Quote = (Lib.find(" ") != StringRef::npos);
2108 std::string ArgStr = Quote ? "\"" : "";
2109 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002110 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002111 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002112 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002113 return ArgStr;
2114}
2115
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002116class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2117public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002118 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002119 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2120 unsigned NumRegisterParameters)
2121 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002122 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002123
Eric Christopher162c91c2015-06-05 22:03:00 +00002124 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002125 CodeGen::CodeGenModule &CGM) const override;
2126
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002127 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002128 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002129 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002130 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002131 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002132
2133 void getDetectMismatchOption(llvm::StringRef Name,
2134 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002135 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002136 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002137 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002138};
2139
Hans Wennborg77dc2362015-01-20 19:45:50 +00002140static void addStackProbeSizeTargetAttribute(const Decl *D,
2141 llvm::GlobalValue *GV,
2142 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002143 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002144 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2145 llvm::Function *Fn = cast<llvm::Function>(GV);
2146
Eric Christopher7565e0d2015-05-29 23:09:49 +00002147 Fn->addFnAttr("stack-probe-size",
2148 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002149 }
2150 }
2151}
2152
Eric Christopher162c91c2015-06-05 22:03:00 +00002153void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002154 llvm::GlobalValue *GV,
2155 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002156 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002157
2158 addStackProbeSizeTargetAttribute(D, GV, CGM);
2159}
2160
Chris Lattner04dc9572010-08-31 16:44:54 +00002161class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2162public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002163 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2164 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002165 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002166
Eric Christopher162c91c2015-06-05 22:03:00 +00002167 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002168 CodeGen::CodeGenModule &CGM) const override;
2169
Craig Topper4f12f102014-03-12 06:41:41 +00002170 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002171 return 7;
2172 }
2173
2174 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002175 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002176 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002177
Chris Lattner04dc9572010-08-31 16:44:54 +00002178 // 0-15 are the 16 integer registers.
2179 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002180 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002181 return false;
2182 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002183
2184 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002185 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002186 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002187 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002188 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002189
2190 void getDetectMismatchOption(llvm::StringRef Name,
2191 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002192 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002193 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002194 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002195};
2196
Eric Christopher162c91c2015-06-05 22:03:00 +00002197void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002198 llvm::GlobalValue *GV,
2199 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002200 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002201
Alexey Bataevd51e9932016-01-15 04:06:31 +00002202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2203 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2204 llvm::Function *Fn = cast<llvm::Function>(GV);
2205 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2206 }
2207 }
2208
Hans Wennborg77dc2362015-01-20 19:45:50 +00002209 addStackProbeSizeTargetAttribute(D, GV, CGM);
2210}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002211}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002212
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002213void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2214 Class &Hi) const {
2215 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2216 //
2217 // (a) If one of the classes is Memory, the whole argument is passed in
2218 // memory.
2219 //
2220 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2221 // memory.
2222 //
2223 // (c) If the size of the aggregate exceeds two eightbytes and the first
2224 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2225 // argument is passed in memory. NOTE: This is necessary to keep the
2226 // ABI working for processors that don't support the __m256 type.
2227 //
2228 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2229 //
2230 // Some of these are enforced by the merging logic. Others can arise
2231 // only with unions; for example:
2232 // union { _Complex double; unsigned; }
2233 //
2234 // Note that clauses (b) and (c) were added in 0.98.
2235 //
2236 if (Hi == Memory)
2237 Lo = Memory;
2238 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2239 Lo = Memory;
2240 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2241 Lo = Memory;
2242 if (Hi == SSEUp && Lo != SSE)
2243 Hi = SSE;
2244}
2245
Chris Lattnerd776fb12010-06-28 21:43:59 +00002246X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002247 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2248 // classified recursively so that always two fields are
2249 // considered. The resulting class is calculated according to
2250 // the classes of the fields in the eightbyte:
2251 //
2252 // (a) If both classes are equal, this is the resulting class.
2253 //
2254 // (b) If one of the classes is NO_CLASS, the resulting class is
2255 // the other class.
2256 //
2257 // (c) If one of the classes is MEMORY, the result is the MEMORY
2258 // class.
2259 //
2260 // (d) If one of the classes is INTEGER, the result is the
2261 // INTEGER.
2262 //
2263 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2264 // MEMORY is used as class.
2265 //
2266 // (f) Otherwise class SSE is used.
2267
2268 // Accum should never be memory (we should have returned) or
2269 // ComplexX87 (because this cannot be passed in a structure).
2270 assert((Accum != Memory && Accum != ComplexX87) &&
2271 "Invalid accumulated classification during merge.");
2272 if (Accum == Field || Field == NoClass)
2273 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002274 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002275 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002276 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002277 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002278 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002279 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002280 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2281 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002282 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002283 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002284}
2285
Chris Lattner5c740f12010-06-30 19:14:05 +00002286void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002287 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002288 // FIXME: This code can be simplified by introducing a simple value class for
2289 // Class pairs with appropriate constructor methods for the various
2290 // situations.
2291
2292 // FIXME: Some of the split computations are wrong; unaligned vectors
2293 // shouldn't be passed in registers for example, so there is no chance they
2294 // can straddle an eightbyte. Verify & simplify.
2295
2296 Lo = Hi = NoClass;
2297
2298 Class &Current = OffsetBase < 64 ? Lo : Hi;
2299 Current = Memory;
2300
John McCall9dd450b2009-09-21 23:43:11 +00002301 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002302 BuiltinType::Kind k = BT->getKind();
2303
2304 if (k == BuiltinType::Void) {
2305 Current = NoClass;
2306 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2307 Lo = Integer;
2308 Hi = Integer;
2309 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2310 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002311 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002312 Current = SSE;
2313 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002314 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2315 if (LDF == &llvm::APFloat::IEEEquad) {
2316 Lo = SSE;
2317 Hi = SSEUp;
2318 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2319 Lo = X87;
2320 Hi = X87Up;
2321 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2322 Current = SSE;
2323 } else
2324 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002325 }
2326 // FIXME: _Decimal32 and _Decimal64 are SSE.
2327 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002328 return;
2329 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002330
Chris Lattnerd776fb12010-06-28 21:43:59 +00002331 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002332 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002333 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002334 return;
2335 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002336
Chris Lattnerd776fb12010-06-28 21:43:59 +00002337 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002338 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002339 return;
2340 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002341
Chris Lattnerd776fb12010-06-28 21:43:59 +00002342 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002343 if (Ty->isMemberFunctionPointerType()) {
2344 if (Has64BitPointers) {
2345 // If Has64BitPointers, this is an {i64, i64}, so classify both
2346 // Lo and Hi now.
2347 Lo = Hi = Integer;
2348 } else {
2349 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2350 // straddles an eightbyte boundary, Hi should be classified as well.
2351 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2352 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2353 if (EB_FuncPtr != EB_ThisAdj) {
2354 Lo = Hi = Integer;
2355 } else {
2356 Current = Integer;
2357 }
2358 }
2359 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002360 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002361 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002362 return;
2363 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002364
Chris Lattnerd776fb12010-06-28 21:43:59 +00002365 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002366 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002367 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2368 // gcc passes the following as integer:
2369 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2370 // 2 bytes - <2 x char>, <1 x short>
2371 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002372 Current = Integer;
2373
2374 // If this type crosses an eightbyte boundary, it should be
2375 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002376 uint64_t EB_Lo = (OffsetBase) / 64;
2377 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2378 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002379 Hi = Lo;
2380 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002381 QualType ElementType = VT->getElementType();
2382
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002383 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002384 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002385 return;
2386
David Majnemere2ae2282016-03-04 05:26:16 +00002387 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2388 // pass them as integer. For platforms where clang is the de facto
2389 // platform compiler, we must continue to use integer.
2390 if (!classifyIntegerMMXAsSSE() &&
2391 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2392 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2393 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2394 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002395 Current = Integer;
2396 else
2397 Current = SSE;
2398
2399 // If this type crosses an eightbyte boundary, it should be
2400 // split.
2401 if (OffsetBase && OffsetBase != 64)
2402 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002403 } else if (Size == 128 ||
2404 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002405 // Arguments of 256-bits are split into four eightbyte chunks. The
2406 // least significant one belongs to class SSE and all the others to class
2407 // SSEUP. The original Lo and Hi design considers that types can't be
2408 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2409 // This design isn't correct for 256-bits, but since there're no cases
2410 // where the upper parts would need to be inspected, avoid adding
2411 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002412 //
2413 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2414 // registers if they are "named", i.e. not part of the "..." of a
2415 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002416 //
2417 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2418 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002419 Lo = SSE;
2420 Hi = SSEUp;
2421 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002422 return;
2423 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002424
Chris Lattnerd776fb12010-06-28 21:43:59 +00002425 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002426 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002427
Chris Lattner2b037972010-07-29 02:01:43 +00002428 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002429 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002430 if (Size <= 64)
2431 Current = Integer;
2432 else if (Size <= 128)
2433 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002434 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002435 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002436 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002437 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002438 } else if (ET == getContext().LongDoubleTy) {
2439 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2440 if (LDF == &llvm::APFloat::IEEEquad)
2441 Current = Memory;
2442 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2443 Current = ComplexX87;
2444 else if (LDF == &llvm::APFloat::IEEEdouble)
2445 Lo = Hi = SSE;
2446 else
2447 llvm_unreachable("unexpected long double representation!");
2448 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002449
2450 // If this complex type crosses an eightbyte boundary then it
2451 // should be split.
2452 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002453 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002454 if (Hi == NoClass && EB_Real != EB_Imag)
2455 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002456
Chris Lattnerd776fb12010-06-28 21:43:59 +00002457 return;
2458 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002459
Chris Lattner2b037972010-07-29 02:01:43 +00002460 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002461 // Arrays are treated like structures.
2462
Chris Lattner2b037972010-07-29 02:01:43 +00002463 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002464
2465 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002466 // than four eightbytes, ..., it has class MEMORY.
2467 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002468 return;
2469
2470 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2471 // fields, it has class MEMORY.
2472 //
2473 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002474 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002475 return;
2476
2477 // Otherwise implement simplified merge. We could be smarter about
2478 // this, but it isn't worth it and would be harder to verify.
2479 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002480 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002481 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002482
2483 // The only case a 256-bit wide vector could be used is when the array
2484 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2485 // to work for sizes wider than 128, early check and fallback to memory.
2486 if (Size > 128 && EltSize != 256)
2487 return;
2488
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002489 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2490 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002491 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002492 Lo = merge(Lo, FieldLo);
2493 Hi = merge(Hi, FieldHi);
2494 if (Lo == Memory || Hi == Memory)
2495 break;
2496 }
2497
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002498 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002499 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002500 return;
2501 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002502
Chris Lattnerd776fb12010-06-28 21:43:59 +00002503 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002504 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002505
2506 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002507 // than four eightbytes, ..., it has class MEMORY.
2508 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002509 return;
2510
Anders Carlsson20759ad2009-09-16 15:53:40 +00002511 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2512 // copy constructor or a non-trivial destructor, it is passed by invisible
2513 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002514 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002515 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002516
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002517 const RecordDecl *RD = RT->getDecl();
2518
2519 // Assume variable sized types are passed in memory.
2520 if (RD->hasFlexibleArrayMember())
2521 return;
2522
Chris Lattner2b037972010-07-29 02:01:43 +00002523 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002524
2525 // Reset Lo class, this will be recomputed.
2526 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002527
2528 // If this is a C++ record, classify the bases first.
2529 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002530 for (const auto &I : CXXRD->bases()) {
2531 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002532 "Unexpected base class!");
2533 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002534 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002535
2536 // Classify this field.
2537 //
2538 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2539 // single eightbyte, each is classified separately. Each eightbyte gets
2540 // initialized to class NO_CLASS.
2541 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002542 uint64_t Offset =
2543 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002544 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002545 Lo = merge(Lo, FieldLo);
2546 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002547 if (Lo == Memory || Hi == Memory) {
2548 postMerge(Size, Lo, Hi);
2549 return;
2550 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002551 }
2552 }
2553
2554 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002556 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002557 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002558 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2559 bool BitField = i->isBitField();
2560
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002561 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2562 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002563 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002564 // The only case a 256-bit wide vector could be used is when the struct
2565 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2566 // to work for sizes wider than 128, early check and fallback to memory.
2567 //
2568 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2569 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002570 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002571 return;
2572 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002573 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002574 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002575 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002576 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002577 return;
2578 }
2579
2580 // Classify this field.
2581 //
2582 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2583 // exceeds a single eightbyte, each is classified
2584 // separately. Each eightbyte gets initialized to class
2585 // NO_CLASS.
2586 Class FieldLo, FieldHi;
2587
2588 // Bit-fields require special handling, they do not force the
2589 // structure to be passed in memory even if unaligned, and
2590 // therefore they can straddle an eightbyte.
2591 if (BitField) {
2592 // Ignore padding bit-fields.
2593 if (i->isUnnamedBitfield())
2594 continue;
2595
2596 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002597 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002598
2599 uint64_t EB_Lo = Offset / 64;
2600 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002601
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002602 if (EB_Lo) {
2603 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2604 FieldLo = NoClass;
2605 FieldHi = Integer;
2606 } else {
2607 FieldLo = Integer;
2608 FieldHi = EB_Hi ? Integer : NoClass;
2609 }
2610 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002611 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002612 Lo = merge(Lo, FieldLo);
2613 Hi = merge(Hi, FieldHi);
2614 if (Lo == Memory || Hi == Memory)
2615 break;
2616 }
2617
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002618 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002619 }
2620}
2621
Chris Lattner22a931e2010-06-29 06:01:59 +00002622ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002623 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2624 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002625 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002626 // Treat an enum type as its underlying type.
2627 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2628 Ty = EnumTy->getDecl()->getIntegerType();
2629
2630 return (Ty->isPromotableIntegerType() ?
2631 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2632 }
2633
John McCall7f416cc2015-09-08 08:05:57 +00002634 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002635}
2636
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002637bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2638 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2639 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002640 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002641 if (Size <= 64 || Size > LargestVector)
2642 return true;
2643 }
2644
2645 return false;
2646}
2647
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002648ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2649 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002650 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2651 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002652 //
2653 // This assumption is optimistic, as there could be free registers available
2654 // when we need to pass this argument in memory, and LLVM could try to pass
2655 // the argument in the free register. This does not seem to happen currently,
2656 // but this code would be much safer if we could mark the argument with
2657 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002658 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002659 // Treat an enum type as its underlying type.
2660 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2661 Ty = EnumTy->getDecl()->getIntegerType();
2662
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002663 return (Ty->isPromotableIntegerType() ?
2664 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002665 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002666
Mark Lacey3825e832013-10-06 01:33:34 +00002667 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002668 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002669
Chris Lattner44c2b902011-05-22 23:21:23 +00002670 // Compute the byval alignment. We specify the alignment of the byval in all
2671 // cases so that the mid-level optimizer knows the alignment of the byval.
2672 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002673
2674 // Attempt to avoid passing indirect results using byval when possible. This
2675 // is important for good codegen.
2676 //
2677 // We do this by coercing the value into a scalar type which the backend can
2678 // handle naturally (i.e., without using byval).
2679 //
2680 // For simplicity, we currently only do this when we have exhausted all of the
2681 // free integer registers. Doing this when there are free integer registers
2682 // would require more care, as we would have to ensure that the coerced value
2683 // did not claim the unused register. That would require either reording the
2684 // arguments to the function (so that any subsequent inreg values came first),
2685 // or only doing this optimization when there were no following arguments that
2686 // might be inreg.
2687 //
2688 // We currently expect it to be rare (particularly in well written code) for
2689 // arguments to be passed on the stack when there are still free integer
2690 // registers available (this would typically imply large structs being passed
2691 // by value), so this seems like a fair tradeoff for now.
2692 //
2693 // We can revisit this if the backend grows support for 'onstack' parameter
2694 // attributes. See PR12193.
2695 if (freeIntRegs == 0) {
2696 uint64_t Size = getContext().getTypeSize(Ty);
2697
2698 // If this type fits in an eightbyte, coerce it into the matching integral
2699 // type, which will end up on the stack (with alignment 8).
2700 if (Align == 8 && Size <= 64)
2701 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2702 Size));
2703 }
2704
John McCall7f416cc2015-09-08 08:05:57 +00002705 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002706}
2707
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002708/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2709/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002710llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002711 // Wrapper structs/arrays that only contain vectors are passed just like
2712 // vectors; strip them off if present.
2713 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2714 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002715
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002716 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002717 if (isa<llvm::VectorType>(IRType) ||
2718 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002719 return IRType;
2720
2721 // We couldn't find the preferred IR vector type for 'Ty'.
2722 uint64_t Size = getContext().getTypeSize(Ty);
2723 assert((Size == 128 || Size == 256) && "Invalid type found!");
2724
2725 // Return a LLVM IR vector type based on the size of 'Ty'.
2726 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2727 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002728}
2729
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002730/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2731/// is known to either be off the end of the specified type or being in
2732/// alignment padding. The user type specified is known to be at most 128 bits
2733/// in size, and have passed through X86_64ABIInfo::classify with a successful
2734/// classification that put one of the two halves in the INTEGER class.
2735///
2736/// It is conservatively correct to return false.
2737static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2738 unsigned EndBit, ASTContext &Context) {
2739 // If the bytes being queried are off the end of the type, there is no user
2740 // data hiding here. This handles analysis of builtins, vectors and other
2741 // types that don't contain interesting padding.
2742 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2743 if (TySize <= StartBit)
2744 return true;
2745
Chris Lattner98076a22010-07-29 07:43:55 +00002746 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2747 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2748 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2749
2750 // Check each element to see if the element overlaps with the queried range.
2751 for (unsigned i = 0; i != NumElts; ++i) {
2752 // If the element is after the span we care about, then we're done..
2753 unsigned EltOffset = i*EltSize;
2754 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002755
Chris Lattner98076a22010-07-29 07:43:55 +00002756 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2757 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2758 EndBit-EltOffset, Context))
2759 return false;
2760 }
2761 // If it overlaps no elements, then it is safe to process as padding.
2762 return true;
2763 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002764
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002765 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2766 const RecordDecl *RD = RT->getDecl();
2767 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002768
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002769 // If this is a C++ record, check the bases first.
2770 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002771 for (const auto &I : CXXRD->bases()) {
2772 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002773 "Unexpected base class!");
2774 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002775 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002776
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002777 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002778 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002779 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002780
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002781 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002782 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002783 EndBit-BaseOffset, Context))
2784 return false;
2785 }
2786 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002787
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002788 // Verify that no field has data that overlaps the region of interest. Yes
2789 // this could be sped up a lot by being smarter about queried fields,
2790 // however we're only looking at structs up to 16 bytes, so we don't care
2791 // much.
2792 unsigned idx = 0;
2793 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2794 i != e; ++i, ++idx) {
2795 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002796
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002797 // If we found a field after the region we care about, then we're done.
2798 if (FieldOffset >= EndBit) break;
2799
2800 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2801 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2802 Context))
2803 return false;
2804 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002805
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002806 // If nothing in this record overlapped the area of interest, then we're
2807 // clean.
2808 return true;
2809 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002810
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002811 return false;
2812}
2813
Chris Lattnere556a712010-07-29 18:39:32 +00002814/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2815/// float member at the specified offset. For example, {int,{float}} has a
2816/// float at offset 4. It is conservatively correct for this routine to return
2817/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002818static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002819 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002820 // Base case if we find a float.
2821 if (IROffset == 0 && IRType->isFloatTy())
2822 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002823
Chris Lattnere556a712010-07-29 18:39:32 +00002824 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002825 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002826 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2827 unsigned Elt = SL->getElementContainingOffset(IROffset);
2828 IROffset -= SL->getElementOffset(Elt);
2829 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2830 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002831
Chris Lattnere556a712010-07-29 18:39:32 +00002832 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002833 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2834 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002835 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2836 IROffset -= IROffset/EltSize*EltSize;
2837 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2838 }
2839
2840 return false;
2841}
2842
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002843
2844/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2845/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002846llvm::Type *X86_64ABIInfo::
2847GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002848 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002849 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002850 // pass as float if the last 4 bytes is just padding. This happens for
2851 // structs that contain 3 floats.
2852 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2853 SourceOffset*8+64, getContext()))
2854 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002855
Chris Lattnere556a712010-07-29 18:39:32 +00002856 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2857 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2858 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002859 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2860 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002861 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002862
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002863 return llvm::Type::getDoubleTy(getVMContext());
2864}
2865
2866
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002867/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2868/// an 8-byte GPR. This means that we either have a scalar or we are talking
2869/// about the high or low part of an up-to-16-byte struct. This routine picks
2870/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002871/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2872/// etc).
2873///
2874/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2875/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2876/// the 8-byte value references. PrefType may be null.
2877///
Alp Toker9907f082014-07-09 14:06:35 +00002878/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002879/// an offset into this that we're processing (which is always either 0 or 8).
2880///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002881llvm::Type *X86_64ABIInfo::
2882GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002883 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002884 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2885 // returning an 8-byte unit starting with it. See if we can safely use it.
2886 if (IROffset == 0) {
2887 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002888 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2889 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002890 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002891
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002892 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2893 // goodness in the source type is just tail padding. This is allowed to
2894 // kick in for struct {double,int} on the int, but not on
2895 // struct{double,int,int} because we wouldn't return the second int. We
2896 // have to do this analysis on the source type because we can't depend on
2897 // unions being lowered a specific way etc.
2898 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002899 IRType->isIntegerTy(32) ||
2900 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2901 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2902 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002903
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002904 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2905 SourceOffset*8+64, getContext()))
2906 return IRType;
2907 }
2908 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002909
Chris Lattner2192fe52011-07-18 04:24:23 +00002910 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002911 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002912 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002913 if (IROffset < SL->getSizeInBytes()) {
2914 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2915 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002916
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002917 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2918 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002919 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002920 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002921
Chris Lattner2192fe52011-07-18 04:24:23 +00002922 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002923 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002924 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002925 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002926 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2927 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002928 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002929
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002930 // Okay, we don't have any better idea of what to pass, so we pass this in an
2931 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002932 unsigned TySizeInBytes =
2933 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002934
Chris Lattner3f763422010-07-29 17:34:39 +00002935 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002936
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002937 // It is always safe to classify this as an integer type up to i64 that
2938 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002939 return llvm::IntegerType::get(getVMContext(),
2940 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002941}
2942
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002943
2944/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2945/// be used as elements of a two register pair to pass or return, return a
2946/// first class aggregate to represent them. For example, if the low part of
2947/// a by-value argument should be passed as i32* and the high part as float,
2948/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002949static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002950GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002951 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002952 // In order to correctly satisfy the ABI, we need to the high part to start
2953 // at offset 8. If the high and low parts we inferred are both 4-byte types
2954 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2955 // the second element at offset 8. Check for this:
2956 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2957 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002958 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002959 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002960
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002961 // To handle this, we have to increase the size of the low part so that the
2962 // second element will start at an 8 byte offset. We can't increase the size
2963 // of the second element because it might make us access off the end of the
2964 // struct.
2965 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002966 // There are usually two sorts of types the ABI generation code can produce
2967 // for the low part of a pair that aren't 8 bytes in size: float or
2968 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2969 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002970 // Promote these to a larger type.
2971 if (Lo->isFloatTy())
2972 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2973 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002974 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2975 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002976 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2977 }
2978 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002979
Reid Kleckneree7cf842014-12-01 22:02:27 +00002980 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002981
2982
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002983 // Verify that the second element is at an 8-byte offset.
2984 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2985 "Invalid x86-64 argument pair!");
2986 return Result;
2987}
2988
Chris Lattner31faff52010-07-28 23:06:14 +00002989ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002990classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002991 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2992 // classification algorithm.
2993 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002994 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002995
2996 // Check some invariants.
2997 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002998 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2999
Craig Topper8a13c412014-05-21 05:09:00 +00003000 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003001 switch (Lo) {
3002 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003003 if (Hi == NoClass)
3004 return ABIArgInfo::getIgnore();
3005 // If the low part is just padding, it takes no register, leave ResType
3006 // null.
3007 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3008 "Unknown missing lo part");
3009 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003010
3011 case SSEUp:
3012 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003013 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003014
3015 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3016 // hidden argument.
3017 case Memory:
3018 return getIndirectReturnResult(RetTy);
3019
3020 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3021 // available register of the sequence %rax, %rdx is used.
3022 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003023 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003024
Chris Lattner1f3a0632010-07-29 21:42:50 +00003025 // If we have a sign or zero extended integer, make sure to return Extend
3026 // so that the parameter gets the right LLVM IR attributes.
3027 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3028 // Treat an enum type as its underlying type.
3029 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3030 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003031
Chris Lattner1f3a0632010-07-29 21:42:50 +00003032 if (RetTy->isIntegralOrEnumerationType() &&
3033 RetTy->isPromotableIntegerType())
3034 return ABIArgInfo::getExtend();
3035 }
Chris Lattner31faff52010-07-28 23:06:14 +00003036 break;
3037
3038 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3039 // available SSE register of the sequence %xmm0, %xmm1 is used.
3040 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003041 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003042 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003043
3044 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3045 // returned on the X87 stack in %st0 as 80-bit x87 number.
3046 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003047 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003048 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003049
3050 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3051 // part of the value is returned in %st0 and the imaginary part in
3052 // %st1.
3053 case ComplexX87:
3054 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003055 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003056 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003057 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003058 break;
3059 }
3060
Craig Topper8a13c412014-05-21 05:09:00 +00003061 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003062 switch (Hi) {
3063 // Memory was handled previously and X87 should
3064 // never occur as a hi class.
3065 case Memory:
3066 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003067 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003068
3069 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003070 case NoClass:
3071 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003072
Chris Lattner52b3c132010-09-01 00:20:33 +00003073 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003074 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003075 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3076 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003077 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003078 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003079 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003080 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3081 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003082 break;
3083
3084 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003085 // is passed in the next available eightbyte chunk if the last used
3086 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003087 //
Chris Lattner57540c52011-04-15 05:22:18 +00003088 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003089 case SSEUp:
3090 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003091 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003092 break;
3093
3094 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3095 // returned together with the previous X87 value in %st0.
3096 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003097 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003098 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003099 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003100 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003101 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003102 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003103 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3104 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003105 }
Chris Lattner31faff52010-07-28 23:06:14 +00003106 break;
3107 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003108
Chris Lattner52b3c132010-09-01 00:20:33 +00003109 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003110 // known to pass in the high eightbyte of the result. We do this by forming a
3111 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003112 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003113 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003114
Chris Lattner1f3a0632010-07-29 21:42:50 +00003115 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003116}
3117
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003118ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003119 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3120 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003121 const
3122{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003123 Ty = useFirstFieldIfTransparentUnion(Ty);
3124
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003125 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003126 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003127
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003128 // Check some invariants.
3129 // FIXME: Enforce these by construction.
3130 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003131 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3132
3133 neededInt = 0;
3134 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003135 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003136 switch (Lo) {
3137 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003138 if (Hi == NoClass)
3139 return ABIArgInfo::getIgnore();
3140 // If the low part is just padding, it takes no register, leave ResType
3141 // null.
3142 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3143 "Unknown missing lo part");
3144 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003145
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003146 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3147 // on the stack.
3148 case Memory:
3149
3150 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3151 // COMPLEX_X87, it is passed in memory.
3152 case X87:
3153 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003154 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003155 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003156 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003157
3158 case SSEUp:
3159 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003160 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003161
3162 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3163 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3164 // and %r9 is used.
3165 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003166 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003167
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003168 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003169 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003170
3171 // If we have a sign or zero extended integer, make sure to return Extend
3172 // so that the parameter gets the right LLVM IR attributes.
3173 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3174 // Treat an enum type as its underlying type.
3175 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3176 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003177
Chris Lattner1f3a0632010-07-29 21:42:50 +00003178 if (Ty->isIntegralOrEnumerationType() &&
3179 Ty->isPromotableIntegerType())
3180 return ABIArgInfo::getExtend();
3181 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003182
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003183 break;
3184
3185 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3186 // available SSE register is used, the registers are taken in the
3187 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003188 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003189 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003190 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003191 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003192 break;
3193 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003194 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003195
Craig Topper8a13c412014-05-21 05:09:00 +00003196 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003197 switch (Hi) {
3198 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003199 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003200 // which is passed in memory.
3201 case Memory:
3202 case X87:
3203 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003204 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003205
3206 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003207
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003208 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003209 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003210 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003211 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003212
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003213 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3214 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003215 break;
3216
3217 // X87Up generally doesn't occur here (long double is passed in
3218 // memory), except in situations involving unions.
3219 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003220 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003221 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003222
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003223 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3224 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003225
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003226 ++neededSSE;
3227 break;
3228
3229 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3230 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003231 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003232 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003233 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003234 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003235 break;
3236 }
3237
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003238 // If a high part was specified, merge it together with the low part. It is
3239 // known to pass in the high eightbyte of the result. We do this by forming a
3240 // first class struct aggregate with the high and low part: {low, high}
3241 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003242 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003243
Chris Lattner1f3a0632010-07-29 21:42:50 +00003244 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003245}
3246
Chris Lattner22326a12010-07-29 02:31:05 +00003247void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003248
Reid Kleckner40ca9132014-05-13 22:05:45 +00003249 if (!getCXXABI().classifyReturnType(FI))
3250 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003251
3252 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003253 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003254
3255 // If the return value is indirect, then the hidden argument is consuming one
3256 // integer register.
3257 if (FI.getReturnInfo().isIndirect())
3258 --freeIntRegs;
3259
Peter Collingbournef7706832014-12-12 23:41:25 +00003260 // The chain argument effectively gives us another free register.
3261 if (FI.isChainCall())
3262 ++freeIntRegs;
3263
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003264 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003265 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3266 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003267 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003268 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003269 it != ie; ++it, ++ArgNo) {
3270 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003271
Bill Wendling9987c0e2010-10-18 23:51:38 +00003272 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003273 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003274 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003275
3276 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3277 // eightbyte of an argument, the whole argument is passed on the
3278 // stack. If registers have already been assigned for some
3279 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003280 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003281 freeIntRegs -= neededInt;
3282 freeSSERegs -= neededSSE;
3283 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003284 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003285 }
3286 }
3287}
3288
John McCall7f416cc2015-09-08 08:05:57 +00003289static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3290 Address VAListAddr, QualType Ty) {
3291 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3292 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003293 llvm::Value *overflow_arg_area =
3294 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3295
3296 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3297 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003298 // It isn't stated explicitly in the standard, but in practice we use
3299 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003300 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3301 if (Align > CharUnits::fromQuantity(8)) {
3302 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3303 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003304 }
3305
3306 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003307 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003308 llvm::Value *Res =
3309 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003310 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003311
3312 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3313 // l->overflow_arg_area + sizeof(type).
3314 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3315 // an 8 byte boundary.
3316
3317 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003318 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003319 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003320 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3321 "overflow_arg_area.next");
3322 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3323
3324 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003325 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003326}
3327
John McCall7f416cc2015-09-08 08:05:57 +00003328Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3329 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003330 // Assume that va_list type is correct; should be pointer to LLVM type:
3331 // struct {
3332 // i32 gp_offset;
3333 // i32 fp_offset;
3334 // i8* overflow_arg_area;
3335 // i8* reg_save_area;
3336 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003337 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003338
John McCall7f416cc2015-09-08 08:05:57 +00003339 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003340 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003341 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003342
3343 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3344 // in the registers. If not go to step 7.
3345 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003346 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003347
3348 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3349 // general purpose registers needed to pass type and num_fp to hold
3350 // the number of floating point registers needed.
3351
3352 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3353 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3354 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3355 //
3356 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3357 // register save space).
3358
Craig Topper8a13c412014-05-21 05:09:00 +00003359 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003360 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3361 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003362 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003363 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003364 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3365 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003366 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003367 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3368 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003369 }
3370
3371 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003372 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003373 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3374 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003375 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3376 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003377 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3378 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003379 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3380 }
3381
3382 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3383 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3384 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3385 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3386
3387 // Emit code to load the value if it was passed in registers.
3388
3389 CGF.EmitBlock(InRegBlock);
3390
3391 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3392 // an offset of l->gp_offset and/or l->fp_offset. This may require
3393 // copying to a temporary location in case the parameter is passed
3394 // in different register classes or requires an alignment greater
3395 // than 8 for general purpose registers and 16 for XMM registers.
3396 //
3397 // FIXME: This really results in shameful code when we end up needing to
3398 // collect arguments from different places; often what should result in a
3399 // simple assembling of a structure from scattered addresses has many more
3400 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003401 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003402 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3403 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3404 "reg_save_area");
3405
3406 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003407 if (neededInt && neededSSE) {
3408 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003409 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003410 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003411 Address Tmp = CGF.CreateMemTemp(Ty);
3412 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003413 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003414 llvm::Type *TyLo = ST->getElementType(0);
3415 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003416 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003417 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003418 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3419 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003420 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3421 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003422 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3423 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003424
John McCall7f416cc2015-09-08 08:05:57 +00003425 // Copy the first element.
3426 llvm::Value *V =
3427 CGF.Builder.CreateDefaultAlignedLoad(
3428 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3429 CGF.Builder.CreateStore(V,
3430 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3431
3432 // Copy the second element.
3433 V = CGF.Builder.CreateDefaultAlignedLoad(
3434 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3435 CharUnits Offset = CharUnits::fromQuantity(
3436 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3437 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3438
3439 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003440 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003441 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3442 CharUnits::fromQuantity(8));
3443 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003444
3445 // Copy to a temporary if necessary to ensure the appropriate alignment.
3446 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003447 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003448 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003449 CharUnits TyAlign = SizeAlign.second;
3450
3451 // Copy into a temporary if the type is more aligned than the
3452 // register save area.
3453 if (TyAlign.getQuantity() > 8) {
3454 Address Tmp = CGF.CreateMemTemp(Ty);
3455 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003456 RegAddr = Tmp;
3457 }
John McCall7f416cc2015-09-08 08:05:57 +00003458
Chris Lattner0cf24192010-06-28 20:05:43 +00003459 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003460 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3461 CharUnits::fromQuantity(16));
3462 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003463 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003464 assert(neededSSE == 2 && "Invalid number of needed registers!");
3465 // SSE registers are spaced 16 bytes apart in the register save
3466 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003467 // The ABI isn't explicit about this, but it seems reasonable
3468 // to assume that the slots are 16-byte aligned, since the stack is
3469 // naturally 16-byte aligned and the prologue is expected to store
3470 // all the SSE registers to the RSA.
3471 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3472 CharUnits::fromQuantity(16));
3473 Address RegAddrHi =
3474 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3475 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003476 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003477 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003478 llvm::Value *V;
3479 Address Tmp = CGF.CreateMemTemp(Ty);
3480 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3481 V = CGF.Builder.CreateLoad(
3482 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3483 CGF.Builder.CreateStore(V,
3484 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3485 V = CGF.Builder.CreateLoad(
3486 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3487 CGF.Builder.CreateStore(V,
3488 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3489
3490 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003491 }
3492
3493 // AMD64-ABI 3.5.7p5: Step 5. Set:
3494 // l->gp_offset = l->gp_offset + num_gp * 8
3495 // l->fp_offset = l->fp_offset + num_fp * 16.
3496 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003497 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003498 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3499 gp_offset_p);
3500 }
3501 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003502 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003503 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3504 fp_offset_p);
3505 }
3506 CGF.EmitBranch(ContBlock);
3507
3508 // Emit code to load the value if it was passed in memory.
3509
3510 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003511 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003512
3513 // Return the appropriate result.
3514
3515 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003516 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3517 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003518 return ResAddr;
3519}
3520
Charles Davisc7d5c942015-09-17 20:55:33 +00003521Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3522 QualType Ty) const {
3523 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3524 CGF.getContext().getTypeInfoInChars(Ty),
3525 CharUnits::fromQuantity(8),
3526 /*allowHigherAlign*/ false);
3527}
3528
Reid Kleckner80944df2014-10-31 22:00:51 +00003529ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3530 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003531
3532 if (Ty->isVoidType())
3533 return ABIArgInfo::getIgnore();
3534
3535 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3536 Ty = EnumTy->getDecl()->getIntegerType();
3537
Reid Kleckner80944df2014-10-31 22:00:51 +00003538 TypeInfo Info = getContext().getTypeInfo(Ty);
3539 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003540 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003541
Reid Kleckner9005f412014-05-02 00:51:20 +00003542 const RecordType *RT = Ty->getAs<RecordType>();
3543 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003544 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003545 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003546 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003547 }
3548
3549 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003550 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003551
Reid Kleckner9005f412014-05-02 00:51:20 +00003552 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003553
Reid Kleckner80944df2014-10-31 22:00:51 +00003554 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3555 // other targets.
3556 const Type *Base = nullptr;
3557 uint64_t NumElts = 0;
3558 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3559 if (FreeSSERegs >= NumElts) {
3560 FreeSSERegs -= NumElts;
3561 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3562 return ABIArgInfo::getDirect();
3563 return ABIArgInfo::getExpand();
3564 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003565 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003566 }
3567
3568
Reid Klecknerec87fec2014-05-02 01:17:12 +00003569 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003570 // If the member pointer is represented by an LLVM int or ptr, pass it
3571 // directly.
3572 llvm::Type *LLTy = CGT.ConvertType(Ty);
3573 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3574 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003575 }
3576
Michael Kuperstein4f818702015-02-24 09:35:58 +00003577 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003578 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3579 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003580 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003581 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003582
Reid Kleckner9005f412014-05-02 00:51:20 +00003583 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003584 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003585 }
3586
Julien Lerouge10dcff82014-08-27 00:36:55 +00003587 // Bool type is always extended to the ABI, other builtin types are not
3588 // extended.
3589 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3590 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003591 return ABIArgInfo::getExtend();
3592
Reid Kleckner11a17192015-10-28 22:29:52 +00003593 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3594 // passes them indirectly through memory.
3595 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3596 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3597 if (LDF == &llvm::APFloat::x87DoubleExtended)
3598 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3599 }
3600
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003601 return ABIArgInfo::getDirect();
3602}
3603
3604void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003605 bool IsVectorCall =
3606 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003607
Reid Kleckner80944df2014-10-31 22:00:51 +00003608 // We can use up to 4 SSE return registers with vectorcall.
3609 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3610 if (!getCXXABI().classifyReturnType(FI))
3611 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3612
3613 // We can use up to 6 SSE register parameters with vectorcall.
3614 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003615 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003616 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003617}
3618
John McCall7f416cc2015-09-08 08:05:57 +00003619Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3620 QualType Ty) const {
3621 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3622 CGF.getContext().getTypeInfoInChars(Ty),
3623 CharUnits::fromQuantity(8),
3624 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003625}
Chris Lattner0cf24192010-06-28 20:05:43 +00003626
John McCallea8d8bb2010-03-11 00:10:12 +00003627// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003628namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003629/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3630class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003631bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003632public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003633 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3634 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003635
John McCall7f416cc2015-09-08 08:05:57 +00003636 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3637 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003638};
3639
3640class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3641public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003642 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3643 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003644
Craig Topper4f12f102014-03-12 06:41:41 +00003645 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003646 // This is recovered from gcc output.
3647 return 1; // r1 is the dedicated stack pointer
3648 }
3649
3650 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003651 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003652};
3653
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003654}
John McCallea8d8bb2010-03-11 00:10:12 +00003655
James Y Knight29b5f082016-02-24 02:59:33 +00003656// TODO: this implementation is now likely redundant with
3657// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003658Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3659 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003660 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003661 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3662 // TODO: Implement this. For now ignore.
3663 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003664 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003665 }
3666
John McCall7f416cc2015-09-08 08:05:57 +00003667 // struct __va_list_tag {
3668 // unsigned char gpr;
3669 // unsigned char fpr;
3670 // unsigned short reserved;
3671 // void *overflow_arg_area;
3672 // void *reg_save_area;
3673 // };
3674
Roman Divacky8a12d842014-11-03 18:32:54 +00003675 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003676 bool isInt =
3677 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003678 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003679
3680 // All aggregates are passed indirectly? That doesn't seem consistent
3681 // with the argument-lowering code.
3682 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003683
3684 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003685
3686 // The calling convention either uses 1-2 GPRs or 1 FPR.
3687 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003688 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003689 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3690 } else {
3691 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003692 }
John McCall7f416cc2015-09-08 08:05:57 +00003693
3694 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3695
3696 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003697 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003698 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3699 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3700 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003701
Eric Christopher7565e0d2015-05-29 23:09:49 +00003702 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003703 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003704
3705 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3706 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3707 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3708
3709 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3710
John McCall7f416cc2015-09-08 08:05:57 +00003711 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3712 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003713
John McCall7f416cc2015-09-08 08:05:57 +00003714 // Case 1: consume registers.
3715 Address RegAddr = Address::invalid();
3716 {
3717 CGF.EmitBlock(UsingRegs);
3718
3719 Address RegSaveAreaPtr =
3720 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3721 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3722 CharUnits::fromQuantity(8));
3723 assert(RegAddr.getElementType() == CGF.Int8Ty);
3724
3725 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003726 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003727 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3728 CharUnits::fromQuantity(32));
3729 }
3730
3731 // Get the address of the saved value by scaling the number of
3732 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003733 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003734 llvm::Value *RegOffset =
3735 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3736 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3737 RegAddr.getPointer(), RegOffset),
3738 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3739 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3740
3741 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003742 NumRegs =
3743 Builder.CreateAdd(NumRegs,
3744 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003745 Builder.CreateStore(NumRegs, NumRegsAddr);
3746
3747 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003748 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003749
John McCall7f416cc2015-09-08 08:05:57 +00003750 // Case 2: consume space in the overflow area.
3751 Address MemAddr = Address::invalid();
3752 {
3753 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003754
Roman Divacky039b9702016-02-20 08:31:24 +00003755 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3756
John McCall7f416cc2015-09-08 08:05:57 +00003757 // Everything in the overflow area is rounded up to a size of at least 4.
3758 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3759
3760 CharUnits Size;
3761 if (!isIndirect) {
3762 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003763 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003764 } else {
3765 Size = CGF.getPointerSize();
3766 }
3767
3768 Address OverflowAreaAddr =
3769 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003770 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003771 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003772 // Round up address of argument to alignment
3773 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3774 if (Align > OverflowAreaAlign) {
3775 llvm::Value *Ptr = OverflowArea.getPointer();
3776 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3777 Align);
3778 }
3779
John McCall7f416cc2015-09-08 08:05:57 +00003780 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3781
3782 // Increase the overflow area.
3783 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3784 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3785 CGF.EmitBranch(Cont);
3786 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003787
3788 CGF.EmitBlock(Cont);
3789
John McCall7f416cc2015-09-08 08:05:57 +00003790 // Merge the cases with a phi.
3791 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3792 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003793
John McCall7f416cc2015-09-08 08:05:57 +00003794 // Load the pointer if the argument was passed indirectly.
3795 if (isIndirect) {
3796 Result = Address(Builder.CreateLoad(Result, "aggr"),
3797 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003798 }
3799
3800 return Result;
3801}
3802
John McCallea8d8bb2010-03-11 00:10:12 +00003803bool
3804PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3805 llvm::Value *Address) const {
3806 // This is calculated from the LLVM and GCC tables and verified
3807 // against gcc output. AFAIK all ABIs use the same encoding.
3808
3809 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003810
Chris Lattnerece04092012-02-07 00:39:47 +00003811 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003812 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3813 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3814 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3815
3816 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003817 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003818
3819 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003820 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003821
3822 // 64-76 are various 4-byte special-purpose registers:
3823 // 64: mq
3824 // 65: lr
3825 // 66: ctr
3826 // 67: ap
3827 // 68-75 cr0-7
3828 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003829 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003830
3831 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003832 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003833
3834 // 109: vrsave
3835 // 110: vscr
3836 // 111: spe_acc
3837 // 112: spefscr
3838 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003839 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003840
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003841 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003842}
3843
Roman Divackyd966e722012-05-09 18:22:46 +00003844// PowerPC-64
3845
3846namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003847/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00003848class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003849public:
3850 enum ABIKind {
3851 ELFv1 = 0,
3852 ELFv2
3853 };
3854
3855private:
3856 static const unsigned GPRBits = 64;
3857 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003858 bool HasQPX;
3859
3860 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3861 // will be passed in a QPX register.
3862 bool IsQPXVectorTy(const Type *Ty) const {
3863 if (!HasQPX)
3864 return false;
3865
3866 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3867 unsigned NumElements = VT->getNumElements();
3868 if (NumElements == 1)
3869 return false;
3870
3871 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3872 if (getContext().getTypeSize(Ty) <= 256)
3873 return true;
3874 } else if (VT->getElementType()->
3875 isSpecificBuiltinType(BuiltinType::Float)) {
3876 if (getContext().getTypeSize(Ty) <= 128)
3877 return true;
3878 }
3879 }
3880
3881 return false;
3882 }
3883
3884 bool IsQPXVectorTy(QualType Ty) const {
3885 return IsQPXVectorTy(Ty.getTypePtr());
3886 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003887
3888public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003889 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
James Y Knight29b5f082016-02-24 02:59:33 +00003890 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003891
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003892 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003893 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003894
3895 ABIArgInfo classifyReturnType(QualType RetTy) const;
3896 ABIArgInfo classifyArgumentType(QualType Ty) const;
3897
Reid Klecknere9f6a712014-10-31 17:10:41 +00003898 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3899 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3900 uint64_t Members) const override;
3901
Bill Schmidt84d37792012-10-12 19:26:17 +00003902 // TODO: We can add more logic to computeInfo to improve performance.
3903 // Example: For aggregate arguments that fit in a register, we could
3904 // use getDirectInReg (as is done below for structs containing a single
3905 // floating-point value) to avoid pushing them to memory on function
3906 // entry. This would require changing the logic in PPCISelLowering
3907 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003908 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003909 if (!getCXXABI().classifyReturnType(FI))
3910 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003911 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003912 // We rely on the default argument classification for the most part.
3913 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003914 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003915 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003916 if (T) {
3917 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003918 if (IsQPXVectorTy(T) ||
3919 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003920 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003921 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003922 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003923 continue;
3924 }
3925 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003926 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003927 }
3928 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003929
John McCall7f416cc2015-09-08 08:05:57 +00003930 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3931 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003932};
3933
3934class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003935
Bill Schmidt25cb3492012-10-03 19:18:57 +00003936public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003937 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003938 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003939 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003940
Craig Topper4f12f102014-03-12 06:41:41 +00003941 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003942 // This is recovered from gcc output.
3943 return 1; // r1 is the dedicated stack pointer
3944 }
3945
3946 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003947 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003948};
3949
Roman Divackyd966e722012-05-09 18:22:46 +00003950class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3951public:
3952 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3953
Craig Topper4f12f102014-03-12 06:41:41 +00003954 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003955 // This is recovered from gcc output.
3956 return 1; // r1 is the dedicated stack pointer
3957 }
3958
3959 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003960 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003961};
3962
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003963}
Roman Divackyd966e722012-05-09 18:22:46 +00003964
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003965// Return true if the ABI requires Ty to be passed sign- or zero-
3966// extended to 64 bits.
3967bool
3968PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3969 // Treat an enum type as its underlying type.
3970 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3971 Ty = EnumTy->getDecl()->getIntegerType();
3972
3973 // Promotable integer types are required to be promoted by the ABI.
3974 if (Ty->isPromotableIntegerType())
3975 return true;
3976
3977 // In addition to the usual promotable integer types, we also need to
3978 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3979 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3980 switch (BT->getKind()) {
3981 case BuiltinType::Int:
3982 case BuiltinType::UInt:
3983 return true;
3984 default:
3985 break;
3986 }
3987
3988 return false;
3989}
3990
John McCall7f416cc2015-09-08 08:05:57 +00003991/// isAlignedParamType - Determine whether a type requires 16-byte or
3992/// higher alignment in the parameter area. Always returns at least 8.
3993CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003994 // Complex types are passed just like their elements.
3995 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3996 Ty = CTy->getElementType();
3997
3998 // Only vector types of size 16 bytes need alignment (larger types are
3999 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004000 if (IsQPXVectorTy(Ty)) {
4001 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004002 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004003
John McCall7f416cc2015-09-08 08:05:57 +00004004 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004005 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004006 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004007 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004008
4009 // For single-element float/vector structs, we consider the whole type
4010 // to have the same alignment requirements as its single element.
4011 const Type *AlignAsType = nullptr;
4012 const Type *EltType = isSingleElementStruct(Ty, getContext());
4013 if (EltType) {
4014 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004015 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004016 getContext().getTypeSize(EltType) == 128) ||
4017 (BT && BT->isFloatingPoint()))
4018 AlignAsType = EltType;
4019 }
4020
Ulrich Weigandb7122372014-07-21 00:48:09 +00004021 // Likewise for ELFv2 homogeneous aggregates.
4022 const Type *Base = nullptr;
4023 uint64_t Members = 0;
4024 if (!AlignAsType && Kind == ELFv2 &&
4025 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4026 AlignAsType = Base;
4027
Ulrich Weigand581badc2014-07-10 17:20:07 +00004028 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004029 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4030 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004031 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004032
John McCall7f416cc2015-09-08 08:05:57 +00004033 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004034 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004035 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004036 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004037
4038 // Otherwise, we only need alignment for any aggregate type that
4039 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004040 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4041 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004042 return CharUnits::fromQuantity(32);
4043 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004044 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004045
John McCall7f416cc2015-09-08 08:05:57 +00004046 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004047}
4048
Ulrich Weigandb7122372014-07-21 00:48:09 +00004049/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4050/// aggregate. Base is set to the base element type, and Members is set
4051/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004052bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4053 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004054 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4055 uint64_t NElements = AT->getSize().getZExtValue();
4056 if (NElements == 0)
4057 return false;
4058 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4059 return false;
4060 Members *= NElements;
4061 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4062 const RecordDecl *RD = RT->getDecl();
4063 if (RD->hasFlexibleArrayMember())
4064 return false;
4065
4066 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004067
4068 // If this is a C++ record, check the bases first.
4069 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4070 for (const auto &I : CXXRD->bases()) {
4071 // Ignore empty records.
4072 if (isEmptyRecord(getContext(), I.getType(), true))
4073 continue;
4074
4075 uint64_t FldMembers;
4076 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4077 return false;
4078
4079 Members += FldMembers;
4080 }
4081 }
4082
Ulrich Weigandb7122372014-07-21 00:48:09 +00004083 for (const auto *FD : RD->fields()) {
4084 // Ignore (non-zero arrays of) empty records.
4085 QualType FT = FD->getType();
4086 while (const ConstantArrayType *AT =
4087 getContext().getAsConstantArrayType(FT)) {
4088 if (AT->getSize().getZExtValue() == 0)
4089 return false;
4090 FT = AT->getElementType();
4091 }
4092 if (isEmptyRecord(getContext(), FT, true))
4093 continue;
4094
4095 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4096 if (getContext().getLangOpts().CPlusPlus &&
4097 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4098 continue;
4099
4100 uint64_t FldMembers;
4101 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4102 return false;
4103
4104 Members = (RD->isUnion() ?
4105 std::max(Members, FldMembers) : Members + FldMembers);
4106 }
4107
4108 if (!Base)
4109 return false;
4110
4111 // Ensure there is no padding.
4112 if (getContext().getTypeSize(Base) * Members !=
4113 getContext().getTypeSize(Ty))
4114 return false;
4115 } else {
4116 Members = 1;
4117 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4118 Members = 2;
4119 Ty = CT->getElementType();
4120 }
4121
Reid Klecknere9f6a712014-10-31 17:10:41 +00004122 // Most ABIs only support float, double, and some vector type widths.
4123 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004124 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004125
4126 // The base type must be the same for all members. Types that
4127 // agree in both total size and mode (float vs. vector) are
4128 // treated as being equivalent here.
4129 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004130 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004131 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004132 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4133 // so make sure to widen it explicitly.
4134 if (const VectorType *VT = Base->getAs<VectorType>()) {
4135 QualType EltTy = VT->getElementType();
4136 unsigned NumElements =
4137 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4138 Base = getContext()
4139 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4140 .getTypePtr();
4141 }
4142 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004143
4144 if (Base->isVectorType() != TyPtr->isVectorType() ||
4145 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4146 return false;
4147 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004148 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4149}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004150
Reid Klecknere9f6a712014-10-31 17:10:41 +00004151bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4152 // Homogeneous aggregates for ELFv2 must have base types of float,
4153 // double, long double, or 128-bit vectors.
4154 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4155 if (BT->getKind() == BuiltinType::Float ||
4156 BT->getKind() == BuiltinType::Double ||
4157 BT->getKind() == BuiltinType::LongDouble)
4158 return true;
4159 }
4160 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004161 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004162 return true;
4163 }
4164 return false;
4165}
4166
4167bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4168 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004169 // Vector types require one register, floating point types require one
4170 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004171 uint32_t NumRegs =
4172 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004173
4174 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004175 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004176}
4177
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004178ABIArgInfo
4179PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004180 Ty = useFirstFieldIfTransparentUnion(Ty);
4181
Bill Schmidt90b22c92012-11-27 02:46:43 +00004182 if (Ty->isAnyComplexType())
4183 return ABIArgInfo::getDirect();
4184
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004185 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4186 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004187 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004188 uint64_t Size = getContext().getTypeSize(Ty);
4189 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004190 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004191 else if (Size < 128) {
4192 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4193 return ABIArgInfo::getDirect(CoerceTy);
4194 }
4195 }
4196
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004197 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004198 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004199 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004200
John McCall7f416cc2015-09-08 08:05:57 +00004201 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4202 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004203
4204 // ELFv2 homogeneous aggregates are passed as array types.
4205 const Type *Base = nullptr;
4206 uint64_t Members = 0;
4207 if (Kind == ELFv2 &&
4208 isHomogeneousAggregate(Ty, Base, Members)) {
4209 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4210 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4211 return ABIArgInfo::getDirect(CoerceTy);
4212 }
4213
Ulrich Weigand601957f2014-07-21 00:56:36 +00004214 // If an aggregate may end up fully in registers, we do not
4215 // use the ByVal method, but pass the aggregate as array.
4216 // This is usually beneficial since we avoid forcing the
4217 // back-end to store the argument to memory.
4218 uint64_t Bits = getContext().getTypeSize(Ty);
4219 if (Bits > 0 && Bits <= 8 * GPRBits) {
4220 llvm::Type *CoerceTy;
4221
4222 // Types up to 8 bytes are passed as integer type (which will be
4223 // properly aligned in the argument save area doubleword).
4224 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004225 CoerceTy =
4226 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004227 // Larger types are passed as arrays, with the base type selected
4228 // according to the required alignment in the save area.
4229 else {
4230 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004231 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004232 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4233 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4234 }
4235
4236 return ABIArgInfo::getDirect(CoerceTy);
4237 }
4238
Ulrich Weigandb7122372014-07-21 00:48:09 +00004239 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004240 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4241 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004242 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004243 }
4244
4245 return (isPromotableTypeForABI(Ty) ?
4246 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4247}
4248
4249ABIArgInfo
4250PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4251 if (RetTy->isVoidType())
4252 return ABIArgInfo::getIgnore();
4253
Bill Schmidta3d121c2012-12-17 04:20:17 +00004254 if (RetTy->isAnyComplexType())
4255 return ABIArgInfo::getDirect();
4256
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004257 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4258 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004259 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004260 uint64_t Size = getContext().getTypeSize(RetTy);
4261 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004262 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004263 else if (Size < 128) {
4264 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4265 return ABIArgInfo::getDirect(CoerceTy);
4266 }
4267 }
4268
Ulrich Weigandb7122372014-07-21 00:48:09 +00004269 if (isAggregateTypeForABI(RetTy)) {
4270 // ELFv2 homogeneous aggregates are returned as array types.
4271 const Type *Base = nullptr;
4272 uint64_t Members = 0;
4273 if (Kind == ELFv2 &&
4274 isHomogeneousAggregate(RetTy, Base, Members)) {
4275 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4276 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4277 return ABIArgInfo::getDirect(CoerceTy);
4278 }
4279
4280 // ELFv2 small aggregates are returned in up to two registers.
4281 uint64_t Bits = getContext().getTypeSize(RetTy);
4282 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4283 if (Bits == 0)
4284 return ABIArgInfo::getIgnore();
4285
4286 llvm::Type *CoerceTy;
4287 if (Bits > GPRBits) {
4288 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004289 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004290 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004291 CoerceTy =
4292 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004293 return ABIArgInfo::getDirect(CoerceTy);
4294 }
4295
4296 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004297 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004298 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004299
4300 return (isPromotableTypeForABI(RetTy) ?
4301 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4302}
4303
Bill Schmidt25cb3492012-10-03 19:18:57 +00004304// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004305Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4306 QualType Ty) const {
4307 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4308 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004309
John McCall7f416cc2015-09-08 08:05:57 +00004310 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004311
Bill Schmidt924c4782013-01-14 17:45:36 +00004312 // If we have a complex type and the base type is smaller than 8 bytes,
4313 // the ABI calls for the real and imaginary parts to be right-adjusted
4314 // in separate doublewords. However, Clang expects us to produce a
4315 // pointer to a structure with the two parts packed tightly. So generate
4316 // loads of the real and imaginary parts relative to the va_list pointer,
4317 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004318 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4319 CharUnits EltSize = TypeInfo.first / 2;
4320 if (EltSize < SlotSize) {
4321 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4322 SlotSize * 2, SlotSize,
4323 SlotSize, /*AllowHigher*/ true);
4324
4325 Address RealAddr = Addr;
4326 Address ImagAddr = RealAddr;
4327 if (CGF.CGM.getDataLayout().isBigEndian()) {
4328 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4329 SlotSize - EltSize);
4330 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4331 2 * SlotSize - EltSize);
4332 } else {
4333 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4334 }
4335
4336 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4337 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4338 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4339 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4340 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4341
4342 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4343 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4344 /*init*/ true);
4345 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004346 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004347 }
4348
John McCall7f416cc2015-09-08 08:05:57 +00004349 // Otherwise, just use the general rule.
4350 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4351 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004352}
4353
4354static bool
4355PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4356 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004357 // This is calculated from the LLVM and GCC tables and verified
4358 // against gcc output. AFAIK all ABIs use the same encoding.
4359
4360 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4361
4362 llvm::IntegerType *i8 = CGF.Int8Ty;
4363 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4364 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4365 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4366
4367 // 0-31: r0-31, the 8-byte general-purpose registers
4368 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4369
4370 // 32-63: fp0-31, the 8-byte floating-point registers
4371 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4372
4373 // 64-76 are various 4-byte special-purpose registers:
4374 // 64: mq
4375 // 65: lr
4376 // 66: ctr
4377 // 67: ap
4378 // 68-75 cr0-7
4379 // 76: xer
4380 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4381
4382 // 77-108: v0-31, the 16-byte vector registers
4383 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4384
4385 // 109: vrsave
4386 // 110: vscr
4387 // 111: spe_acc
4388 // 112: spefscr
4389 // 113: sfp
4390 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4391
4392 return false;
4393}
John McCallea8d8bb2010-03-11 00:10:12 +00004394
Bill Schmidt25cb3492012-10-03 19:18:57 +00004395bool
4396PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4397 CodeGen::CodeGenFunction &CGF,
4398 llvm::Value *Address) const {
4399
4400 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4401}
4402
4403bool
4404PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4405 llvm::Value *Address) const {
4406
4407 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4408}
4409
Chris Lattner0cf24192010-06-28 20:05:43 +00004410//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004411// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004412//===----------------------------------------------------------------------===//
4413
4414namespace {
4415
John McCall12f23522016-04-04 18:33:08 +00004416class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004417public:
4418 enum ABIKind {
4419 AAPCS = 0,
4420 DarwinPCS
4421 };
4422
4423private:
4424 ABIKind Kind;
4425
4426public:
John McCall12f23522016-04-04 18:33:08 +00004427 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4428 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004429
4430private:
4431 ABIKind getABIKind() const { return Kind; }
4432 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4433
4434 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004435 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004436 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4437 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4438 uint64_t Members) const override;
4439
Tim Northovera2ee4332014-03-29 15:09:45 +00004440 bool isIllegalVectorType(QualType Ty) const;
4441
David Blaikie1cbb9712014-11-14 19:09:44 +00004442 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004443 if (!getCXXABI().classifyReturnType(FI))
4444 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004445
Tim Northoverb047bfa2014-11-27 21:02:49 +00004446 for (auto &it : FI.arguments())
4447 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004448 }
4449
John McCall7f416cc2015-09-08 08:05:57 +00004450 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4451 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004452
John McCall7f416cc2015-09-08 08:05:57 +00004453 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4454 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004455
John McCall7f416cc2015-09-08 08:05:57 +00004456 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4457 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004458 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4459 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4460 }
John McCall12f23522016-04-04 18:33:08 +00004461
4462 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4463 ArrayRef<llvm::Type*> scalars,
4464 bool asReturnValue) const override {
4465 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4466 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004467};
4468
Tim Northover573cbee2014-05-24 12:52:07 +00004469class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004470public:
Tim Northover573cbee2014-05-24 12:52:07 +00004471 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4472 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004473
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004474 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004475 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4476 }
4477
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004478 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4479 return 31;
4480 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004481
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004482 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004483};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004484}
Tim Northovera2ee4332014-03-29 15:09:45 +00004485
Tim Northoverb047bfa2014-11-27 21:02:49 +00004486ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004487 Ty = useFirstFieldIfTransparentUnion(Ty);
4488
Tim Northovera2ee4332014-03-29 15:09:45 +00004489 // Handle illegal vector types here.
4490 if (isIllegalVectorType(Ty)) {
4491 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004492 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004493 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004494 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4495 return ABIArgInfo::getDirect(ResType);
4496 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004497 if (Size <= 32) {
4498 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004499 return ABIArgInfo::getDirect(ResType);
4500 }
4501 if (Size == 64) {
4502 llvm::Type *ResType =
4503 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004504 return ABIArgInfo::getDirect(ResType);
4505 }
4506 if (Size == 128) {
4507 llvm::Type *ResType =
4508 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004509 return ABIArgInfo::getDirect(ResType);
4510 }
John McCall7f416cc2015-09-08 08:05:57 +00004511 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004512 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004513
4514 if (!isAggregateTypeForABI(Ty)) {
4515 // Treat an enum type as its underlying type.
4516 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4517 Ty = EnumTy->getDecl()->getIntegerType();
4518
Tim Northovera2ee4332014-03-29 15:09:45 +00004519 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4520 ? ABIArgInfo::getExtend()
4521 : ABIArgInfo::getDirect());
4522 }
4523
4524 // Structures with either a non-trivial destructor or a non-trivial
4525 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004526 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004527 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4528 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004529 }
4530
4531 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4532 // elsewhere for GNU compatibility.
4533 if (isEmptyRecord(getContext(), Ty, true)) {
4534 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4535 return ABIArgInfo::getIgnore();
4536
Tim Northovera2ee4332014-03-29 15:09:45 +00004537 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4538 }
4539
4540 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004541 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004542 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004543 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004544 return ABIArgInfo::getDirect(
4545 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004546 }
4547
4548 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4549 uint64_t Size = getContext().getTypeSize(Ty);
4550 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004551 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004552 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004553
Tim Northovera2ee4332014-03-29 15:09:45 +00004554 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4555 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004556 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004557 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4558 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4559 }
4560 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4561 }
4562
John McCall7f416cc2015-09-08 08:05:57 +00004563 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004564}
4565
Tim Northover573cbee2014-05-24 12:52:07 +00004566ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004567 if (RetTy->isVoidType())
4568 return ABIArgInfo::getIgnore();
4569
4570 // Large vector types should be returned via memory.
4571 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004572 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004573
4574 if (!isAggregateTypeForABI(RetTy)) {
4575 // Treat an enum type as its underlying type.
4576 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4577 RetTy = EnumTy->getDecl()->getIntegerType();
4578
Tim Northover4dab6982014-04-18 13:46:08 +00004579 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4580 ? ABIArgInfo::getExtend()
4581 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004582 }
4583
Tim Northovera2ee4332014-03-29 15:09:45 +00004584 if (isEmptyRecord(getContext(), RetTy, true))
4585 return ABIArgInfo::getIgnore();
4586
Craig Topper8a13c412014-05-21 05:09:00 +00004587 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004588 uint64_t Members = 0;
4589 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004590 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4591 return ABIArgInfo::getDirect();
4592
4593 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4594 uint64_t Size = getContext().getTypeSize(RetTy);
4595 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004596 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004597 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004598
4599 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4600 // For aggregates with 16-byte alignment, we use i128.
4601 if (Alignment < 128 && Size == 128) {
4602 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4603 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4604 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004605 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4606 }
4607
John McCall7f416cc2015-09-08 08:05:57 +00004608 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004609}
4610
Tim Northover573cbee2014-05-24 12:52:07 +00004611/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4612bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004613 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4614 // Check whether VT is legal.
4615 unsigned NumElements = VT->getNumElements();
4616 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004617 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004618 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004619 return true;
4620 return Size != 64 && (Size != 128 || NumElements == 1);
4621 }
4622 return false;
4623}
4624
Reid Klecknere9f6a712014-10-31 17:10:41 +00004625bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4626 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4627 // point type or a short-vector type. This is the same as the 32-bit ABI,
4628 // but with the difference that any floating-point type is allowed,
4629 // including __fp16.
4630 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4631 if (BT->isFloatingPoint())
4632 return true;
4633 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4634 unsigned VecSize = getContext().getTypeSize(VT);
4635 if (VecSize == 64 || VecSize == 128)
4636 return true;
4637 }
4638 return false;
4639}
4640
4641bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4642 uint64_t Members) const {
4643 return Members <= 4;
4644}
4645
John McCall7f416cc2015-09-08 08:05:57 +00004646Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004647 QualType Ty,
4648 CodeGenFunction &CGF) const {
4649 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004650 bool IsIndirect = AI.isIndirect();
4651
Tim Northoverb047bfa2014-11-27 21:02:49 +00004652 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4653 if (IsIndirect)
4654 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4655 else if (AI.getCoerceToType())
4656 BaseTy = AI.getCoerceToType();
4657
4658 unsigned NumRegs = 1;
4659 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4660 BaseTy = ArrTy->getElementType();
4661 NumRegs = ArrTy->getNumElements();
4662 }
4663 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4664
Tim Northovera2ee4332014-03-29 15:09:45 +00004665 // The AArch64 va_list type and handling is specified in the Procedure Call
4666 // Standard, section B.4:
4667 //
4668 // struct {
4669 // void *__stack;
4670 // void *__gr_top;
4671 // void *__vr_top;
4672 // int __gr_offs;
4673 // int __vr_offs;
4674 // };
4675
4676 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4677 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4678 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4679 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004680
John McCall7f416cc2015-09-08 08:05:57 +00004681 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4682 CharUnits TyAlign = TyInfo.second;
4683
4684 Address reg_offs_p = Address::invalid();
4685 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004686 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004687 CharUnits reg_top_offset;
4688 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004689 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004690 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004691 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004692 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4693 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004694 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4695 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004696 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004697 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004698 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004699 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004700 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004701 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4702 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004703 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4704 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004705 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004706 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004707 }
4708
4709 //=======================================
4710 // Find out where argument was passed
4711 //=======================================
4712
4713 // If reg_offs >= 0 we're already using the stack for this type of
4714 // argument. We don't want to keep updating reg_offs (in case it overflows,
4715 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4716 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004717 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004718 UsingStack = CGF.Builder.CreateICmpSGE(
4719 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4720
4721 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4722
4723 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004724 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004725 CGF.EmitBlock(MaybeRegBlock);
4726
4727 // Integer arguments may need to correct register alignment (for example a
4728 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4729 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004730 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4731 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004732
4733 reg_offs = CGF.Builder.CreateAdd(
4734 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4735 "align_regoffs");
4736 reg_offs = CGF.Builder.CreateAnd(
4737 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4738 "aligned_regoffs");
4739 }
4740
4741 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004742 // The fact that this is done unconditionally reflects the fact that
4743 // allocating an argument to the stack also uses up all the remaining
4744 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004745 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004746 NewOffset = CGF.Builder.CreateAdd(
4747 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4748 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4749
4750 // Now we're in a position to decide whether this argument really was in
4751 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004752 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004753 InRegs = CGF.Builder.CreateICmpSLE(
4754 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4755
4756 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4757
4758 //=======================================
4759 // Argument was in registers
4760 //=======================================
4761
4762 // Now we emit the code for if the argument was originally passed in
4763 // registers. First start the appropriate block:
4764 CGF.EmitBlock(InRegBlock);
4765
John McCall7f416cc2015-09-08 08:05:57 +00004766 llvm::Value *reg_top = nullptr;
4767 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4768 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004769 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004770 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4771 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4772 Address RegAddr = Address::invalid();
4773 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004774
4775 if (IsIndirect) {
4776 // If it's been passed indirectly (actually a struct), whatever we find from
4777 // stored registers or on the stack will actually be a struct **.
4778 MemTy = llvm::PointerType::getUnqual(MemTy);
4779 }
4780
Craig Topper8a13c412014-05-21 05:09:00 +00004781 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004782 uint64_t NumMembers = 0;
4783 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004784 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004785 // Homogeneous aggregates passed in registers will have their elements split
4786 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4787 // qN+1, ...). We reload and store into a temporary local variable
4788 // contiguously.
4789 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004790 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004791 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4792 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004793 Address Tmp = CGF.CreateTempAlloca(HFATy,
4794 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004795
John McCall7f416cc2015-09-08 08:05:57 +00004796 // On big-endian platforms, the value will be right-aligned in its slot.
4797 int Offset = 0;
4798 if (CGF.CGM.getDataLayout().isBigEndian() &&
4799 BaseTyInfo.first.getQuantity() < 16)
4800 Offset = 16 - BaseTyInfo.first.getQuantity();
4801
Tim Northovera2ee4332014-03-29 15:09:45 +00004802 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004803 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4804 Address LoadAddr =
4805 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4806 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4807
4808 Address StoreAddr =
4809 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004810
4811 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4812 CGF.Builder.CreateStore(Elem, StoreAddr);
4813 }
4814
John McCall7f416cc2015-09-08 08:05:57 +00004815 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004816 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004817 // Otherwise the object is contiguous in memory.
4818
4819 // It might be right-aligned in its slot.
4820 CharUnits SlotSize = BaseAddr.getAlignment();
4821 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004822 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004823 TyInfo.first < SlotSize) {
4824 CharUnits Offset = SlotSize - TyInfo.first;
4825 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004826 }
4827
John McCall7f416cc2015-09-08 08:05:57 +00004828 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004829 }
4830
4831 CGF.EmitBranch(ContBlock);
4832
4833 //=======================================
4834 // Argument was on the stack
4835 //=======================================
4836 CGF.EmitBlock(OnStackBlock);
4837
John McCall7f416cc2015-09-08 08:05:57 +00004838 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4839 CharUnits::Zero(), "stack_p");
4840 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004841
John McCall7f416cc2015-09-08 08:05:57 +00004842 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004843 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004844 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4845 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004846
John McCall7f416cc2015-09-08 08:05:57 +00004847 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004848
John McCall7f416cc2015-09-08 08:05:57 +00004849 OnStackPtr = CGF.Builder.CreateAdd(
4850 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004851 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004852 OnStackPtr = CGF.Builder.CreateAnd(
4853 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004854 "align_stack");
4855
John McCall7f416cc2015-09-08 08:05:57 +00004856 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004857 }
John McCall7f416cc2015-09-08 08:05:57 +00004858 Address OnStackAddr(OnStackPtr,
4859 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004860
John McCall7f416cc2015-09-08 08:05:57 +00004861 // All stack slots are multiples of 8 bytes.
4862 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4863 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004864 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004865 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004866 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004867 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004868
John McCall7f416cc2015-09-08 08:05:57 +00004869 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004870 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004871 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004872
4873 // Write the new value of __stack for the next call to va_arg
4874 CGF.Builder.CreateStore(NewStack, stack_p);
4875
4876 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004877 TyInfo.first < StackSlotSize) {
4878 CharUnits Offset = StackSlotSize - TyInfo.first;
4879 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004880 }
4881
John McCall7f416cc2015-09-08 08:05:57 +00004882 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004883
4884 CGF.EmitBranch(ContBlock);
4885
4886 //=======================================
4887 // Tidy up
4888 //=======================================
4889 CGF.EmitBlock(ContBlock);
4890
John McCall7f416cc2015-09-08 08:05:57 +00004891 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4892 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004893
4894 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004895 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4896 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004897
4898 return ResAddr;
4899}
4900
John McCall7f416cc2015-09-08 08:05:57 +00004901Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4902 CodeGenFunction &CGF) const {
4903 // The backend's lowering doesn't support va_arg for aggregates or
4904 // illegal vector types. Lower VAArg here for these cases and use
4905 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004906 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00004907 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004908
John McCall7f416cc2015-09-08 08:05:57 +00004909 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004910
John McCall7f416cc2015-09-08 08:05:57 +00004911 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004912 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004913 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4914 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4915 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004916 }
4917
John McCall7f416cc2015-09-08 08:05:57 +00004918 // The size of the actual thing passed, which might end up just
4919 // being a pointer for indirect types.
4920 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4921
4922 // Arguments bigger than 16 bytes which aren't homogeneous
4923 // aggregates should be passed indirectly.
4924 bool IsIndirect = false;
4925 if (TyInfo.first.getQuantity() > 16) {
4926 const Type *Base = nullptr;
4927 uint64_t Members = 0;
4928 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004929 }
4930
John McCall7f416cc2015-09-08 08:05:57 +00004931 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4932 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004933}
4934
4935//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004936// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004937//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004938
4939namespace {
4940
John McCall12f23522016-04-04 18:33:08 +00004941class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004942public:
4943 enum ABIKind {
4944 APCS = 0,
4945 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004946 AAPCS_VFP = 2,
4947 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004948 };
4949
4950private:
4951 ABIKind Kind;
4952
4953public:
John McCall12f23522016-04-04 18:33:08 +00004954 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
4955 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004956 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004957 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004958
John McCall3480ef22011-08-30 01:42:09 +00004959 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004960 switch (getTarget().getTriple().getEnvironment()) {
4961 case llvm::Triple::Android:
4962 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004963 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004964 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004965 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004966 return true;
4967 default:
4968 return false;
4969 }
John McCall3480ef22011-08-30 01:42:09 +00004970 }
4971
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004972 bool isEABIHF() const {
4973 switch (getTarget().getTriple().getEnvironment()) {
4974 case llvm::Triple::EABIHF:
4975 case llvm::Triple::GNUEABIHF:
4976 return true;
4977 default:
4978 return false;
4979 }
4980 }
4981
Daniel Dunbar020daa92009-09-12 01:00:39 +00004982 ABIKind getABIKind() const { return Kind; }
4983
Tim Northovera484bc02013-10-01 14:34:25 +00004984private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004985 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004986 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004987 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004988
Reid Klecknere9f6a712014-10-31 17:10:41 +00004989 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4990 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4991 uint64_t Members) const override;
4992
Craig Topper4f12f102014-03-12 06:41:41 +00004993 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004994
John McCall7f416cc2015-09-08 08:05:57 +00004995 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4996 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004997
4998 llvm::CallingConv::ID getLLVMDefaultCC() const;
4999 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005000 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005001
5002 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5003 ArrayRef<llvm::Type*> scalars,
5004 bool asReturnValue) const override {
5005 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5006 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005007};
5008
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005009class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5010public:
Chris Lattner2b037972010-07-29 02:01:43 +00005011 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5012 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005013
John McCall3480ef22011-08-30 01:42:09 +00005014 const ARMABIInfo &getABIInfo() const {
5015 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5016 }
5017
Craig Topper4f12f102014-03-12 06:41:41 +00005018 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005019 return 13;
5020 }
Roman Divackyc1617352011-05-18 19:36:54 +00005021
Craig Topper4f12f102014-03-12 06:41:41 +00005022 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005023 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5024 }
5025
Roman Divackyc1617352011-05-18 19:36:54 +00005026 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005027 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005028 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005029
5030 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005031 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005032 return false;
5033 }
John McCall3480ef22011-08-30 01:42:09 +00005034
Craig Topper4f12f102014-03-12 06:41:41 +00005035 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005036 if (getABIInfo().isEABI()) return 88;
5037 return TargetCodeGenInfo::getSizeOfUnwindException();
5038 }
Tim Northovera484bc02013-10-01 14:34:25 +00005039
Eric Christopher162c91c2015-06-05 22:03:00 +00005040 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005041 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005042 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005043 if (!FD)
5044 return;
5045
5046 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5047 if (!Attr)
5048 return;
5049
5050 const char *Kind;
5051 switch (Attr->getInterrupt()) {
5052 case ARMInterruptAttr::Generic: Kind = ""; break;
5053 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5054 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5055 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5056 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5057 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5058 }
5059
5060 llvm::Function *Fn = cast<llvm::Function>(GV);
5061
5062 Fn->addFnAttr("interrupt", Kind);
5063
Tim Northover5627d392015-10-30 16:30:45 +00005064 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5065 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005066 return;
5067
5068 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5069 // however this is not necessarily true on taking any interrupt. Instruct
5070 // the backend to perform a realignment as part of the function prologue.
5071 llvm::AttrBuilder B;
5072 B.addStackAlignmentAttr(8);
5073 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5074 llvm::AttributeSet::get(CGM.getLLVMContext(),
5075 llvm::AttributeSet::FunctionIndex,
5076 B));
5077 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005078};
5079
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005080class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005081public:
5082 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5083 : ARMTargetCodeGenInfo(CGT, K) {}
5084
Eric Christopher162c91c2015-06-05 22:03:00 +00005085 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005086 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005087
5088 void getDependentLibraryOption(llvm::StringRef Lib,
5089 llvm::SmallString<24> &Opt) const override {
5090 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5091 }
5092
5093 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5094 llvm::SmallString<32> &Opt) const override {
5095 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5096 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005097};
5098
Eric Christopher162c91c2015-06-05 22:03:00 +00005099void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005100 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005101 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005102 addStackProbeSizeTargetAttribute(D, GV, CGM);
5103}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005104}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005105
Chris Lattner22326a12010-07-29 02:31:05 +00005106void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005107 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005108 FI.getReturnInfo() =
5109 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005110
Tim Northoverbc784d12015-02-24 17:22:40 +00005111 for (auto &I : FI.arguments())
5112 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005113
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005114 // Always honor user-specified calling convention.
5115 if (FI.getCallingConvention() != llvm::CallingConv::C)
5116 return;
5117
John McCall882987f2013-02-28 19:01:20 +00005118 llvm::CallingConv::ID cc = getRuntimeCC();
5119 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005120 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005121}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005122
John McCall882987f2013-02-28 19:01:20 +00005123/// Return the default calling convention that LLVM will use.
5124llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5125 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005126 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005127 return llvm::CallingConv::ARM_AAPCS_VFP;
5128 else if (isEABI())
5129 return llvm::CallingConv::ARM_AAPCS;
5130 else
5131 return llvm::CallingConv::ARM_APCS;
5132}
5133
5134/// Return the calling convention that our ABI would like us to use
5135/// as the C calling convention.
5136llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005137 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005138 case APCS: return llvm::CallingConv::ARM_APCS;
5139 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5140 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005141 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005142 }
John McCall882987f2013-02-28 19:01:20 +00005143 llvm_unreachable("bad ABI kind");
5144}
5145
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005146void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005147 assert(getRuntimeCC() == llvm::CallingConv::C);
5148
5149 // Don't muddy up the IR with a ton of explicit annotations if
5150 // they'd just match what LLVM will infer from the triple.
5151 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5152 if (abiCC != getLLVMDefaultCC())
5153 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005154
Tim Northover5627d392015-10-30 16:30:45 +00005155 // AAPCS apparently requires runtime support functions to be soft-float, but
5156 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5157 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5158 switch (getABIKind()) {
5159 case APCS:
5160 case AAPCS16_VFP:
5161 if (abiCC != getLLVMDefaultCC())
5162 BuiltinCC = abiCC;
5163 break;
5164 case AAPCS:
5165 case AAPCS_VFP:
5166 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5167 break;
5168 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005169}
5170
Tim Northoverbc784d12015-02-24 17:22:40 +00005171ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5172 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005173 // 6.1.2.1 The following argument types are VFP CPRCs:
5174 // A single-precision floating-point type (including promoted
5175 // half-precision types); A double-precision floating-point type;
5176 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5177 // with a Base Type of a single- or double-precision floating-point type,
5178 // 64-bit containerized vectors or 128-bit containerized vectors with one
5179 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005180 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005181
Reid Klecknerb1be6832014-11-15 01:41:41 +00005182 Ty = useFirstFieldIfTransparentUnion(Ty);
5183
Manman Renfef9e312012-10-16 19:18:39 +00005184 // Handle illegal vector types here.
5185 if (isIllegalVectorType(Ty)) {
5186 uint64_t Size = getContext().getTypeSize(Ty);
5187 if (Size <= 32) {
5188 llvm::Type *ResType =
5189 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005190 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005191 }
5192 if (Size == 64) {
5193 llvm::Type *ResType = llvm::VectorType::get(
5194 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005195 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005196 }
5197 if (Size == 128) {
5198 llvm::Type *ResType = llvm::VectorType::get(
5199 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005200 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005201 }
John McCall7f416cc2015-09-08 08:05:57 +00005202 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005203 }
5204
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005205 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5206 // unspecified. This is not done for OpenCL as it handles the half type
5207 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005208 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005209 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5210 llvm::Type::getFloatTy(getVMContext()) :
5211 llvm::Type::getInt32Ty(getVMContext());
5212 return ABIArgInfo::getDirect(ResType);
5213 }
5214
John McCalla1dee5302010-08-22 10:59:02 +00005215 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005216 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005217 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005218 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005219 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005220
Tim Northover5a1558e2014-11-07 22:30:50 +00005221 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5222 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005223 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005224
Oliver Stannard405bded2014-02-11 09:25:50 +00005225 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005226 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005227 }
Tim Northover1060eae2013-06-21 22:49:34 +00005228
Daniel Dunbar09d33622009-09-14 21:54:03 +00005229 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005230 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005231 return ABIArgInfo::getIgnore();
5232
Tim Northover5a1558e2014-11-07 22:30:50 +00005233 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005234 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5235 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005236 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005237 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005238 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005239 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005240 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005241 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005242 }
Tim Northover5627d392015-10-30 16:30:45 +00005243 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5244 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5245 // this convention even for a variadic function: the backend will use GPRs
5246 // if needed.
5247 const Type *Base = nullptr;
5248 uint64_t Members = 0;
5249 if (isHomogeneousAggregate(Ty, Base, Members)) {
5250 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5251 llvm::Type *Ty =
5252 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5253 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5254 }
5255 }
5256
5257 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5258 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5259 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5260 // bigger than 128-bits, they get placed in space allocated by the caller,
5261 // and a pointer is passed.
5262 return ABIArgInfo::getIndirect(
5263 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005264 }
5265
Manman Ren6c30e132012-08-13 21:23:55 +00005266 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005267 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5268 // most 8-byte. We realign the indirect argument if type alignment is bigger
5269 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005270 uint64_t ABIAlign = 4;
5271 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5272 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005273 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005274 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005275
Manman Ren8cd99812012-11-06 04:58:01 +00005276 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005277 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005278 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5279 /*ByVal=*/true,
5280 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005281 }
5282
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005283 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005284 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005285 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005286 // FIXME: Try to match the types of the arguments more accurately where
5287 // we can.
5288 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005289 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5290 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005291 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005292 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5293 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005294 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005295
Tim Northover5a1558e2014-11-07 22:30:50 +00005296 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005297}
5298
Chris Lattner458b2aa2010-07-29 02:16:43 +00005299static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005300 llvm::LLVMContext &VMContext) {
5301 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5302 // is called integer-like if its size is less than or equal to one word, and
5303 // the offset of each of its addressable sub-fields is zero.
5304
5305 uint64_t Size = Context.getTypeSize(Ty);
5306
5307 // Check that the type fits in a word.
5308 if (Size > 32)
5309 return false;
5310
5311 // FIXME: Handle vector types!
5312 if (Ty->isVectorType())
5313 return false;
5314
Daniel Dunbard53bac72009-09-14 02:20:34 +00005315 // Float types are never treated as "integer like".
5316 if (Ty->isRealFloatingType())
5317 return false;
5318
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005319 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005320 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005321 return true;
5322
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005323 // Small complex integer types are "integer like".
5324 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5325 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005326
5327 // Single element and zero sized arrays should be allowed, by the definition
5328 // above, but they are not.
5329
5330 // Otherwise, it must be a record type.
5331 const RecordType *RT = Ty->getAs<RecordType>();
5332 if (!RT) return false;
5333
5334 // Ignore records with flexible arrays.
5335 const RecordDecl *RD = RT->getDecl();
5336 if (RD->hasFlexibleArrayMember())
5337 return false;
5338
5339 // Check that all sub-fields are at offset 0, and are themselves "integer
5340 // like".
5341 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5342
5343 bool HadField = false;
5344 unsigned idx = 0;
5345 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5346 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005347 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005348
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005349 // Bit-fields are not addressable, we only need to verify they are "integer
5350 // like". We still have to disallow a subsequent non-bitfield, for example:
5351 // struct { int : 0; int x }
5352 // is non-integer like according to gcc.
5353 if (FD->isBitField()) {
5354 if (!RD->isUnion())
5355 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005356
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005357 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5358 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005359
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005360 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005361 }
5362
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005363 // Check if this field is at offset 0.
5364 if (Layout.getFieldOffset(idx) != 0)
5365 return false;
5366
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005367 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5368 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005369
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005370 // Only allow at most one field in a structure. This doesn't match the
5371 // wording above, but follows gcc in situations with a field following an
5372 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005373 if (!RD->isUnion()) {
5374 if (HadField)
5375 return false;
5376
5377 HadField = true;
5378 }
5379 }
5380
5381 return true;
5382}
5383
Oliver Stannard405bded2014-02-11 09:25:50 +00005384ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5385 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005386 bool IsEffectivelyAAPCS_VFP =
5387 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005388
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005389 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005390 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005391
Daniel Dunbar19964db2010-09-23 01:54:32 +00005392 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005393 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005394 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005395 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005396
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005397 // __fp16 gets returned as if it were an int or float, but with the top 16
5398 // bits unspecified. This is not done for OpenCL as it handles the half type
5399 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005400 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005401 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5402 llvm::Type::getFloatTy(getVMContext()) :
5403 llvm::Type::getInt32Ty(getVMContext());
5404 return ABIArgInfo::getDirect(ResType);
5405 }
5406
John McCalla1dee5302010-08-22 10:59:02 +00005407 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005408 // Treat an enum type as its underlying type.
5409 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5410 RetTy = EnumTy->getDecl()->getIntegerType();
5411
Tim Northover5a1558e2014-11-07 22:30:50 +00005412 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5413 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005414 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005415
5416 // Are we following APCS?
5417 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005418 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005419 return ABIArgInfo::getIgnore();
5420
Daniel Dunbareedf1512010-02-01 23:31:19 +00005421 // Complex types are all returned as packed integers.
5422 //
5423 // FIXME: Consider using 2 x vector types if the back end handles them
5424 // correctly.
5425 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005426 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5427 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005428
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005429 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005430 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005431 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005432 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005433 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005434 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005435 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005436 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5437 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005438 }
5439
5440 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005441 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005442 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005443
5444 // Otherwise this is an AAPCS variant.
5445
Chris Lattner458b2aa2010-07-29 02:16:43 +00005446 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005447 return ABIArgInfo::getIgnore();
5448
Bob Wilson1d9269a2011-11-02 04:51:36 +00005449 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005450 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005451 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005452 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005453 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005454 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005455 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005456 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005457 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005458 }
5459
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005460 // Aggregates <= 4 bytes are returned in r0; other aggregates
5461 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005462 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005463 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005464 if (getDataLayout().isBigEndian())
5465 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005466 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005467
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005468 // Return in the smallest viable integer type.
5469 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005470 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005471 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005472 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5473 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005474 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5475 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5476 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005477 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005478 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005479 }
5480
John McCall7f416cc2015-09-08 08:05:57 +00005481 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005482}
5483
Manman Renfef9e312012-10-16 19:18:39 +00005484/// isIllegalVector - check whether Ty is an illegal vector type.
5485bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005486 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5487 if (isAndroid()) {
5488 // Android shipped using Clang 3.1, which supported a slightly different
5489 // vector ABI. The primary differences were that 3-element vector types
5490 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5491 // accepts that legacy behavior for Android only.
5492 // Check whether VT is legal.
5493 unsigned NumElements = VT->getNumElements();
5494 // NumElements should be power of 2 or equal to 3.
5495 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5496 return true;
5497 } else {
5498 // Check whether VT is legal.
5499 unsigned NumElements = VT->getNumElements();
5500 uint64_t Size = getContext().getTypeSize(VT);
5501 // NumElements should be power of 2.
5502 if (!llvm::isPowerOf2_32(NumElements))
5503 return true;
5504 // Size should be greater than 32 bits.
5505 return Size <= 32;
5506 }
Manman Renfef9e312012-10-16 19:18:39 +00005507 }
5508 return false;
5509}
5510
Reid Klecknere9f6a712014-10-31 17:10:41 +00005511bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5512 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5513 // double, or 64-bit or 128-bit vectors.
5514 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5515 if (BT->getKind() == BuiltinType::Float ||
5516 BT->getKind() == BuiltinType::Double ||
5517 BT->getKind() == BuiltinType::LongDouble)
5518 return true;
5519 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5520 unsigned VecSize = getContext().getTypeSize(VT);
5521 if (VecSize == 64 || VecSize == 128)
5522 return true;
5523 }
5524 return false;
5525}
5526
5527bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5528 uint64_t Members) const {
5529 return Members <= 4;
5530}
5531
John McCall7f416cc2015-09-08 08:05:57 +00005532Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5533 QualType Ty) const {
5534 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005535
John McCall7f416cc2015-09-08 08:05:57 +00005536 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005537 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005538 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5539 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5540 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005541 }
5542
John McCall7f416cc2015-09-08 08:05:57 +00005543 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5544 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005545
John McCall7f416cc2015-09-08 08:05:57 +00005546 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5547 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005548 const Type *Base = nullptr;
5549 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005550 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5551 IsIndirect = true;
5552
Tim Northover5627d392015-10-30 16:30:45 +00005553 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5554 // allocated by the caller.
5555 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5556 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5557 !isHomogeneousAggregate(Ty, Base, Members)) {
5558 IsIndirect = true;
5559
John McCall7f416cc2015-09-08 08:05:57 +00005560 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005561 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5562 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005563 // Our callers should be prepared to handle an under-aligned address.
5564 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5565 getABIKind() == ARMABIInfo::AAPCS) {
5566 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5567 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005568 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5569 // ARMv7k allows type alignment up to 16 bytes.
5570 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5571 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005572 } else {
5573 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005574 }
John McCall7f416cc2015-09-08 08:05:57 +00005575 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005576
John McCall7f416cc2015-09-08 08:05:57 +00005577 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5578 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005579}
5580
Chris Lattner0cf24192010-06-28 20:05:43 +00005581//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005582// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005583//===----------------------------------------------------------------------===//
5584
5585namespace {
5586
Justin Holewinski83e96682012-05-24 17:43:12 +00005587class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005588public:
Justin Holewinski36837432013-03-30 14:38:24 +00005589 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005590
5591 ABIArgInfo classifyReturnType(QualType RetTy) const;
5592 ABIArgInfo classifyArgumentType(QualType Ty) const;
5593
Craig Topper4f12f102014-03-12 06:41:41 +00005594 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005595 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5596 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005597};
5598
Justin Holewinski83e96682012-05-24 17:43:12 +00005599class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005600public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005601 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5602 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005603
Eric Christopher162c91c2015-06-05 22:03:00 +00005604 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005605 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005606private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005607 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5608 // resulting MDNode to the nvvm.annotations MDNode.
5609 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005610};
5611
Justin Holewinski83e96682012-05-24 17:43:12 +00005612ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005613 if (RetTy->isVoidType())
5614 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005615
5616 // note: this is different from default ABI
5617 if (!RetTy->isScalarType())
5618 return ABIArgInfo::getDirect();
5619
5620 // Treat an enum type as its underlying type.
5621 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5622 RetTy = EnumTy->getDecl()->getIntegerType();
5623
5624 return (RetTy->isPromotableIntegerType() ?
5625 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005626}
5627
Justin Holewinski83e96682012-05-24 17:43:12 +00005628ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005629 // Treat an enum type as its underlying type.
5630 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5631 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005632
Eli Bendersky95338a02014-10-29 13:43:21 +00005633 // Return aggregates type as indirect by value
5634 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005635 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005636
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005637 return (Ty->isPromotableIntegerType() ?
5638 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005639}
5640
Justin Holewinski83e96682012-05-24 17:43:12 +00005641void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005642 if (!getCXXABI().classifyReturnType(FI))
5643 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005644 for (auto &I : FI.arguments())
5645 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005646
5647 // Always honor user-specified calling convention.
5648 if (FI.getCallingConvention() != llvm::CallingConv::C)
5649 return;
5650
John McCall882987f2013-02-28 19:01:20 +00005651 FI.setEffectiveCallingConvention(getRuntimeCC());
5652}
5653
John McCall7f416cc2015-09-08 08:05:57 +00005654Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5655 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005656 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005657}
5658
Justin Holewinski83e96682012-05-24 17:43:12 +00005659void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005660setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005661 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005662 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005663 if (!FD) return;
5664
5665 llvm::Function *F = cast<llvm::Function>(GV);
5666
5667 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005668 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005669 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005670 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005671 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005672 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005673 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5674 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005675 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005676 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005677 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005678 }
Justin Holewinski38031972011-10-05 17:58:44 +00005679
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005680 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005681 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005682 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005683 // __global__ functions cannot be called from the device, we do not
5684 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005685 if (FD->hasAttr<CUDAGlobalAttr>()) {
5686 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5687 addNVVMMetadata(F, "kernel", 1);
5688 }
Artem Belevich7093e402015-04-21 22:55:54 +00005689 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005690 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005691 llvm::APSInt MaxThreads(32);
5692 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5693 if (MaxThreads > 0)
5694 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5695
5696 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5697 // not specified in __launch_bounds__ or if the user specified a 0 value,
5698 // we don't have to add a PTX directive.
5699 if (Attr->getMinBlocks()) {
5700 llvm::APSInt MinBlocks(32);
5701 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5702 if (MinBlocks > 0)
5703 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5704 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005705 }
5706 }
Justin Holewinski38031972011-10-05 17:58:44 +00005707 }
5708}
5709
Eli Benderskye06a2c42014-04-15 16:57:05 +00005710void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5711 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005712 llvm::Module *M = F->getParent();
5713 llvm::LLVMContext &Ctx = M->getContext();
5714
5715 // Get "nvvm.annotations" metadata node
5716 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5717
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005718 llvm::Metadata *MDVals[] = {
5719 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5720 llvm::ConstantAsMetadata::get(
5721 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005722 // Append metadata to nvvm.annotations
5723 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5724}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005725}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005726
5727//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005728// SystemZ ABI Implementation
5729//===----------------------------------------------------------------------===//
5730
5731namespace {
5732
Bryan Chane3f1ed52016-04-28 13:56:43 +00005733class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005734 bool HasVector;
5735
Ulrich Weigand47445072013-05-06 16:26:41 +00005736public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005737 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00005738 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005739
5740 bool isPromotableIntegerType(QualType Ty) const;
5741 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005742 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005743 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005744 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005745
5746 ABIArgInfo classifyReturnType(QualType RetTy) const;
5747 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5748
Craig Topper4f12f102014-03-12 06:41:41 +00005749 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005750 if (!getCXXABI().classifyReturnType(FI))
5751 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005752 for (auto &I : FI.arguments())
5753 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005754 }
5755
John McCall7f416cc2015-09-08 08:05:57 +00005756 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5757 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00005758
5759 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5760 ArrayRef<llvm::Type*> scalars,
5761 bool asReturnValue) const override {
5762 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5763 }
Ulrich Weigand47445072013-05-06 16:26:41 +00005764};
5765
5766class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5767public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005768 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5769 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005770};
5771
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005772}
Ulrich Weigand47445072013-05-06 16:26:41 +00005773
5774bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5775 // Treat an enum type as its underlying type.
5776 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5777 Ty = EnumTy->getDecl()->getIntegerType();
5778
5779 // Promotable integer types are required to be promoted by the ABI.
5780 if (Ty->isPromotableIntegerType())
5781 return true;
5782
5783 // 32-bit values must also be promoted.
5784 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5785 switch (BT->getKind()) {
5786 case BuiltinType::Int:
5787 case BuiltinType::UInt:
5788 return true;
5789 default:
5790 return false;
5791 }
5792 return false;
5793}
5794
5795bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005796 return (Ty->isAnyComplexType() ||
5797 Ty->isVectorType() ||
5798 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005799}
5800
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005801bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5802 return (HasVector &&
5803 Ty->isVectorType() &&
5804 getContext().getTypeSize(Ty) <= 128);
5805}
5806
Ulrich Weigand47445072013-05-06 16:26:41 +00005807bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5808 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5809 switch (BT->getKind()) {
5810 case BuiltinType::Float:
5811 case BuiltinType::Double:
5812 return true;
5813 default:
5814 return false;
5815 }
5816
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005817 return false;
5818}
5819
5820QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005821 if (const RecordType *RT = Ty->getAsStructureType()) {
5822 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005823 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005824
5825 // If this is a C++ record, check the bases first.
5826 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005827 for (const auto &I : CXXRD->bases()) {
5828 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005829
5830 // Empty bases don't affect things either way.
5831 if (isEmptyRecord(getContext(), Base, true))
5832 continue;
5833
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005834 if (!Found.isNull())
5835 return Ty;
5836 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005837 }
5838
5839 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005840 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005841 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005842 // Unlike isSingleElementStruct(), empty structure and array fields
5843 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005844 if (getContext().getLangOpts().CPlusPlus &&
5845 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5846 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005847
5848 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005849 // Nested structures still do though.
5850 if (!Found.isNull())
5851 return Ty;
5852 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005853 }
5854
5855 // Unlike isSingleElementStruct(), trailing padding is allowed.
5856 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005857 if (!Found.isNull())
5858 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005859 }
5860
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005861 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005862}
5863
John McCall7f416cc2015-09-08 08:05:57 +00005864Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5865 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005866 // Assume that va_list type is correct; should be pointer to LLVM type:
5867 // struct {
5868 // i64 __gpr;
5869 // i64 __fpr;
5870 // i8 *__overflow_arg_area;
5871 // i8 *__reg_save_area;
5872 // };
5873
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005874 // Every non-vector argument occupies 8 bytes and is passed by preference
5875 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5876 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005877 Ty = getContext().getCanonicalType(Ty);
5878 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005879 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005880 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005881 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005882 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005883 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005884 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005885 CharUnits UnpaddedSize;
5886 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005887 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005888 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5889 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005890 } else {
5891 if (AI.getCoerceToType())
5892 ArgTy = AI.getCoerceToType();
5893 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005894 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005895 UnpaddedSize = TyInfo.first;
5896 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005897 }
John McCall7f416cc2015-09-08 08:05:57 +00005898 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5899 if (IsVector && UnpaddedSize > PaddedSize)
5900 PaddedSize = CharUnits::fromQuantity(16);
5901 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005902
John McCall7f416cc2015-09-08 08:05:57 +00005903 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005904
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005905 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005906 llvm::Value *PaddedSizeV =
5907 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005908
5909 if (IsVector) {
5910 // Work out the address of a vector argument on the stack.
5911 // Vector arguments are always passed in the high bits of a
5912 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005913 Address OverflowArgAreaPtr =
5914 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005915 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005916 Address OverflowArgArea =
5917 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5918 TyInfo.second);
5919 Address MemAddr =
5920 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005921
5922 // Update overflow_arg_area_ptr pointer
5923 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005924 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5925 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005926 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5927
5928 return MemAddr;
5929 }
5930
John McCall7f416cc2015-09-08 08:05:57 +00005931 assert(PaddedSize.getQuantity() == 8);
5932
5933 unsigned MaxRegs, RegCountField, RegSaveIndex;
5934 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005935 if (InFPRs) {
5936 MaxRegs = 4; // Maximum of 4 FPR arguments
5937 RegCountField = 1; // __fpr
5938 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005939 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005940 } else {
5941 MaxRegs = 5; // Maximum of 5 GPR arguments
5942 RegCountField = 0; // __gpr
5943 RegSaveIndex = 2; // save offset for r2
5944 RegPadding = Padding; // values are passed in the low bits of a GPR
5945 }
5946
John McCall7f416cc2015-09-08 08:05:57 +00005947 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5948 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5949 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005950 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005951 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5952 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005953 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005954
5955 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5956 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5957 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5958 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5959
5960 // Emit code to load the value if it was passed in registers.
5961 CGF.EmitBlock(InRegBlock);
5962
5963 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005964 llvm::Value *ScaledRegCount =
5965 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5966 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005967 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5968 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005969 llvm::Value *RegOffset =
5970 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005971 Address RegSaveAreaPtr =
5972 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5973 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005974 llvm::Value *RegSaveArea =
5975 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005976 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5977 "raw_reg_addr"),
5978 PaddedSize);
5979 Address RegAddr =
5980 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005981
5982 // Update the register count
5983 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5984 llvm::Value *NewRegCount =
5985 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5986 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5987 CGF.EmitBranch(ContBlock);
5988
5989 // Emit code to load the value if it was passed in memory.
5990 CGF.EmitBlock(InMemBlock);
5991
5992 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005993 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5994 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5995 Address OverflowArgArea =
5996 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5997 PaddedSize);
5998 Address RawMemAddr =
5999 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6000 Address MemAddr =
6001 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006002
6003 // Update overflow_arg_area_ptr pointer
6004 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006005 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6006 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006007 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6008 CGF.EmitBranch(ContBlock);
6009
6010 // Return the appropriate result.
6011 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006012 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6013 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006014
6015 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006016 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6017 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006018
6019 return ResAddr;
6020}
6021
Ulrich Weigand47445072013-05-06 16:26:41 +00006022ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6023 if (RetTy->isVoidType())
6024 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006025 if (isVectorArgumentType(RetTy))
6026 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006027 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006028 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006029 return (isPromotableIntegerType(RetTy) ?
6030 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6031}
6032
6033ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6034 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006035 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006036 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006037
6038 // Integers and enums are extended to full register width.
6039 if (isPromotableIntegerType(Ty))
6040 return ABIArgInfo::getExtend();
6041
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006042 // Handle vector types and vector-like structure types. Note that
6043 // as opposed to float-like structure types, we do not allow any
6044 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006045 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006046 QualType SingleElementTy = GetSingleElementType(Ty);
6047 if (isVectorArgumentType(SingleElementTy) &&
6048 getContext().getTypeSize(SingleElementTy) == Size)
6049 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6050
6051 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006052 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006053 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006054
6055 // Handle small structures.
6056 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6057 // Structures with flexible arrays have variable length, so really
6058 // fail the size test above.
6059 const RecordDecl *RD = RT->getDecl();
6060 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006061 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006062
6063 // The structure is passed as an unextended integer, a float, or a double.
6064 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006065 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006066 assert(Size == 32 || Size == 64);
6067 if (Size == 32)
6068 PassTy = llvm::Type::getFloatTy(getVMContext());
6069 else
6070 PassTy = llvm::Type::getDoubleTy(getVMContext());
6071 } else
6072 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6073 return ABIArgInfo::getDirect(PassTy);
6074 }
6075
6076 // Non-structure compounds are passed indirectly.
6077 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006078 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006079
Craig Topper8a13c412014-05-21 05:09:00 +00006080 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006081}
6082
6083//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006084// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006085//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006086
6087namespace {
6088
6089class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6090public:
Chris Lattner2b037972010-07-29 02:01:43 +00006091 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6092 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006093 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006094 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006095};
6096
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006097}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006098
Eric Christopher162c91c2015-06-05 22:03:00 +00006099void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006100 llvm::GlobalValue *GV,
6101 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006102 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006103 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6104 // Handle 'interrupt' attribute:
6105 llvm::Function *F = cast<llvm::Function>(GV);
6106
6107 // Step 1: Set ISR calling convention.
6108 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6109
6110 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006111 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006112
6113 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006114 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006115 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6116 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006117 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006118 }
6119}
6120
Chris Lattner0cf24192010-06-28 20:05:43 +00006121//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006122// MIPS ABI Implementation. This works for both little-endian and
6123// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006124//===----------------------------------------------------------------------===//
6125
John McCall943fae92010-05-27 06:19:26 +00006126namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006127class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006128 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006129 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6130 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006131 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006132 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006133 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006134 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006135public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006136 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006137 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006138 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006139
6140 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006141 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006142 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006143 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6144 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006145 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006146};
6147
John McCall943fae92010-05-27 06:19:26 +00006148class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006149 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006150public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006151 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6152 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006153 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006154
Craig Topper4f12f102014-03-12 06:41:41 +00006155 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006156 return 29;
6157 }
6158
Eric Christopher162c91c2015-06-05 22:03:00 +00006159 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006160 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006161 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006162 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006163 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006164 if (FD->hasAttr<Mips16Attr>()) {
6165 Fn->addFnAttr("mips16");
6166 }
6167 else if (FD->hasAttr<NoMips16Attr>()) {
6168 Fn->addFnAttr("nomips16");
6169 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006170
6171 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6172 if (!Attr)
6173 return;
6174
6175 const char *Kind;
6176 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006177 case MipsInterruptAttr::eic: Kind = "eic"; break;
6178 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6179 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6180 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6181 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6182 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6183 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6184 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6185 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6186 }
6187
6188 Fn->addFnAttr("interrupt", Kind);
6189
Reed Kotler373feca2013-01-16 17:10:28 +00006190 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006191
John McCall943fae92010-05-27 06:19:26 +00006192 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006193 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006194
Craig Topper4f12f102014-03-12 06:41:41 +00006195 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006196 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006197 }
John McCall943fae92010-05-27 06:19:26 +00006198};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006199}
John McCall943fae92010-05-27 06:19:26 +00006200
Eric Christopher7565e0d2015-05-29 23:09:49 +00006201void MipsABIInfo::CoerceToIntArgs(
6202 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006203 llvm::IntegerType *IntTy =
6204 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006205
6206 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6207 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6208 ArgList.push_back(IntTy);
6209
6210 // If necessary, add one more integer type to ArgList.
6211 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6212
6213 if (R)
6214 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006215}
6216
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006217// In N32/64, an aligned double precision floating point field is passed in
6218// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006219llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006220 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6221
6222 if (IsO32) {
6223 CoerceToIntArgs(TySize, ArgList);
6224 return llvm::StructType::get(getVMContext(), ArgList);
6225 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006226
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006227 if (Ty->isComplexType())
6228 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006229
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006230 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006231
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006232 // Unions/vectors are passed in integer registers.
6233 if (!RT || !RT->isStructureOrClassType()) {
6234 CoerceToIntArgs(TySize, ArgList);
6235 return llvm::StructType::get(getVMContext(), ArgList);
6236 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006237
6238 const RecordDecl *RD = RT->getDecl();
6239 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006240 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006241
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006242 uint64_t LastOffset = 0;
6243 unsigned idx = 0;
6244 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6245
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006246 // Iterate over fields in the struct/class and check if there are any aligned
6247 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006248 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6249 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006250 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006251 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6252
6253 if (!BT || BT->getKind() != BuiltinType::Double)
6254 continue;
6255
6256 uint64_t Offset = Layout.getFieldOffset(idx);
6257 if (Offset % 64) // Ignore doubles that are not aligned.
6258 continue;
6259
6260 // Add ((Offset - LastOffset) / 64) args of type i64.
6261 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6262 ArgList.push_back(I64);
6263
6264 // Add double type.
6265 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6266 LastOffset = Offset + 64;
6267 }
6268
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006269 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6270 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006271
6272 return llvm::StructType::get(getVMContext(), ArgList);
6273}
6274
Akira Hatanakaddd66342013-10-29 18:41:15 +00006275llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6276 uint64_t Offset) const {
6277 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006278 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006279
Akira Hatanakaddd66342013-10-29 18:41:15 +00006280 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006281}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006282
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006283ABIArgInfo
6284MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006285 Ty = useFirstFieldIfTransparentUnion(Ty);
6286
Akira Hatanaka1632af62012-01-09 19:31:25 +00006287 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006288 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006289 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006290
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006291 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6292 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006293 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6294 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006295
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006296 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006297 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006298 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006299 return ABIArgInfo::getIgnore();
6300
Mark Lacey3825e832013-10-06 01:33:34 +00006301 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006302 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006303 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006304 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006305
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006306 // If we have reached here, aggregates are passed directly by coercing to
6307 // another structure type. Padding is inserted if the offset of the
6308 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006309 ABIArgInfo ArgInfo =
6310 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6311 getPaddingType(OrigOffset, CurrOffset));
6312 ArgInfo.setInReg(true);
6313 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006314 }
6315
6316 // Treat an enum type as its underlying type.
6317 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6318 Ty = EnumTy->getDecl()->getIntegerType();
6319
Daniel Sanders5b445b32014-10-24 14:42:42 +00006320 // All integral types are promoted to the GPR width.
6321 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006322 return ABIArgInfo::getExtend();
6323
Akira Hatanakaddd66342013-10-29 18:41:15 +00006324 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006325 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006326}
6327
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006328llvm::Type*
6329MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006330 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006331 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006332
Akira Hatanakab6f74432012-02-09 18:49:26 +00006333 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006334 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006335 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6336 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006337
Akira Hatanakab6f74432012-02-09 18:49:26 +00006338 // N32/64 returns struct/classes in floating point registers if the
6339 // following conditions are met:
6340 // 1. The size of the struct/class is no larger than 128-bit.
6341 // 2. The struct/class has one or two fields all of which are floating
6342 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006343 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006344 //
6345 // Any other composite results are returned in integer registers.
6346 //
6347 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6348 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6349 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006350 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006351
Akira Hatanakab6f74432012-02-09 18:49:26 +00006352 if (!BT || !BT->isFloatingPoint())
6353 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006354
David Blaikie2d7c57e2012-04-30 02:36:29 +00006355 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006356 }
6357
6358 if (b == e)
6359 return llvm::StructType::get(getVMContext(), RTList,
6360 RD->hasAttr<PackedAttr>());
6361
6362 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006363 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006364 }
6365
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006366 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006367 return llvm::StructType::get(getVMContext(), RTList);
6368}
6369
Akira Hatanakab579fe52011-06-02 00:09:17 +00006370ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006371 uint64_t Size = getContext().getTypeSize(RetTy);
6372
Daniel Sandersed39f582014-09-04 13:28:14 +00006373 if (RetTy->isVoidType())
6374 return ABIArgInfo::getIgnore();
6375
6376 // O32 doesn't treat zero-sized structs differently from other structs.
6377 // However, N32/N64 ignores zero sized return values.
6378 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006379 return ABIArgInfo::getIgnore();
6380
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006381 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006382 if (Size <= 128) {
6383 if (RetTy->isAnyComplexType())
6384 return ABIArgInfo::getDirect();
6385
Daniel Sanderse5018b62014-09-04 15:05:39 +00006386 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006387 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006388 if (!IsO32 ||
6389 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6390 ABIArgInfo ArgInfo =
6391 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6392 ArgInfo.setInReg(true);
6393 return ArgInfo;
6394 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006395 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006396
John McCall7f416cc2015-09-08 08:05:57 +00006397 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006398 }
6399
6400 // Treat an enum type as its underlying type.
6401 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6402 RetTy = EnumTy->getDecl()->getIntegerType();
6403
6404 return (RetTy->isPromotableIntegerType() ?
6405 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6406}
6407
6408void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006409 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006410 if (!getCXXABI().classifyReturnType(FI))
6411 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006412
Eric Christopher7565e0d2015-05-29 23:09:49 +00006413 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006414 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006415
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006416 for (auto &I : FI.arguments())
6417 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006418}
6419
John McCall7f416cc2015-09-08 08:05:57 +00006420Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6421 QualType OrigTy) const {
6422 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006423
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006424 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6425 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006426 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006427 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006428 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006429 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006430 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006431 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006432 DidPromote = true;
6433 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6434 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006435 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006436
John McCall7f416cc2015-09-08 08:05:57 +00006437 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006438
John McCall7f416cc2015-09-08 08:05:57 +00006439 // The alignment of things in the argument area is never larger than
6440 // StackAlignInBytes.
6441 TyInfo.second =
6442 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6443
6444 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6445 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6446
6447 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6448 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6449
6450
6451 // If there was a promotion, "unpromote" into a temporary.
6452 // TODO: can we just use a pointer into a subset of the original slot?
6453 if (DidPromote) {
6454 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6455 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6456
6457 // Truncate down to the right width.
6458 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6459 : CGF.IntPtrTy);
6460 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6461 if (OrigTy->isPointerType())
6462 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6463
6464 CGF.Builder.CreateStore(V, Temp);
6465 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006466 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006467
John McCall7f416cc2015-09-08 08:05:57 +00006468 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006469}
6470
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006471bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6472 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006473
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006474 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6475 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6476 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006477
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006478 return false;
6479}
6480
John McCall943fae92010-05-27 06:19:26 +00006481bool
6482MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6483 llvm::Value *Address) const {
6484 // This information comes from gcc's implementation, which seems to
6485 // as canonical as it gets.
6486
John McCall943fae92010-05-27 06:19:26 +00006487 // Everything on MIPS is 4 bytes. Double-precision FP registers
6488 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006489 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006490
6491 // 0-31 are the general purpose registers, $0 - $31.
6492 // 32-63 are the floating-point registers, $f0 - $f31.
6493 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6494 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006495 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006496
6497 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6498 // They are one bit wide and ignored here.
6499
6500 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6501 // (coprocessor 1 is the FP unit)
6502 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6503 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6504 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006505 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006506 return false;
6507}
6508
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006509//===----------------------------------------------------------------------===//
6510// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006511// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006512// handling.
6513//===----------------------------------------------------------------------===//
6514
6515namespace {
6516
6517class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6518public:
6519 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6520 : DefaultTargetCodeGenInfo(CGT) {}
6521
Eric Christopher162c91c2015-06-05 22:03:00 +00006522 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006523 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006524};
6525
Eric Christopher162c91c2015-06-05 22:03:00 +00006526void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006527 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006528 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006529 if (!FD) return;
6530
6531 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006532
David Blaikiebbafb8a2012-03-11 07:00:24 +00006533 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006534 if (FD->hasAttr<OpenCLKernelAttr>()) {
6535 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006536 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006537 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6538 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006539 // Convert the reqd_work_group_size() attributes to metadata.
6540 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006541 llvm::NamedMDNode *OpenCLMetadata =
6542 M.getModule().getOrInsertNamedMetadata(
6543 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006544
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006545 SmallVector<llvm::Metadata *, 5> Operands;
6546 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006547
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006548 Operands.push_back(
6549 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6550 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6551 Operands.push_back(
6552 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6553 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6554 Operands.push_back(
6555 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6556 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006557
Eric Christopher7565e0d2015-05-29 23:09:49 +00006558 // Add a boolean constant operand for "required" (true) or "hint"
6559 // (false) for implementing the work_group_size_hint attr later.
6560 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006561 Operands.push_back(
6562 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006563 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6564 }
6565 }
6566 }
6567}
6568
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006569}
John McCall943fae92010-05-27 06:19:26 +00006570
Tony Linthicum76329bf2011-12-12 21:14:55 +00006571//===----------------------------------------------------------------------===//
6572// Hexagon ABI Implementation
6573//===----------------------------------------------------------------------===//
6574
6575namespace {
6576
6577class HexagonABIInfo : public ABIInfo {
6578
6579
6580public:
6581 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6582
6583private:
6584
6585 ABIArgInfo classifyReturnType(QualType RetTy) const;
6586 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6587
Craig Topper4f12f102014-03-12 06:41:41 +00006588 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006589
John McCall7f416cc2015-09-08 08:05:57 +00006590 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6591 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006592};
6593
6594class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6595public:
6596 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6597 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6598
Craig Topper4f12f102014-03-12 06:41:41 +00006599 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006600 return 29;
6601 }
6602};
6603
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006604}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006605
6606void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006607 if (!getCXXABI().classifyReturnType(FI))
6608 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006609 for (auto &I : FI.arguments())
6610 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006611}
6612
6613ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6614 if (!isAggregateTypeForABI(Ty)) {
6615 // Treat an enum type as its underlying type.
6616 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6617 Ty = EnumTy->getDecl()->getIntegerType();
6618
6619 return (Ty->isPromotableIntegerType() ?
6620 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6621 }
6622
6623 // Ignore empty records.
6624 if (isEmptyRecord(getContext(), Ty, true))
6625 return ABIArgInfo::getIgnore();
6626
Mark Lacey3825e832013-10-06 01:33:34 +00006627 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006628 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006629
6630 uint64_t Size = getContext().getTypeSize(Ty);
6631 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006632 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006633 // Pass in the smallest viable integer type.
6634 else if (Size > 32)
6635 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6636 else if (Size > 16)
6637 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6638 else if (Size > 8)
6639 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6640 else
6641 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6642}
6643
6644ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6645 if (RetTy->isVoidType())
6646 return ABIArgInfo::getIgnore();
6647
6648 // Large vector types should be returned via memory.
6649 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006650 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006651
6652 if (!isAggregateTypeForABI(RetTy)) {
6653 // Treat an enum type as its underlying type.
6654 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6655 RetTy = EnumTy->getDecl()->getIntegerType();
6656
6657 return (RetTy->isPromotableIntegerType() ?
6658 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6659 }
6660
Tony Linthicum76329bf2011-12-12 21:14:55 +00006661 if (isEmptyRecord(getContext(), RetTy, true))
6662 return ABIArgInfo::getIgnore();
6663
6664 // Aggregates <= 8 bytes are returned in r0; other aggregates
6665 // are returned indirectly.
6666 uint64_t Size = getContext().getTypeSize(RetTy);
6667 if (Size <= 64) {
6668 // Return in the smallest viable integer type.
6669 if (Size <= 8)
6670 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6671 if (Size <= 16)
6672 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6673 if (Size <= 32)
6674 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6675 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6676 }
6677
John McCall7f416cc2015-09-08 08:05:57 +00006678 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006679}
6680
John McCall7f416cc2015-09-08 08:05:57 +00006681Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6682 QualType Ty) const {
6683 // FIXME: Someone needs to audit that this handle alignment correctly.
6684 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6685 getContext().getTypeInfoInChars(Ty),
6686 CharUnits::fromQuantity(4),
6687 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006688}
6689
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006690//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006691// Lanai ABI Implementation
6692//===----------------------------------------------------------------------===//
6693
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006694namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006695class LanaiABIInfo : public DefaultABIInfo {
6696public:
6697 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6698
6699 bool shouldUseInReg(QualType Ty, CCState &State) const;
6700
6701 void computeInfo(CGFunctionInfo &FI) const override {
6702 CCState State(FI.getCallingConvention());
6703 // Lanai uses 4 registers to pass arguments unless the function has the
6704 // regparm attribute set.
6705 if (FI.getHasRegParm()) {
6706 State.FreeRegs = FI.getRegParm();
6707 } else {
6708 State.FreeRegs = 4;
6709 }
6710
6711 if (!getCXXABI().classifyReturnType(FI))
6712 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6713 for (auto &I : FI.arguments())
6714 I.info = classifyArgumentType(I.type, State);
6715 }
6716
Jacques Pienaare74d9132016-04-26 00:09:29 +00006717 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006718 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6719};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006720} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006721
6722bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6723 unsigned Size = getContext().getTypeSize(Ty);
6724 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6725
6726 if (SizeInRegs == 0)
6727 return false;
6728
6729 if (SizeInRegs > State.FreeRegs) {
6730 State.FreeRegs = 0;
6731 return false;
6732 }
6733
6734 State.FreeRegs -= SizeInRegs;
6735
6736 return true;
6737}
6738
Jacques Pienaare74d9132016-04-26 00:09:29 +00006739ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6740 CCState &State) const {
6741 if (!ByVal) {
6742 if (State.FreeRegs) {
6743 --State.FreeRegs; // Non-byval indirects just use one pointer.
6744 return getNaturalAlignIndirectInReg(Ty);
6745 }
6746 return getNaturalAlignIndirect(Ty, false);
6747 }
6748
6749 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00006750 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00006751 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6752 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6753 /*Realign=*/TypeAlign >
6754 MinABIStackAlignInBytes);
6755}
6756
Jacques Pienaard964cc22016-03-28 21:02:54 +00006757ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6758 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006759 // Check with the C++ ABI first.
6760 const RecordType *RT = Ty->getAs<RecordType>();
6761 if (RT) {
6762 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6763 if (RAA == CGCXXABI::RAA_Indirect) {
6764 return getIndirectResult(Ty, /*ByVal=*/false, State);
6765 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6766 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6767 }
6768 }
6769
6770 if (isAggregateTypeForABI(Ty)) {
6771 // Structures with flexible arrays are always indirect.
6772 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6773 return getIndirectResult(Ty, /*ByVal=*/true, State);
6774
6775 // Ignore empty structs/unions.
6776 if (isEmptyRecord(getContext(), Ty, true))
6777 return ABIArgInfo::getIgnore();
6778
6779 llvm::LLVMContext &LLVMContext = getVMContext();
6780 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6781 if (SizeInRegs <= State.FreeRegs) {
6782 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6783 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6784 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6785 State.FreeRegs -= SizeInRegs;
6786 return ABIArgInfo::getDirectInReg(Result);
6787 } else {
6788 State.FreeRegs = 0;
6789 }
6790 return getIndirectResult(Ty, true, State);
6791 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00006792
6793 // Treat an enum type as its underlying type.
6794 if (const auto *EnumTy = Ty->getAs<EnumType>())
6795 Ty = EnumTy->getDecl()->getIntegerType();
6796
Jacques Pienaare74d9132016-04-26 00:09:29 +00006797 bool InReg = shouldUseInReg(Ty, State);
6798 if (Ty->isPromotableIntegerType()) {
6799 if (InReg)
6800 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006801 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00006802 }
6803 if (InReg)
6804 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006805 return ABIArgInfo::getDirect();
6806}
6807
6808namespace {
6809class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6810public:
6811 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
6812 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
6813};
6814}
6815
6816//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006817// AMDGPU ABI Implementation
6818//===----------------------------------------------------------------------===//
6819
6820namespace {
6821
6822class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6823public:
6824 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6825 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006826 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006827 CodeGen::CodeGenModule &M) const override;
6828};
6829
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006830}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006831
Eric Christopher162c91c2015-06-05 22:03:00 +00006832void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006833 const Decl *D,
6834 llvm::GlobalValue *GV,
6835 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006836 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006837 if (!FD)
6838 return;
6839
6840 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6841 llvm::Function *F = cast<llvm::Function>(GV);
6842 uint32_t NumVGPR = Attr->getNumVGPR();
6843 if (NumVGPR != 0)
6844 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6845 }
6846
6847 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6848 llvm::Function *F = cast<llvm::Function>(GV);
6849 unsigned NumSGPR = Attr->getNumSGPR();
6850 if (NumSGPR != 0)
6851 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6852 }
6853}
6854
Tony Linthicum76329bf2011-12-12 21:14:55 +00006855
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006856//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00006857// SPARC v8 ABI Implementation.
6858// Based on the SPARC Compliance Definition version 2.4.1.
6859//
6860// Ensures that complex values are passed in registers.
6861//
6862namespace {
6863class SparcV8ABIInfo : public DefaultABIInfo {
6864public:
6865 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6866
6867private:
6868 ABIArgInfo classifyReturnType(QualType RetTy) const;
6869 void computeInfo(CGFunctionInfo &FI) const override;
6870};
6871} // end anonymous namespace
6872
6873
6874ABIArgInfo
6875SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
6876 if (Ty->isAnyComplexType()) {
6877 return ABIArgInfo::getDirect();
6878 }
6879 else {
6880 return DefaultABIInfo::classifyReturnType(Ty);
6881 }
6882}
6883
6884void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6885
6886 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6887 for (auto &Arg : FI.arguments())
6888 Arg.info = classifyArgumentType(Arg.type);
6889}
6890
6891namespace {
6892class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
6893public:
6894 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
6895 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
6896};
6897} // end anonymous namespace
6898
6899//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006900// SPARC v9 ABI Implementation.
6901// Based on the SPARC Compliance Definition version 2.4.1.
6902//
6903// Function arguments a mapped to a nominal "parameter array" and promoted to
6904// registers depending on their type. Each argument occupies 8 or 16 bytes in
6905// the array, structs larger than 16 bytes are passed indirectly.
6906//
6907// One case requires special care:
6908//
6909// struct mixed {
6910// int i;
6911// float f;
6912// };
6913//
6914// When a struct mixed is passed by value, it only occupies 8 bytes in the
6915// parameter array, but the int is passed in an integer register, and the float
6916// is passed in a floating point register. This is represented as two arguments
6917// with the LLVM IR inreg attribute:
6918//
6919// declare void f(i32 inreg %i, float inreg %f)
6920//
6921// The code generator will only allocate 4 bytes from the parameter array for
6922// the inreg arguments. All other arguments are allocated a multiple of 8
6923// bytes.
6924//
6925namespace {
6926class SparcV9ABIInfo : public ABIInfo {
6927public:
6928 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6929
6930private:
6931 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006932 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006933 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6934 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006935
6936 // Coercion type builder for structs passed in registers. The coercion type
6937 // serves two purposes:
6938 //
6939 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6940 // in registers.
6941 // 2. Expose aligned floating point elements as first-level elements, so the
6942 // code generator knows to pass them in floating point registers.
6943 //
6944 // We also compute the InReg flag which indicates that the struct contains
6945 // aligned 32-bit floats.
6946 //
6947 struct CoerceBuilder {
6948 llvm::LLVMContext &Context;
6949 const llvm::DataLayout &DL;
6950 SmallVector<llvm::Type*, 8> Elems;
6951 uint64_t Size;
6952 bool InReg;
6953
6954 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6955 : Context(c), DL(dl), Size(0), InReg(false) {}
6956
6957 // Pad Elems with integers until Size is ToSize.
6958 void pad(uint64_t ToSize) {
6959 assert(ToSize >= Size && "Cannot remove elements");
6960 if (ToSize == Size)
6961 return;
6962
6963 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006964 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006965 if (Aligned > Size && Aligned <= ToSize) {
6966 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6967 Size = Aligned;
6968 }
6969
6970 // Add whole 64-bit words.
6971 while (Size + 64 <= ToSize) {
6972 Elems.push_back(llvm::Type::getInt64Ty(Context));
6973 Size += 64;
6974 }
6975
6976 // Final in-word padding.
6977 if (Size < ToSize) {
6978 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6979 Size = ToSize;
6980 }
6981 }
6982
6983 // Add a floating point element at Offset.
6984 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6985 // Unaligned floats are treated as integers.
6986 if (Offset % Bits)
6987 return;
6988 // The InReg flag is only required if there are any floats < 64 bits.
6989 if (Bits < 64)
6990 InReg = true;
6991 pad(Offset);
6992 Elems.push_back(Ty);
6993 Size = Offset + Bits;
6994 }
6995
6996 // Add a struct type to the coercion type, starting at Offset (in bits).
6997 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6998 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6999 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7000 llvm::Type *ElemTy = StrTy->getElementType(i);
7001 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7002 switch (ElemTy->getTypeID()) {
7003 case llvm::Type::StructTyID:
7004 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7005 break;
7006 case llvm::Type::FloatTyID:
7007 addFloat(ElemOffset, ElemTy, 32);
7008 break;
7009 case llvm::Type::DoubleTyID:
7010 addFloat(ElemOffset, ElemTy, 64);
7011 break;
7012 case llvm::Type::FP128TyID:
7013 addFloat(ElemOffset, ElemTy, 128);
7014 break;
7015 case llvm::Type::PointerTyID:
7016 if (ElemOffset % 64 == 0) {
7017 pad(ElemOffset);
7018 Elems.push_back(ElemTy);
7019 Size += 64;
7020 }
7021 break;
7022 default:
7023 break;
7024 }
7025 }
7026 }
7027
7028 // Check if Ty is a usable substitute for the coercion type.
7029 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007030 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007031 }
7032
7033 // Get the coercion type as a literal struct type.
7034 llvm::Type *getType() const {
7035 if (Elems.size() == 1)
7036 return Elems.front();
7037 else
7038 return llvm::StructType::get(Context, Elems);
7039 }
7040 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007041};
7042} // end anonymous namespace
7043
7044ABIArgInfo
7045SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7046 if (Ty->isVoidType())
7047 return ABIArgInfo::getIgnore();
7048
7049 uint64_t Size = getContext().getTypeSize(Ty);
7050
7051 // Anything too big to fit in registers is passed with an explicit indirect
7052 // pointer / sret pointer.
7053 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007054 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007055
7056 // Treat an enum type as its underlying type.
7057 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7058 Ty = EnumTy->getDecl()->getIntegerType();
7059
7060 // Integer types smaller than a register are extended.
7061 if (Size < 64 && Ty->isIntegerType())
7062 return ABIArgInfo::getExtend();
7063
7064 // Other non-aggregates go in registers.
7065 if (!isAggregateTypeForABI(Ty))
7066 return ABIArgInfo::getDirect();
7067
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007068 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7069 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7070 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007071 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007072
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007073 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007074 // Build a coercion type from the LLVM struct type.
7075 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7076 if (!StrTy)
7077 return ABIArgInfo::getDirect();
7078
7079 CoerceBuilder CB(getVMContext(), getDataLayout());
7080 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007081 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007082
7083 // Try to use the original type for coercion.
7084 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7085
7086 if (CB.InReg)
7087 return ABIArgInfo::getDirectInReg(CoerceTy);
7088 else
7089 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007090}
7091
John McCall7f416cc2015-09-08 08:05:57 +00007092Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7093 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007094 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7095 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7096 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7097 AI.setCoerceToType(ArgTy);
7098
John McCall7f416cc2015-09-08 08:05:57 +00007099 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007100
John McCall7f416cc2015-09-08 08:05:57 +00007101 CGBuilderTy &Builder = CGF.Builder;
7102 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7103 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7104
7105 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7106
7107 Address ArgAddr = Address::invalid();
7108 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007109 switch (AI.getKind()) {
7110 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007111 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007112 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007113 llvm_unreachable("Unsupported ABI kind for va_arg");
7114
John McCall7f416cc2015-09-08 08:05:57 +00007115 case ABIArgInfo::Extend: {
7116 Stride = SlotSize;
7117 CharUnits Offset = SlotSize - TypeInfo.first;
7118 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007119 break;
John McCall7f416cc2015-09-08 08:05:57 +00007120 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007121
John McCall7f416cc2015-09-08 08:05:57 +00007122 case ABIArgInfo::Direct: {
7123 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007124 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007125 ArgAddr = Addr;
7126 break;
John McCall7f416cc2015-09-08 08:05:57 +00007127 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007128
7129 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007130 Stride = SlotSize;
7131 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7132 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7133 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007134 break;
7135
7136 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007137 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007138 }
7139
7140 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007141 llvm::Value *NextPtr =
7142 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7143 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007144
John McCall7f416cc2015-09-08 08:05:57 +00007145 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007146}
7147
7148void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7149 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007150 for (auto &I : FI.arguments())
7151 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007152}
7153
7154namespace {
7155class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7156public:
7157 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7158 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007159
Craig Topper4f12f102014-03-12 06:41:41 +00007160 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007161 return 14;
7162 }
7163
7164 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007165 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007166};
7167} // end anonymous namespace
7168
Roman Divackyf02c9942014-02-24 18:46:27 +00007169bool
7170SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7171 llvm::Value *Address) const {
7172 // This is calculated from the LLVM and GCC tables and verified
7173 // against gcc output. AFAIK all ABIs use the same encoding.
7174
7175 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7176
7177 llvm::IntegerType *i8 = CGF.Int8Ty;
7178 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7179 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7180
7181 // 0-31: the 8-byte general-purpose registers
7182 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7183
7184 // 32-63: f0-31, the 4-byte floating-point registers
7185 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7186
7187 // Y = 64
7188 // PSR = 65
7189 // WIM = 66
7190 // TBR = 67
7191 // PC = 68
7192 // NPC = 69
7193 // FSR = 70
7194 // CSR = 71
7195 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007196
Roman Divackyf02c9942014-02-24 18:46:27 +00007197 // 72-87: d0-15, the 8-byte floating-point registers
7198 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7199
7200 return false;
7201}
7202
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007203
Robert Lytton0e076492013-08-13 09:43:10 +00007204//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007205// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007206//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007207
Robert Lytton0e076492013-08-13 09:43:10 +00007208namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007209
7210/// A SmallStringEnc instance is used to build up the TypeString by passing
7211/// it by reference between functions that append to it.
7212typedef llvm::SmallString<128> SmallStringEnc;
7213
7214/// TypeStringCache caches the meta encodings of Types.
7215///
7216/// The reason for caching TypeStrings is two fold:
7217/// 1. To cache a type's encoding for later uses;
7218/// 2. As a means to break recursive member type inclusion.
7219///
7220/// A cache Entry can have a Status of:
7221/// NonRecursive: The type encoding is not recursive;
7222/// Recursive: The type encoding is recursive;
7223/// Incomplete: An incomplete TypeString;
7224/// IncompleteUsed: An incomplete TypeString that has been used in a
7225/// Recursive type encoding.
7226///
7227/// A NonRecursive entry will have all of its sub-members expanded as fully
7228/// as possible. Whilst it may contain types which are recursive, the type
7229/// itself is not recursive and thus its encoding may be safely used whenever
7230/// the type is encountered.
7231///
7232/// A Recursive entry will have all of its sub-members expanded as fully as
7233/// possible. The type itself is recursive and it may contain other types which
7234/// are recursive. The Recursive encoding must not be used during the expansion
7235/// of a recursive type's recursive branch. For simplicity the code uses
7236/// IncompleteCount to reject all usage of Recursive encodings for member types.
7237///
7238/// An Incomplete entry is always a RecordType and only encodes its
7239/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7240/// are placed into the cache during type expansion as a means to identify and
7241/// handle recursive inclusion of types as sub-members. If there is recursion
7242/// the entry becomes IncompleteUsed.
7243///
7244/// During the expansion of a RecordType's members:
7245///
7246/// If the cache contains a NonRecursive encoding for the member type, the
7247/// cached encoding is used;
7248///
7249/// If the cache contains a Recursive encoding for the member type, the
7250/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7251///
7252/// If the member is a RecordType, an Incomplete encoding is placed into the
7253/// cache to break potential recursive inclusion of itself as a sub-member;
7254///
7255/// Once a member RecordType has been expanded, its temporary incomplete
7256/// entry is removed from the cache. If a Recursive encoding was swapped out
7257/// it is swapped back in;
7258///
7259/// If an incomplete entry is used to expand a sub-member, the incomplete
7260/// entry is marked as IncompleteUsed. The cache keeps count of how many
7261/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7262///
7263/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7264/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7265/// Else the member is part of a recursive type and thus the recursion has
7266/// been exited too soon for the encoding to be correct for the member.
7267///
7268class TypeStringCache {
7269 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7270 struct Entry {
7271 std::string Str; // The encoded TypeString for the type.
7272 enum Status State; // Information about the encoding in 'Str'.
7273 std::string Swapped; // A temporary place holder for a Recursive encoding
7274 // during the expansion of RecordType's members.
7275 };
7276 std::map<const IdentifierInfo *, struct Entry> Map;
7277 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7278 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7279public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007280 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007281 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7282 bool removeIncomplete(const IdentifierInfo *ID);
7283 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7284 bool IsRecursive);
7285 StringRef lookupStr(const IdentifierInfo *ID);
7286};
7287
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007288/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007289/// FieldEncoding is a helper for this ordering process.
7290class FieldEncoding {
7291 bool HasName;
7292 std::string Enc;
7293public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007294 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7295 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007296 bool operator<(const FieldEncoding &rhs) const {
7297 if (HasName != rhs.HasName) return HasName;
7298 return Enc < rhs.Enc;
7299 }
7300};
7301
Robert Lytton7d1db152013-08-19 09:46:39 +00007302class XCoreABIInfo : public DefaultABIInfo {
7303public:
7304 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007305 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7306 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007307};
7308
Robert Lyttond21e2d72014-03-03 13:45:29 +00007309class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007310 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007311public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007312 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007313 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007314 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7315 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007316};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007317
Robert Lytton2d196952013-10-11 10:29:34 +00007318} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007319
James Y Knight29b5f082016-02-24 02:59:33 +00007320// TODO: this implementation is likely now redundant with the default
7321// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007322Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7323 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007324 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007325
Robert Lytton2d196952013-10-11 10:29:34 +00007326 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007327 CharUnits SlotSize = CharUnits::fromQuantity(4);
7328 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007329
Robert Lytton2d196952013-10-11 10:29:34 +00007330 // Handle the argument.
7331 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007332 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007333 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7334 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7335 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007336 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007337
7338 Address Val = Address::invalid();
7339 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007340 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007341 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007342 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007343 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007344 llvm_unreachable("Unsupported ABI kind for va_arg");
7345 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007346 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7347 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007348 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007349 case ABIArgInfo::Extend:
7350 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007351 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7352 ArgSize = CharUnits::fromQuantity(
7353 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007354 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007355 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007356 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007357 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7358 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7359 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007360 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007361 }
Robert Lytton2d196952013-10-11 10:29:34 +00007362
7363 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007364 if (!ArgSize.isZero()) {
7365 llvm::Value *APN =
7366 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7367 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007368 }
John McCall7f416cc2015-09-08 08:05:57 +00007369
Robert Lytton2d196952013-10-11 10:29:34 +00007370 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007371}
Robert Lytton0e076492013-08-13 09:43:10 +00007372
Robert Lytton844aeeb2014-05-02 09:33:20 +00007373/// During the expansion of a RecordType, an incomplete TypeString is placed
7374/// into the cache as a means to identify and break recursion.
7375/// If there is a Recursive encoding in the cache, it is swapped out and will
7376/// be reinserted by removeIncomplete().
7377/// All other types of encoding should have been used rather than arriving here.
7378void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7379 std::string StubEnc) {
7380 if (!ID)
7381 return;
7382 Entry &E = Map[ID];
7383 assert( (E.Str.empty() || E.State == Recursive) &&
7384 "Incorrectly use of addIncomplete");
7385 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7386 E.Swapped.swap(E.Str); // swap out the Recursive
7387 E.Str.swap(StubEnc);
7388 E.State = Incomplete;
7389 ++IncompleteCount;
7390}
7391
7392/// Once the RecordType has been expanded, the temporary incomplete TypeString
7393/// must be removed from the cache.
7394/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7395/// Returns true if the RecordType was defined recursively.
7396bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7397 if (!ID)
7398 return false;
7399 auto I = Map.find(ID);
7400 assert(I != Map.end() && "Entry not present");
7401 Entry &E = I->second;
7402 assert( (E.State == Incomplete ||
7403 E.State == IncompleteUsed) &&
7404 "Entry must be an incomplete type");
7405 bool IsRecursive = false;
7406 if (E.State == IncompleteUsed) {
7407 // We made use of our Incomplete encoding, thus we are recursive.
7408 IsRecursive = true;
7409 --IncompleteUsedCount;
7410 }
7411 if (E.Swapped.empty())
7412 Map.erase(I);
7413 else {
7414 // Swap the Recursive back.
7415 E.Swapped.swap(E.Str);
7416 E.Swapped.clear();
7417 E.State = Recursive;
7418 }
7419 --IncompleteCount;
7420 return IsRecursive;
7421}
7422
7423/// Add the encoded TypeString to the cache only if it is NonRecursive or
7424/// Recursive (viz: all sub-members were expanded as fully as possible).
7425void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7426 bool IsRecursive) {
7427 if (!ID || IncompleteUsedCount)
7428 return; // No key or it is is an incomplete sub-type so don't add.
7429 Entry &E = Map[ID];
7430 if (IsRecursive && !E.Str.empty()) {
7431 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7432 "This is not the same Recursive entry");
7433 // The parent container was not recursive after all, so we could have used
7434 // this Recursive sub-member entry after all, but we assumed the worse when
7435 // we started viz: IncompleteCount!=0.
7436 return;
7437 }
7438 assert(E.Str.empty() && "Entry already present");
7439 E.Str = Str.str();
7440 E.State = IsRecursive? Recursive : NonRecursive;
7441}
7442
7443/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7444/// are recursively expanding a type (IncompleteCount != 0) and the cached
7445/// encoding is Recursive, return an empty StringRef.
7446StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7447 if (!ID)
7448 return StringRef(); // We have no key.
7449 auto I = Map.find(ID);
7450 if (I == Map.end())
7451 return StringRef(); // We have no encoding.
7452 Entry &E = I->second;
7453 if (E.State == Recursive && IncompleteCount)
7454 return StringRef(); // We don't use Recursive encodings for member types.
7455
7456 if (E.State == Incomplete) {
7457 // The incomplete type is being used to break out of recursion.
7458 E.State = IncompleteUsed;
7459 ++IncompleteUsedCount;
7460 }
7461 return E.Str.c_str();
7462}
7463
7464/// The XCore ABI includes a type information section that communicates symbol
7465/// type information to the linker. The linker uses this information to verify
7466/// safety/correctness of things such as array bound and pointers et al.
7467/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7468/// This type information (TypeString) is emitted into meta data for all global
7469/// symbols: definitions, declarations, functions & variables.
7470///
7471/// The TypeString carries type, qualifier, name, size & value details.
7472/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007473/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007474/// The output is tested by test/CodeGen/xcore-stringtype.c.
7475///
7476static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7477 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7478
7479/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7480void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7481 CodeGen::CodeGenModule &CGM) const {
7482 SmallStringEnc Enc;
7483 if (getTypeString(Enc, D, CGM, TSC)) {
7484 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007485 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7486 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007487 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7488 llvm::NamedMDNode *MD =
7489 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7490 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7491 }
7492}
7493
Xiuli Pan972bea82016-03-24 03:57:17 +00007494//===----------------------------------------------------------------------===//
7495// SPIR ABI Implementation
7496//===----------------------------------------------------------------------===//
7497
7498namespace {
7499class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7500public:
7501 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7502 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7503 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7504 CodeGen::CodeGenModule &M) const override;
7505};
7506} // End anonymous namespace.
7507
7508/// Emit SPIR specific metadata: OpenCL and SPIR version.
7509void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7510 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00007511 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7512 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7513 llvm::Module &M = CGM.getModule();
7514 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7515 // opencl.spir.version named metadata.
7516 llvm::Metadata *SPIRVerElts[] = {
7517 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7518 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7519 llvm::NamedMDNode *SPIRVerMD =
7520 M.getOrInsertNamedMetadata("opencl.spir.version");
7521 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
7522 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7523 // opencl.ocl.version named metadata node.
7524 llvm::Metadata *OCLVerElts[] = {
7525 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7526 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7527 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7528 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7529 llvm::NamedMDNode *OCLVerMD =
7530 M.getOrInsertNamedMetadata("opencl.ocl.version");
7531 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7532}
7533
Robert Lytton844aeeb2014-05-02 09:33:20 +00007534static bool appendType(SmallStringEnc &Enc, QualType QType,
7535 const CodeGen::CodeGenModule &CGM,
7536 TypeStringCache &TSC);
7537
7538/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007539/// Builds a SmallVector containing the encoded field types in declaration
7540/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007541static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7542 const RecordDecl *RD,
7543 const CodeGen::CodeGenModule &CGM,
7544 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007545 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007546 SmallStringEnc Enc;
7547 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007548 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007549 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007550 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007551 Enc += "b(";
7552 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007553 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007554 Enc += ':';
7555 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007556 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007557 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007558 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007559 Enc += ')';
7560 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007561 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007562 }
7563 return true;
7564}
7565
7566/// Appends structure and union types to Enc and adds encoding to cache.
7567/// Recursively calls appendType (via extractFieldType) for each field.
7568/// Union types have their fields ordered according to the ABI.
7569static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7570 const CodeGen::CodeGenModule &CGM,
7571 TypeStringCache &TSC, const IdentifierInfo *ID) {
7572 // Append the cached TypeString if we have one.
7573 StringRef TypeString = TSC.lookupStr(ID);
7574 if (!TypeString.empty()) {
7575 Enc += TypeString;
7576 return true;
7577 }
7578
7579 // Start to emit an incomplete TypeString.
7580 size_t Start = Enc.size();
7581 Enc += (RT->isUnionType()? 'u' : 's');
7582 Enc += '(';
7583 if (ID)
7584 Enc += ID->getName();
7585 Enc += "){";
7586
7587 // We collect all encoded fields and order as necessary.
7588 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007589 const RecordDecl *RD = RT->getDecl()->getDefinition();
7590 if (RD && !RD->field_empty()) {
7591 // An incomplete TypeString stub is placed in the cache for this RecordType
7592 // so that recursive calls to this RecordType will use it whilst building a
7593 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007594 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007595 std::string StubEnc(Enc.substr(Start).str());
7596 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7597 TSC.addIncomplete(ID, std::move(StubEnc));
7598 if (!extractFieldType(FE, RD, CGM, TSC)) {
7599 (void) TSC.removeIncomplete(ID);
7600 return false;
7601 }
7602 IsRecursive = TSC.removeIncomplete(ID);
7603 // The ABI requires unions to be sorted but not structures.
7604 // See FieldEncoding::operator< for sort algorithm.
7605 if (RT->isUnionType())
7606 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007607 // We can now complete the TypeString.
7608 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007609 for (unsigned I = 0; I != E; ++I) {
7610 if (I)
7611 Enc += ',';
7612 Enc += FE[I].str();
7613 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007614 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007615 Enc += '}';
7616 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7617 return true;
7618}
7619
7620/// Appends enum types to Enc and adds the encoding to the cache.
7621static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7622 TypeStringCache &TSC,
7623 const IdentifierInfo *ID) {
7624 // Append the cached TypeString if we have one.
7625 StringRef TypeString = TSC.lookupStr(ID);
7626 if (!TypeString.empty()) {
7627 Enc += TypeString;
7628 return true;
7629 }
7630
7631 size_t Start = Enc.size();
7632 Enc += "e(";
7633 if (ID)
7634 Enc += ID->getName();
7635 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007636
7637 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007638 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007639 SmallVector<FieldEncoding, 16> FE;
7640 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7641 ++I) {
7642 SmallStringEnc EnumEnc;
7643 EnumEnc += "m(";
7644 EnumEnc += I->getName();
7645 EnumEnc += "){";
7646 I->getInitVal().toString(EnumEnc);
7647 EnumEnc += '}';
7648 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7649 }
7650 std::sort(FE.begin(), FE.end());
7651 unsigned E = FE.size();
7652 for (unsigned I = 0; I != E; ++I) {
7653 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007654 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007655 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007656 }
7657 }
7658 Enc += '}';
7659 TSC.addIfComplete(ID, Enc.substr(Start), false);
7660 return true;
7661}
7662
7663/// Appends type's qualifier to Enc.
7664/// This is done prior to appending the type's encoding.
7665static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7666 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007667 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007668 int Lookup = 0;
7669 if (QT.isConstQualified())
7670 Lookup += 1<<0;
7671 if (QT.isRestrictQualified())
7672 Lookup += 1<<1;
7673 if (QT.isVolatileQualified())
7674 Lookup += 1<<2;
7675 Enc += Table[Lookup];
7676}
7677
7678/// Appends built-in types to Enc.
7679static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7680 const char *EncType;
7681 switch (BT->getKind()) {
7682 case BuiltinType::Void:
7683 EncType = "0";
7684 break;
7685 case BuiltinType::Bool:
7686 EncType = "b";
7687 break;
7688 case BuiltinType::Char_U:
7689 EncType = "uc";
7690 break;
7691 case BuiltinType::UChar:
7692 EncType = "uc";
7693 break;
7694 case BuiltinType::SChar:
7695 EncType = "sc";
7696 break;
7697 case BuiltinType::UShort:
7698 EncType = "us";
7699 break;
7700 case BuiltinType::Short:
7701 EncType = "ss";
7702 break;
7703 case BuiltinType::UInt:
7704 EncType = "ui";
7705 break;
7706 case BuiltinType::Int:
7707 EncType = "si";
7708 break;
7709 case BuiltinType::ULong:
7710 EncType = "ul";
7711 break;
7712 case BuiltinType::Long:
7713 EncType = "sl";
7714 break;
7715 case BuiltinType::ULongLong:
7716 EncType = "ull";
7717 break;
7718 case BuiltinType::LongLong:
7719 EncType = "sll";
7720 break;
7721 case BuiltinType::Float:
7722 EncType = "ft";
7723 break;
7724 case BuiltinType::Double:
7725 EncType = "d";
7726 break;
7727 case BuiltinType::LongDouble:
7728 EncType = "ld";
7729 break;
7730 default:
7731 return false;
7732 }
7733 Enc += EncType;
7734 return true;
7735}
7736
7737/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7738static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7739 const CodeGen::CodeGenModule &CGM,
7740 TypeStringCache &TSC) {
7741 Enc += "p(";
7742 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7743 return false;
7744 Enc += ')';
7745 return true;
7746}
7747
7748/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007749static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7750 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007751 const CodeGen::CodeGenModule &CGM,
7752 TypeStringCache &TSC, StringRef NoSizeEnc) {
7753 if (AT->getSizeModifier() != ArrayType::Normal)
7754 return false;
7755 Enc += "a(";
7756 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7757 CAT->getSize().toStringUnsigned(Enc);
7758 else
7759 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7760 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007761 // The Qualifiers should be attached to the type rather than the array.
7762 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007763 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7764 return false;
7765 Enc += ')';
7766 return true;
7767}
7768
7769/// Appends a function encoding to Enc, calling appendType for the return type
7770/// and the arguments.
7771static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7772 const CodeGen::CodeGenModule &CGM,
7773 TypeStringCache &TSC) {
7774 Enc += "f{";
7775 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7776 return false;
7777 Enc += "}(";
7778 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7779 // N.B. we are only interested in the adjusted param types.
7780 auto I = FPT->param_type_begin();
7781 auto E = FPT->param_type_end();
7782 if (I != E) {
7783 do {
7784 if (!appendType(Enc, *I, CGM, TSC))
7785 return false;
7786 ++I;
7787 if (I != E)
7788 Enc += ',';
7789 } while (I != E);
7790 if (FPT->isVariadic())
7791 Enc += ",va";
7792 } else {
7793 if (FPT->isVariadic())
7794 Enc += "va";
7795 else
7796 Enc += '0';
7797 }
7798 }
7799 Enc += ')';
7800 return true;
7801}
7802
7803/// Handles the type's qualifier before dispatching a call to handle specific
7804/// type encodings.
7805static bool appendType(SmallStringEnc &Enc, QualType QType,
7806 const CodeGen::CodeGenModule &CGM,
7807 TypeStringCache &TSC) {
7808
7809 QualType QT = QType.getCanonicalType();
7810
Robert Lytton6adb20f2014-06-05 09:06:21 +00007811 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7812 // The Qualifiers should be attached to the type rather than the array.
7813 // Thus we don't call appendQualifier() here.
7814 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7815
Robert Lytton844aeeb2014-05-02 09:33:20 +00007816 appendQualifier(Enc, QT);
7817
7818 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7819 return appendBuiltinType(Enc, BT);
7820
Robert Lytton844aeeb2014-05-02 09:33:20 +00007821 if (const PointerType *PT = QT->getAs<PointerType>())
7822 return appendPointerType(Enc, PT, CGM, TSC);
7823
7824 if (const EnumType *ET = QT->getAs<EnumType>())
7825 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7826
7827 if (const RecordType *RT = QT->getAsStructureType())
7828 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7829
7830 if (const RecordType *RT = QT->getAsUnionType())
7831 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7832
7833 if (const FunctionType *FT = QT->getAs<FunctionType>())
7834 return appendFunctionType(Enc, FT, CGM, TSC);
7835
7836 return false;
7837}
7838
7839static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7840 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7841 if (!D)
7842 return false;
7843
7844 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7845 if (FD->getLanguageLinkage() != CLanguageLinkage)
7846 return false;
7847 return appendType(Enc, FD->getType(), CGM, TSC);
7848 }
7849
7850 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7851 if (VD->getLanguageLinkage() != CLanguageLinkage)
7852 return false;
7853 QualType QT = VD->getType().getCanonicalType();
7854 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7855 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007856 // The Qualifiers should be attached to the type rather than the array.
7857 // Thus we don't call appendQualifier() here.
7858 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007859 }
7860 return appendType(Enc, QT, CGM, TSC);
7861 }
7862 return false;
7863}
7864
7865
Robert Lytton0e076492013-08-13 09:43:10 +00007866//===----------------------------------------------------------------------===//
7867// Driver code
7868//===----------------------------------------------------------------------===//
7869
Rafael Espindola9f834732014-09-19 01:54:22 +00007870const llvm::Triple &CodeGenModule::getTriple() const {
7871 return getTarget().getTriple();
7872}
7873
7874bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00007875 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00007876}
7877
Chris Lattner2b037972010-07-29 02:01:43 +00007878const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007879 if (TheTargetCodeGenInfo)
7880 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007881
Reid Kleckner9305fd12016-04-13 23:37:17 +00007882 // Helper to set the unique_ptr while still keeping the return value.
7883 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
7884 this->TheTargetCodeGenInfo.reset(P);
7885 return *P;
7886 };
7887
John McCallc8e01702013-04-16 22:48:15 +00007888 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007889 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007890 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007891 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007892
Derek Schuff09338a22012-09-06 17:37:28 +00007893 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007894 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007895 case llvm::Triple::mips:
7896 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007897 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00007898 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
7899 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007900
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007901 case llvm::Triple::mips64:
7902 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007903 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007904
Tim Northover25e8a672014-05-24 12:51:25 +00007905 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007906 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007907 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007908 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007909 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007910
Reid Kleckner9305fd12016-04-13 23:37:17 +00007911 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007912 }
7913
Dan Gohmanc2853072015-09-03 22:51:53 +00007914 case llvm::Triple::wasm32:
7915 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007916 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00007917
Daniel Dunbard59655c2009-09-12 00:59:49 +00007918 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007919 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007920 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007921 case llvm::Triple::thumbeb: {
7922 if (Triple.getOS() == llvm::Triple::Win32) {
7923 return SetCGInfo(
7924 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007925 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007926
Reid Kleckner9305fd12016-04-13 23:37:17 +00007927 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
7928 StringRef ABIStr = getTarget().getABI();
7929 if (ABIStr == "apcs-gnu")
7930 Kind = ARMABIInfo::APCS;
7931 else if (ABIStr == "aapcs16")
7932 Kind = ARMABIInfo::AAPCS16_VFP;
7933 else if (CodeGenOpts.FloatABI == "hard" ||
7934 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00007935 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
7936 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00007937 Kind = ARMABIInfo::AAPCS_VFP;
7938
7939 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
7940 }
7941
John McCallea8d8bb2010-03-11 00:10:12 +00007942 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007943 return SetCGInfo(
7944 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007945 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007946 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007947 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007948 if (getTarget().getABI() == "elfv2")
7949 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007950 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007951
Reid Kleckner9305fd12016-04-13 23:37:17 +00007952 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007953 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00007954 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007955 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007956 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007957 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007958 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007959 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007960 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007961
Reid Kleckner9305fd12016-04-13 23:37:17 +00007962 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007963 }
John McCallea8d8bb2010-03-11 00:10:12 +00007964
Peter Collingbournec947aae2012-05-20 23:28:41 +00007965 case llvm::Triple::nvptx:
7966 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007967 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007968
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007969 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007970 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007971
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007972 case llvm::Triple::systemz: {
7973 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00007974 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007975 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007976
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007977 case llvm::Triple::tce:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007978 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007979
Eli Friedman33465822011-07-08 23:31:17 +00007980 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007981 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007982 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007983 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007984 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007985
John McCall1fe2a8c2013-06-18 02:46:29 +00007986 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00007987 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
7988 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
7989 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007990 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00007991 return SetCGInfo(new X86_32TargetCodeGenInfo(
7992 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
7993 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7994 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007995 }
Eli Friedman33465822011-07-08 23:31:17 +00007996 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007997
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007998 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007999 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008000 X86AVXABILevel AVXLevel =
8001 (ABI == "avx512"
8002 ? X86AVXABILevel::AVX512
8003 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008004
Chris Lattner04dc9572010-08-31 16:44:54 +00008005 switch (Triple.getOS()) {
8006 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008007 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008008 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008009 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008010 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008011 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008012 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008013 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008014 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008015 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008016 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008017 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008018 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008019 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008020 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008021 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008022 case llvm::Triple::sparc:
8023 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008024 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008025 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008026 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008027 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008028 case llvm::Triple::spir:
8029 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008030 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008031 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008032}