blob: bbc6b3b1ae28917b0220116176a206b4e178abd9 [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"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000023#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000027#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000028#include <algorithm> // std::sort
29
Anton Korobeynikov244360d2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall943fae92010-05-27 06:19:26 +000033static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
34 llvm::Value *Array,
35 llvm::Value *Value,
36 unsigned FirstIndex,
37 unsigned LastIndex) {
38 // Alternatively, we could emit this as a loop in the source.
39 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000040 llvm::Value *Cell =
41 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000042 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000043 }
44}
45
John McCalla1dee5302010-08-22 10:59:02 +000046static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000047 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000048 T->isMemberFunctionPointerType();
49}
50
John McCall7f416cc2015-09-08 08:05:57 +000051ABIArgInfo
52ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
53 llvm::Type *Padding) const {
54 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
55 ByRef, Realign, Padding);
56}
57
58ABIArgInfo
59ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
60 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
61 /*ByRef*/ false, Realign);
62}
63
Charles Davisc7d5c942015-09-17 20:55:33 +000064Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
65 QualType Ty) const {
66 return Address::invalid();
67}
68
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000069ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000070
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000071static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000072 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000073 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
74 if (!RD)
75 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000076 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000077}
78
79static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000080 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000081 const RecordType *RT = T->getAs<RecordType>();
82 if (!RT)
83 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000084 return getRecordArgABI(RT, CXXABI);
85}
86
Reid Klecknerb1be6832014-11-15 01:41:41 +000087/// Pass transparent unions as if they were the type of the first element. Sema
88/// should ensure that all elements of the union have the same "machine type".
89static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
90 if (const RecordType *UT = Ty->getAsUnionType()) {
91 const RecordDecl *UD = UT->getDecl();
92 if (UD->hasAttr<TransparentUnionAttr>()) {
93 assert(!UD->field_empty() && "sema created an empty transparent union");
94 return UD->field_begin()->getType();
95 }
96 }
97 return Ty;
98}
99
Mark Lacey3825e832013-10-06 01:33:34 +0000100CGCXXABI &ABIInfo::getCXXABI() const {
101 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000102}
103
Chris Lattner2b037972010-07-29 02:01:43 +0000104ASTContext &ABIInfo::getContext() const {
105 return CGT.getContext();
106}
107
108llvm::LLVMContext &ABIInfo::getVMContext() const {
109 return CGT.getLLVMContext();
110}
111
Micah Villmowdd31ca12012-10-08 16:25:52 +0000112const llvm::DataLayout &ABIInfo::getDataLayout() const {
113 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000114}
115
John McCallc8e01702013-04-16 22:48:15 +0000116const TargetInfo &ABIInfo::getTarget() const {
117 return CGT.getTarget();
118}
Chris Lattner2b037972010-07-29 02:01:43 +0000119
Reid Klecknere9f6a712014-10-31 17:10:41 +0000120bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
121 return false;
122}
123
124bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
125 uint64_t Members) const {
126 return false;
127}
128
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000129bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
130 return false;
131}
132
Yaron Kerencdae9412016-01-29 19:38:18 +0000133LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000134 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000135 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000136 switch (TheKind) {
137 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000138 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000139 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000140 Ty->print(OS);
141 else
142 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000143 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000144 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000145 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000146 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000147 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000148 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000149 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000150 case InAlloca:
151 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
152 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000153 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000154 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000155 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000156 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000157 break;
158 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000159 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000160 break;
161 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000162 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000163}
164
Petar Jovanovic402257b2015-12-04 00:26:47 +0000165// Dynamically round a pointer up to a multiple of the given alignment.
166static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
167 llvm::Value *Ptr,
168 CharUnits Align) {
169 llvm::Value *PtrAsInt = Ptr;
170 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
171 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
172 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
173 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
174 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
175 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
176 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
177 Ptr->getType(),
178 Ptr->getName() + ".aligned");
179 return PtrAsInt;
180}
181
John McCall7f416cc2015-09-08 08:05:57 +0000182/// Emit va_arg for a platform using the common void* representation,
183/// where arguments are simply emitted in an array of slots on the stack.
184///
185/// This version implements the core direct-value passing rules.
186///
187/// \param SlotSize - The size and alignment of a stack slot.
188/// Each argument will be allocated to a multiple of this number of
189/// slots, and all the slots will be aligned to this value.
190/// \param AllowHigherAlign - The slot alignment is not a cap;
191/// an argument type with an alignment greater than the slot size
192/// will be emitted on a higher-alignment address, potentially
193/// leaving one or more empty slots behind as padding. If this
194/// is false, the returned address might be less-aligned than
195/// DirectAlign.
196static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
197 Address VAListAddr,
198 llvm::Type *DirectTy,
199 CharUnits DirectSize,
200 CharUnits DirectAlign,
201 CharUnits SlotSize,
202 bool AllowHigherAlign) {
203 // Cast the element type to i8* if necessary. Some platforms define
204 // va_list as a struct containing an i8* instead of just an i8*.
205 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
206 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
207
208 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
209
210 // If the CC aligns values higher than the slot size, do so if needed.
211 Address Addr = Address::invalid();
212 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000213 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
214 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000215 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000216 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000217 }
218
219 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000220 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000221 llvm::Value *NextPtr =
222 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
223 "argp.next");
224 CGF.Builder.CreateStore(NextPtr, VAListAddr);
225
226 // If the argument is smaller than a slot, and this is a big-endian
227 // target, the argument will be right-adjusted in its slot.
228 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian()) {
229 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
230 }
231
232 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
233 return Addr;
234}
235
236/// Emit va_arg for a platform using the common void* representation,
237/// where arguments are simply emitted in an array of slots on the stack.
238///
239/// \param IsIndirect - Values of this type are passed indirectly.
240/// \param ValueInfo - The size and alignment of this type, generally
241/// computed with getContext().getTypeInfoInChars(ValueTy).
242/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
243/// Each argument will be allocated to a multiple of this number of
244/// slots, and all the slots will be aligned to this value.
245/// \param AllowHigherAlign - The slot alignment is not a cap;
246/// an argument type with an alignment greater than the slot size
247/// will be emitted on a higher-alignment address, potentially
248/// leaving one or more empty slots behind as padding.
249static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
250 QualType ValueTy, bool IsIndirect,
251 std::pair<CharUnits, CharUnits> ValueInfo,
252 CharUnits SlotSizeAndAlign,
253 bool AllowHigherAlign) {
254 // The size and alignment of the value that was passed directly.
255 CharUnits DirectSize, DirectAlign;
256 if (IsIndirect) {
257 DirectSize = CGF.getPointerSize();
258 DirectAlign = CGF.getPointerAlign();
259 } else {
260 DirectSize = ValueInfo.first;
261 DirectAlign = ValueInfo.second;
262 }
263
264 // Cast the address we've calculated to the right type.
265 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
266 if (IsIndirect)
267 DirectTy = DirectTy->getPointerTo(0);
268
269 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
270 DirectSize, DirectAlign,
271 SlotSizeAndAlign,
272 AllowHigherAlign);
273
274 if (IsIndirect) {
275 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
276 }
277
278 return Addr;
279
280}
281
282static Address emitMergePHI(CodeGenFunction &CGF,
283 Address Addr1, llvm::BasicBlock *Block1,
284 Address Addr2, llvm::BasicBlock *Block2,
285 const llvm::Twine &Name = "") {
286 assert(Addr1.getType() == Addr2.getType());
287 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
288 PHI->addIncoming(Addr1.getPointer(), Block1);
289 PHI->addIncoming(Addr2.getPointer(), Block2);
290 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
291 return Address(PHI, Align);
292}
293
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000294TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
295
John McCall3480ef22011-08-30 01:42:09 +0000296// If someone can figure out a general rule for this, that would be great.
297// It's probably just doomed to be platform-dependent, though.
298unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
299 // Verified for:
300 // x86-64 FreeBSD, Linux, Darwin
301 // x86-32 FreeBSD, Linux, Darwin
302 // PowerPC Linux, Darwin
303 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000304 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000305 return 32;
306}
307
John McCalla729c622012-02-17 03:33:10 +0000308bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
309 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000310 // The following conventions are known to require this to be false:
311 // x86_stdcall
312 // MIPS
313 // For everything else, we just prefer false unless we opt out.
314 return false;
315}
316
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000317void
318TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
319 llvm::SmallString<24> &Opt) const {
320 // This assumes the user is passing a library name like "rt" instead of a
321 // filename like "librt.a/so", and that they don't care whether it's static or
322 // dynamic.
323 Opt = "-l";
324 Opt += Lib;
325}
326
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000327static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000328
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000329/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000330/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000331static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
332 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000333 if (FD->isUnnamedBitfield())
334 return true;
335
336 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000337
Eli Friedman0b3f2012011-11-18 03:47:20 +0000338 // Constant arrays of empty records count as empty, strip them off.
339 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000340 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000341 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
342 if (AT->getSize() == 0)
343 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000344 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000345 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000346
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000347 const RecordType *RT = FT->getAs<RecordType>();
348 if (!RT)
349 return false;
350
351 // C++ record fields are never empty, at least in the Itanium ABI.
352 //
353 // FIXME: We should use a predicate for whether this behavior is true in the
354 // current ABI.
355 if (isa<CXXRecordDecl>(RT->getDecl()))
356 return false;
357
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000358 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000359}
360
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000361/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000362/// fields. Note that a structure with a flexible array member is not
363/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000364static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000365 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000366 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000367 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000368 const RecordDecl *RD = RT->getDecl();
369 if (RD->hasFlexibleArrayMember())
370 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000371
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000372 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000373 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000374 for (const auto &I : CXXRD->bases())
375 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000376 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000377
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000378 for (const auto *I : RD->fields())
379 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000380 return false;
381 return true;
382}
383
384/// isSingleElementStruct - Determine if a structure is a "single
385/// element struct", i.e. it has exactly one non-empty field or
386/// exactly one field which is itself a single element
387/// struct. Structures with flexible array members are never
388/// considered single element structs.
389///
390/// \return The field declaration for the single non-empty field, if
391/// it exists.
392static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000393 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000394 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000395 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000396
397 const RecordDecl *RD = RT->getDecl();
398 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000399 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000400
Craig Topper8a13c412014-05-21 05:09:00 +0000401 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000402
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000403 // If this is a C++ record, check the bases first.
404 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000405 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000406 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000407 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000408 continue;
409
410 // If we already found an element then this isn't a single-element struct.
411 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000412 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000413
414 // If this is non-empty and not a single element struct, the composite
415 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000416 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000417 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000418 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000419 }
420 }
421
422 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000423 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000424 QualType FT = FD->getType();
425
426 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000427 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000428 continue;
429
430 // If we already found an element then this isn't a single-element
431 // struct.
432 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000433 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000434
435 // Treat single element arrays as the element.
436 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
437 if (AT->getSize().getZExtValue() != 1)
438 break;
439 FT = AT->getElementType();
440 }
441
John McCalla1dee5302010-08-22 10:59:02 +0000442 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000443 Found = FT.getTypePtr();
444 } else {
445 Found = isSingleElementStruct(FT, Context);
446 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000447 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000448 }
449 }
450
Eli Friedmanee945342011-11-18 01:25:50 +0000451 // We don't consider a struct a single-element struct if it has
452 // padding beyond the element type.
453 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000454 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000455
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000456 return Found;
457}
458
459static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000460 // Treat complex types as the element type.
461 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
462 Ty = CTy->getElementType();
463
464 // Check for a type which we know has a simple scalar argument-passing
465 // convention without any padding. (We're specifically looking for 32
466 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000467 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000468 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000469 return false;
470
471 uint64_t Size = Context.getTypeSize(Ty);
472 return Size == 32 || Size == 64;
473}
474
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000475/// canExpandIndirectArgument - Test whether an argument type which is to be
476/// passed indirectly (on the stack) would have the equivalent layout if it was
477/// expanded into separate arguments. If so, we prefer to do the latter to avoid
478/// inhibiting optimizations.
479///
480// FIXME: This predicate is missing many cases, currently it just follows
481// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
482// should probably make this smarter, or better yet make the LLVM backend
483// capable of handling it.
484static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
485 // We can only expand structure types.
486 const RecordType *RT = Ty->getAs<RecordType>();
487 if (!RT)
488 return false;
489
490 // We can only expand (C) structures.
491 //
492 // FIXME: This needs to be generalized to handle classes as well.
493 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000494 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000495 return false;
496
Manman Ren27382782015-04-03 18:10:29 +0000497 // We try to expand CLike CXXRecordDecl.
498 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
499 if (!CXXRD->isCLike())
500 return false;
501 }
502
Eli Friedmane5c85622011-11-18 01:32:26 +0000503 uint64_t Size = 0;
504
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000505 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000506 if (!is32Or64BitBasicType(FD->getType(), Context))
507 return false;
508
509 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
510 // how to expand them yet, and the predicate for telling if a bitfield still
511 // counts as "basic" is more complicated than what we were doing previously.
512 if (FD->isBitField())
513 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000514
515 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000516 }
517
Eli Friedmane5c85622011-11-18 01:32:26 +0000518 // Make sure there are not any holes in the struct.
519 if (Size != Context.getTypeSize(Ty))
520 return false;
521
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000522 return true;
523}
524
525namespace {
526/// DefaultABIInfo - The default implementation for ABI specific
527/// details. This implementation provides information which results in
528/// self-consistent and sensible LLVM IR generation, but does not
529/// conform to any particular ABI.
530class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000531public:
532 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000533
Chris Lattner458b2aa2010-07-29 02:16:43 +0000534 ABIArgInfo classifyReturnType(QualType RetTy) const;
535 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000536
Craig Topper4f12f102014-03-12 06:41:41 +0000537 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000538 if (!getCXXABI().classifyReturnType(FI))
539 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000540 for (auto &I : FI.arguments())
541 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000542 }
543
John McCall7f416cc2015-09-08 08:05:57 +0000544 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
545 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000546};
547
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000548class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
549public:
Chris Lattner2b037972010-07-29 02:01:43 +0000550 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
551 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000552};
553
John McCall7f416cc2015-09-08 08:05:57 +0000554Address DefaultABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
555 QualType Ty) const {
556 return Address::invalid();
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000557}
558
Chris Lattner458b2aa2010-07-29 02:16:43 +0000559ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000560 Ty = useFirstFieldIfTransparentUnion(Ty);
561
562 if (isAggregateTypeForABI(Ty)) {
563 // Records with non-trivial destructors/copy-constructors should not be
564 // passed by value.
565 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000566 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000567
John McCall7f416cc2015-09-08 08:05:57 +0000568 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000569 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000570
Chris Lattner9723d6c2010-03-11 18:19:55 +0000571 // Treat an enum type as its underlying type.
572 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
573 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000574
Chris Lattner9723d6c2010-03-11 18:19:55 +0000575 return (Ty->isPromotableIntegerType() ?
576 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000577}
578
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000579ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
580 if (RetTy->isVoidType())
581 return ABIArgInfo::getIgnore();
582
583 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000584 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000585
586 // Treat an enum type as its underlying type.
587 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
588 RetTy = EnumTy->getDecl()->getIntegerType();
589
590 return (RetTy->isPromotableIntegerType() ?
591 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
592}
593
Derek Schuff09338a22012-09-06 17:37:28 +0000594//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000595// WebAssembly ABI Implementation
596//
597// This is a very simple ABI that relies a lot on DefaultABIInfo.
598//===----------------------------------------------------------------------===//
599
600class WebAssemblyABIInfo final : public DefaultABIInfo {
601public:
602 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
603 : DefaultABIInfo(CGT) {}
604
605private:
606 ABIArgInfo classifyReturnType(QualType RetTy) const;
607 ABIArgInfo classifyArgumentType(QualType Ty) const;
608
609 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
610 // non-virtual, but computeInfo is virtual, so we overload that.
611 void computeInfo(CGFunctionInfo &FI) const override {
612 if (!getCXXABI().classifyReturnType(FI))
613 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
614 for (auto &Arg : FI.arguments())
615 Arg.info = classifyArgumentType(Arg.type);
616 }
617};
618
619class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
620public:
621 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
622 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
623};
624
625/// \brief Classify argument of given type \p Ty.
626ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
627 Ty = useFirstFieldIfTransparentUnion(Ty);
628
629 if (isAggregateTypeForABI(Ty)) {
630 // Records with non-trivial destructors/copy-constructors should not be
631 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000632 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000633 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000634 // Ignore empty structs/unions.
635 if (isEmptyRecord(getContext(), Ty, true))
636 return ABIArgInfo::getIgnore();
637 // Lower single-element structs to just pass a regular value. TODO: We
638 // could do reasonable-size multiple-element structs too, using getExpand(),
639 // though watch out for things like bitfields.
640 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
641 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000642 }
643
644 // Otherwise just do the default thing.
645 return DefaultABIInfo::classifyArgumentType(Ty);
646}
647
648ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
649 if (isAggregateTypeForABI(RetTy)) {
650 // Records with non-trivial destructors/copy-constructors should not be
651 // returned by value.
652 if (!getRecordArgABI(RetTy, getCXXABI())) {
653 // Ignore empty structs/unions.
654 if (isEmptyRecord(getContext(), RetTy, true))
655 return ABIArgInfo::getIgnore();
656 // Lower single-element structs to just return a regular value. TODO: We
657 // could do reasonable-size multiple-element structs too, using
658 // ABIArgInfo::getDirect().
659 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
660 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
661 }
662 }
663
664 // Otherwise just do the default thing.
665 return DefaultABIInfo::classifyReturnType(RetTy);
666}
667
668//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000669// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000670//
671// This is a simplified version of the x86_32 ABI. Arguments and return values
672// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000673//===----------------------------------------------------------------------===//
674
675class PNaClABIInfo : public ABIInfo {
676 public:
677 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
678
679 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000680 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000681
Craig Topper4f12f102014-03-12 06:41:41 +0000682 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000683 Address EmitVAArg(CodeGenFunction &CGF,
684 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000685};
686
687class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
688 public:
689 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
690 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
691};
692
693void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000694 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000695 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
696
Reid Kleckner40ca9132014-05-13 22:05:45 +0000697 for (auto &I : FI.arguments())
698 I.info = classifyArgumentType(I.type);
699}
Derek Schuff09338a22012-09-06 17:37:28 +0000700
John McCall7f416cc2015-09-08 08:05:57 +0000701Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
702 QualType Ty) const {
703 return Address::invalid();
Derek Schuff09338a22012-09-06 17:37:28 +0000704}
705
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000706/// \brief Classify argument of given type \p Ty.
707ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000708 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000709 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000710 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
711 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000712 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
713 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000714 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000715 } else if (Ty->isFloatingType()) {
716 // Floating-point types don't go inreg.
717 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000718 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000719
720 return (Ty->isPromotableIntegerType() ?
721 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000722}
723
724ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
725 if (RetTy->isVoidType())
726 return ABIArgInfo::getIgnore();
727
Eli Benderskye20dad62013-04-04 22:49:35 +0000728 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000729 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000730 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000731
732 // Treat an enum type as its underlying type.
733 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
734 RetTy = EnumTy->getDecl()->getIntegerType();
735
736 return (RetTy->isPromotableIntegerType() ?
737 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
738}
739
Chad Rosier651c1832013-03-25 21:00:27 +0000740/// IsX86_MMXType - Return true if this is an MMX type.
741bool IsX86_MMXType(llvm::Type *IRType) {
742 // 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 +0000743 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
744 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
745 IRType->getScalarSizeInBits() != 64;
746}
747
Jay Foad7c57be32011-07-11 09:56:20 +0000748static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000749 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000750 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000751 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
752 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
753 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000754 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000755 }
756
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000757 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000758 }
759
760 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000761 return Ty;
762}
763
Reid Kleckner80944df2014-10-31 22:00:51 +0000764/// Returns true if this type can be passed in SSE registers with the
765/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
766static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
767 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
768 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
769 return true;
770 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
771 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
772 // registers specially.
773 unsigned VecSize = Context.getTypeSize(VT);
774 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
775 return true;
776 }
777 return false;
778}
779
780/// Returns true if this aggregate is small enough to be passed in SSE registers
781/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
782static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
783 return NumMembers <= 4;
784}
785
Chris Lattner0cf24192010-06-28 20:05:43 +0000786//===----------------------------------------------------------------------===//
787// X86-32 ABI Implementation
788//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000789
Reid Kleckner661f35b2014-01-18 01:12:41 +0000790/// \brief Similar to llvm::CCState, but for Clang.
791struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000792 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000793
794 unsigned CC;
795 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000796 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000797};
798
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000799/// X86_32ABIInfo - The X86-32 ABI information.
800class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000801 enum Class {
802 Integer,
803 Float
804 };
805
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000806 static const unsigned MinABIStackAlignInBytes = 4;
807
David Chisnallde3a0692009-08-17 23:08:21 +0000808 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000809 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000810 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000811 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000812 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000813 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000814
815 static bool isRegisterSize(unsigned Size) {
816 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
817 }
818
Reid Kleckner80944df2014-10-31 22:00:51 +0000819 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
820 // FIXME: Assumes vectorcall is in use.
821 return isX86VectorTypeForVectorCall(getContext(), Ty);
822 }
823
824 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
825 uint64_t NumMembers) const override {
826 // FIXME: Assumes vectorcall is in use.
827 return isX86VectorCallAggregateSmallEnough(NumMembers);
828 }
829
Reid Kleckner40ca9132014-05-13 22:05:45 +0000830 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000831
Daniel Dunbar557893d2010-04-21 19:10:51 +0000832 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
833 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000834 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
835
John McCall7f416cc2015-09-08 08:05:57 +0000836 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000837
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000838 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000839 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000840
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000841 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000842 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000843 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000844 /// \brief Updates the number of available free registers, returns
845 /// true if any registers were allocated.
846 bool updateFreeRegs(QualType Ty, CCState &State) const;
847
848 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
849 bool &NeedsPadding) const;
850 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000851
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000852 /// \brief Rewrite the function info so that all memory arguments use
853 /// inalloca.
854 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
855
856 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000857 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000858 QualType Type) const;
859
Rafael Espindola75419dc2012-07-23 23:30:29 +0000860public:
861
Craig Topper4f12f102014-03-12 06:41:41 +0000862 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000863 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
864 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000865
Michael Kupersteindc745202015-10-19 07:52:25 +0000866 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
867 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000868 unsigned NumRegisterParameters, bool SoftFloatABI)
Michael Kupersteindc745202015-10-19 07:52:25 +0000869 : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
870 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
871 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000872 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000873 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000874 DefaultNumRegisterParameters(NumRegisterParameters) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000875};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000876
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000877class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
878public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000879 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
880 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000881 unsigned NumRegisterParameters, bool SoftFloatABI)
882 : TargetCodeGenInfo(new X86_32ABIInfo(
883 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
884 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000885
John McCall1fe2a8c2013-06-18 02:46:29 +0000886 static bool isStructReturnInRegABI(
887 const llvm::Triple &Triple, const CodeGenOptions &Opts);
888
Eric Christopher162c91c2015-06-05 22:03:00 +0000889 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000890 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000891
Craig Topper4f12f102014-03-12 06:41:41 +0000892 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000893 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000894 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000895 return 4;
896 }
897
898 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000899 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000900
Jay Foad7c57be32011-07-11 09:56:20 +0000901 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000902 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000903 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000904 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
905 }
906
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000907 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
908 std::string &Constraints,
909 std::vector<llvm::Type *> &ResultRegTypes,
910 std::vector<llvm::Type *> &ResultTruncRegTypes,
911 std::vector<LValue> &ResultRegDests,
912 std::string &AsmString,
913 unsigned NumOutputs) const override;
914
Craig Topper4f12f102014-03-12 06:41:41 +0000915 llvm::Constant *
916 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000917 unsigned Sig = (0xeb << 0) | // jmp rel8
918 (0x06 << 8) | // .+0x08
919 ('F' << 16) |
920 ('T' << 24);
921 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
922 }
John McCall01391782016-02-05 21:37:38 +0000923
924 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
925 return "movl\t%ebp, %ebp"
926 "\t\t## marker for objc_retainAutoreleaseReturnValue";
927 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000928};
929
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000930}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000931
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000932/// Rewrite input constraint references after adding some output constraints.
933/// In the case where there is one output and one input and we add one output,
934/// we need to replace all operand references greater than or equal to 1:
935/// mov $0, $1
936/// mov eax, $1
937/// The result will be:
938/// mov $0, $2
939/// mov eax, $2
940static void rewriteInputConstraintReferences(unsigned FirstIn,
941 unsigned NumNewOuts,
942 std::string &AsmString) {
943 std::string Buf;
944 llvm::raw_string_ostream OS(Buf);
945 size_t Pos = 0;
946 while (Pos < AsmString.size()) {
947 size_t DollarStart = AsmString.find('$', Pos);
948 if (DollarStart == std::string::npos)
949 DollarStart = AsmString.size();
950 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
951 if (DollarEnd == std::string::npos)
952 DollarEnd = AsmString.size();
953 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
954 Pos = DollarEnd;
955 size_t NumDollars = DollarEnd - DollarStart;
956 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
957 // We have an operand reference.
958 size_t DigitStart = Pos;
959 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
960 if (DigitEnd == std::string::npos)
961 DigitEnd = AsmString.size();
962 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
963 unsigned OperandIndex;
964 if (!OperandStr.getAsInteger(10, OperandIndex)) {
965 if (OperandIndex >= FirstIn)
966 OperandIndex += NumNewOuts;
967 OS << OperandIndex;
968 } else {
969 OS << OperandStr;
970 }
971 Pos = DigitEnd;
972 }
973 }
974 AsmString = std::move(OS.str());
975}
976
977/// Add output constraints for EAX:EDX because they are return registers.
978void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
979 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
980 std::vector<llvm::Type *> &ResultRegTypes,
981 std::vector<llvm::Type *> &ResultTruncRegTypes,
982 std::vector<LValue> &ResultRegDests, std::string &AsmString,
983 unsigned NumOutputs) const {
984 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
985
986 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
987 // larger.
988 if (!Constraints.empty())
989 Constraints += ',';
990 if (RetWidth <= 32) {
991 Constraints += "={eax}";
992 ResultRegTypes.push_back(CGF.Int32Ty);
993 } else {
994 // Use the 'A' constraint for EAX:EDX.
995 Constraints += "=A";
996 ResultRegTypes.push_back(CGF.Int64Ty);
997 }
998
999 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1000 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1001 ResultTruncRegTypes.push_back(CoerceTy);
1002
1003 // Coerce the integer by bitcasting the return slot pointer.
1004 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1005 CoerceTy->getPointerTo()));
1006 ResultRegDests.push_back(ReturnSlot);
1007
1008 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1009}
1010
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001011/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001012/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001013bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1014 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001015 uint64_t Size = Context.getTypeSize(Ty);
1016
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001017 // For i386, type must be register sized.
1018 // For the MCU ABI, it only needs to be <= 8-byte
1019 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1020 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001021
1022 if (Ty->isVectorType()) {
1023 // 64- and 128- bit vectors inside structures are not returned in
1024 // registers.
1025 if (Size == 64 || Size == 128)
1026 return false;
1027
1028 return true;
1029 }
1030
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001031 // If this is a builtin, pointer, enum, complex type, member pointer, or
1032 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001033 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001034 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001035 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001036 return true;
1037
1038 // Arrays are treated like records.
1039 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001040 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001041
1042 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001043 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001044 if (!RT) return false;
1045
Anders Carlsson40446e82010-01-27 03:25:19 +00001046 // FIXME: Traverse bases here too.
1047
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001048 // Structure types are passed in register if all fields would be
1049 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001050 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001051 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001052 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001053 continue;
1054
1055 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001056 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001057 return false;
1058 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001059 return true;
1060}
1061
John McCall7f416cc2015-09-08 08:05:57 +00001062ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001063 // If the return value is indirect, then the hidden argument is consuming one
1064 // integer register.
1065 if (State.FreeRegs) {
1066 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001067 if (!IsMCUABI)
1068 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001069 }
John McCall7f416cc2015-09-08 08:05:57 +00001070 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001071}
1072
Eric Christopher7565e0d2015-05-29 23:09:49 +00001073ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1074 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001075 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001076 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001077
Reid Kleckner80944df2014-10-31 22:00:51 +00001078 const Type *Base = nullptr;
1079 uint64_t NumElts = 0;
1080 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1081 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1082 // The LLVM struct type for such an aggregate should lower properly.
1083 return ABIArgInfo::getDirect();
1084 }
1085
Chris Lattner458b2aa2010-07-29 02:16:43 +00001086 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001087 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001088 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001089 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001090
1091 // 128-bit vectors are a special case; they are returned in
1092 // registers and we need to make sure to pick a type the LLVM
1093 // backend will like.
1094 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001095 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001096 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001097
1098 // Always return in register if it fits in a general purpose
1099 // register, or if it is 64 bits and has a single element.
1100 if ((Size == 8 || Size == 16 || Size == 32) ||
1101 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001102 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001103 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001104
John McCall7f416cc2015-09-08 08:05:57 +00001105 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001106 }
1107
1108 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001109 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001110
John McCalla1dee5302010-08-22 10:59:02 +00001111 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001112 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001113 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001114 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001115 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001116 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001117
David Chisnallde3a0692009-08-17 23:08:21 +00001118 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001119 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001120 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001121
Denis Zobnin380b2242016-02-11 11:26:03 +00001122 // Ignore empty structs/unions.
1123 if (isEmptyRecord(getContext(), RetTy, true))
1124 return ABIArgInfo::getIgnore();
1125
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001126 // Small structures which are register sized are generally returned
1127 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001128 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001129 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001130
1131 // As a special-case, if the struct is a "single-element" struct, and
1132 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001133 // floating-point register. (MSVC does not apply this special case.)
1134 // We apply a similar transformation for pointer types to improve the
1135 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001136 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001137 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001138 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001139 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1140
1141 // FIXME: We should be able to narrow this integer in cases with dead
1142 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001143 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001144 }
1145
John McCall7f416cc2015-09-08 08:05:57 +00001146 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001147 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001148
Chris Lattner458b2aa2010-07-29 02:16:43 +00001149 // Treat an enum type as its underlying type.
1150 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1151 RetTy = EnumTy->getDecl()->getIntegerType();
1152
1153 return (RetTy->isPromotableIntegerType() ?
1154 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001155}
1156
Eli Friedman7919bea2012-06-05 19:40:46 +00001157static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1158 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1159}
1160
Daniel Dunbared23de32010-09-16 20:42:00 +00001161static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1162 const RecordType *RT = Ty->getAs<RecordType>();
1163 if (!RT)
1164 return 0;
1165 const RecordDecl *RD = RT->getDecl();
1166
1167 // If this is a C++ record, check the bases first.
1168 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001169 for (const auto &I : CXXRD->bases())
1170 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001171 return false;
1172
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001173 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001174 QualType FT = i->getType();
1175
Eli Friedman7919bea2012-06-05 19:40:46 +00001176 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001177 return true;
1178
1179 if (isRecordWithSSEVectorType(Context, FT))
1180 return true;
1181 }
1182
1183 return false;
1184}
1185
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001186unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1187 unsigned Align) const {
1188 // Otherwise, if the alignment is less than or equal to the minimum ABI
1189 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001190 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001191 return 0; // Use default alignment.
1192
1193 // On non-Darwin, the stack type alignment is always 4.
1194 if (!IsDarwinVectorABI) {
1195 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001196 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001197 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001198
Daniel Dunbared23de32010-09-16 20:42:00 +00001199 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001200 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1201 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001202 return 16;
1203
1204 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001205}
1206
Rafael Espindola703c47f2012-10-19 05:04:37 +00001207ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001208 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001209 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001210 if (State.FreeRegs) {
1211 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001212 if (!IsMCUABI)
1213 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001214 }
John McCall7f416cc2015-09-08 08:05:57 +00001215 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001216 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001217
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001218 // Compute the byval alignment.
1219 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1220 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1221 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001222 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001223
1224 // If the stack alignment is less than the type alignment, realign the
1225 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001226 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001227 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1228 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001229}
1230
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001231X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1232 const Type *T = isSingleElementStruct(Ty, getContext());
1233 if (!T)
1234 T = Ty.getTypePtr();
1235
1236 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1237 BuiltinType::Kind K = BT->getKind();
1238 if (K == BuiltinType::Float || K == BuiltinType::Double)
1239 return Float;
1240 }
1241 return Integer;
1242}
1243
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001244bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001245 if (!IsSoftFloatABI) {
1246 Class C = classify(Ty);
1247 if (C == Float)
1248 return false;
1249 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001250
Rafael Espindola077dd592012-10-24 01:58:58 +00001251 unsigned Size = getContext().getTypeSize(Ty);
1252 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001253
1254 if (SizeInRegs == 0)
1255 return false;
1256
Michael Kuperstein68901882015-10-25 08:18:20 +00001257 if (!IsMCUABI) {
1258 if (SizeInRegs > State.FreeRegs) {
1259 State.FreeRegs = 0;
1260 return false;
1261 }
1262 } else {
1263 // The MCU psABI allows passing parameters in-reg even if there are
1264 // earlier parameters that are passed on the stack. Also,
1265 // it does not allow passing >8-byte structs in-register,
1266 // even if there are 3 free registers available.
1267 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1268 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001269 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001270
Reid Kleckner661f35b2014-01-18 01:12:41 +00001271 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001272 return true;
1273}
1274
1275bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1276 bool &InReg,
1277 bool &NeedsPadding) const {
1278 NeedsPadding = false;
1279 InReg = !IsMCUABI;
1280
1281 if (!updateFreeRegs(Ty, State))
1282 return false;
1283
1284 if (IsMCUABI)
1285 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001286
Reid Kleckner80944df2014-10-31 22:00:51 +00001287 if (State.CC == llvm::CallingConv::X86_FastCall ||
1288 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001289 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001290 NeedsPadding = true;
1291
Rafael Espindola077dd592012-10-24 01:58:58 +00001292 return false;
1293 }
1294
Rafael Espindola703c47f2012-10-19 05:04:37 +00001295 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001296}
1297
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001298bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1299 if (!updateFreeRegs(Ty, State))
1300 return false;
1301
1302 if (IsMCUABI)
1303 return false;
1304
1305 if (State.CC == llvm::CallingConv::X86_FastCall ||
1306 State.CC == llvm::CallingConv::X86_VectorCall) {
1307 if (getContext().getTypeSize(Ty) > 32)
1308 return false;
1309
1310 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1311 Ty->isReferenceType());
1312 }
1313
1314 return true;
1315}
1316
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001317ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1318 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001319 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001320
Reid Klecknerb1be6832014-11-15 01:41:41 +00001321 Ty = useFirstFieldIfTransparentUnion(Ty);
1322
Reid Kleckner80944df2014-10-31 22:00:51 +00001323 // Check with the C++ ABI first.
1324 const RecordType *RT = Ty->getAs<RecordType>();
1325 if (RT) {
1326 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1327 if (RAA == CGCXXABI::RAA_Indirect) {
1328 return getIndirectResult(Ty, false, State);
1329 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1330 // The field index doesn't matter, we'll fix it up later.
1331 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1332 }
1333 }
1334
1335 // vectorcall adds the concept of a homogenous vector aggregate, similar
1336 // to other targets.
1337 const Type *Base = nullptr;
1338 uint64_t NumElts = 0;
1339 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1340 isHomogeneousAggregate(Ty, Base, NumElts)) {
1341 if (State.FreeSSERegs >= NumElts) {
1342 State.FreeSSERegs -= NumElts;
1343 if (Ty->isBuiltinType() || Ty->isVectorType())
1344 return ABIArgInfo::getDirect();
1345 return ABIArgInfo::getExpand();
1346 }
1347 return getIndirectResult(Ty, /*ByVal=*/false, State);
1348 }
1349
1350 if (isAggregateTypeForABI(Ty)) {
1351 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001352 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001353 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001354 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001355
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001356 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001357 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001358 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001359 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001360
Eli Friedman9f061a32011-11-18 00:28:11 +00001361 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001362 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001363 return ABIArgInfo::getIgnore();
1364
Rafael Espindolafad28de2012-10-24 01:59:00 +00001365 llvm::LLVMContext &LLVMContext = getVMContext();
1366 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001367 bool NeedsPadding, InReg;
1368 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001369 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001370 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001371 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001372 if (InReg)
1373 return ABIArgInfo::getDirectInReg(Result);
1374 else
1375 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001376 }
Craig Topper8a13c412014-05-21 05:09:00 +00001377 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001378
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001379 // Expand small (<= 128-bit) record types when we know that the stack layout
1380 // of those arguments will match the struct. This is important because the
1381 // LLVM backend isn't smart enough to remove byval, which inhibits many
1382 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001383 // Don't do this for the MCU if there are still free integer registers
1384 // (see X86_64 ABI for full explanation).
Chris Lattner458b2aa2010-07-29 02:16:43 +00001385 if (getContext().getTypeSize(Ty) <= 4*32 &&
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001386 canExpandIndirectArgument(Ty, getContext()) &&
1387 (!IsMCUABI || State.FreeRegs == 0))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001388 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001389 State.CC == llvm::CallingConv::X86_FastCall ||
1390 State.CC == llvm::CallingConv::X86_VectorCall,
1391 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001392
Reid Kleckner661f35b2014-01-18 01:12:41 +00001393 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001394 }
1395
Chris Lattnerd774ae92010-08-26 20:05:13 +00001396 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001397 // On Darwin, some vectors are passed in memory, we handle this by passing
1398 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001399 if (IsDarwinVectorABI) {
1400 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001401 if ((Size == 8 || Size == 16 || Size == 32) ||
1402 (Size == 64 && VT->getNumElements() == 1))
1403 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1404 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001405 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001406
Chad Rosier651c1832013-03-25 21:00:27 +00001407 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1408 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001409
Chris Lattnerd774ae92010-08-26 20:05:13 +00001410 return ABIArgInfo::getDirect();
1411 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001412
1413
Chris Lattner458b2aa2010-07-29 02:16:43 +00001414 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1415 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001416
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001417 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001418
1419 if (Ty->isPromotableIntegerType()) {
1420 if (InReg)
1421 return ABIArgInfo::getExtendInReg();
1422 return ABIArgInfo::getExtend();
1423 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001424
Rafael Espindola703c47f2012-10-19 05:04:37 +00001425 if (InReg)
1426 return ABIArgInfo::getDirectInReg();
1427 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001428}
1429
Rafael Espindolaa6472962012-07-24 00:01:07 +00001430void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001431 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001432 if (IsMCUABI)
1433 State.FreeRegs = 3;
1434 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001435 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001436 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1437 State.FreeRegs = 2;
1438 State.FreeSSERegs = 6;
1439 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001440 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001441 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001442 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001443
Reid Kleckner677539d2014-07-10 01:58:55 +00001444 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001445 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001446 } else if (FI.getReturnInfo().isIndirect()) {
1447 // The C++ ABI is not aware of register usage, so we have to check if the
1448 // return value was sret and put it in a register ourselves if appropriate.
1449 if (State.FreeRegs) {
1450 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001451 if (!IsMCUABI)
1452 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001453 }
1454 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001455
Peter Collingbournef7706832014-12-12 23:41:25 +00001456 // The chain argument effectively gives us another free register.
1457 if (FI.isChainCall())
1458 ++State.FreeRegs;
1459
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001460 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001461 for (auto &I : FI.arguments()) {
1462 I.info = classifyArgumentType(I.type, State);
1463 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001464 }
1465
1466 // If we needed to use inalloca for any argument, do a second pass and rewrite
1467 // all the memory arguments to use inalloca.
1468 if (UsedInAlloca)
1469 rewriteWithInAlloca(FI);
1470}
1471
1472void
1473X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001474 CharUnits &StackOffset, ABIArgInfo &Info,
1475 QualType Type) const {
1476 // Arguments are always 4-byte-aligned.
1477 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1478
1479 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001480 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1481 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001482 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001483
John McCall7f416cc2015-09-08 08:05:57 +00001484 // Insert padding bytes to respect alignment.
1485 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001486 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001487 if (StackOffset != FieldEnd) {
1488 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001489 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001490 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001491 FrameFields.push_back(Ty);
1492 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001493}
1494
Reid Kleckner852361d2014-07-26 00:12:26 +00001495static bool isArgInAlloca(const ABIArgInfo &Info) {
1496 // Leave ignored and inreg arguments alone.
1497 switch (Info.getKind()) {
1498 case ABIArgInfo::InAlloca:
1499 return true;
1500 case ABIArgInfo::Indirect:
1501 assert(Info.getIndirectByVal());
1502 return true;
1503 case ABIArgInfo::Ignore:
1504 return false;
1505 case ABIArgInfo::Direct:
1506 case ABIArgInfo::Extend:
1507 case ABIArgInfo::Expand:
1508 if (Info.getInReg())
1509 return false;
1510 return true;
1511 }
1512 llvm_unreachable("invalid enum");
1513}
1514
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001515void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1516 assert(IsWin32StructABI && "inalloca only supported on win32");
1517
1518 // Build a packed struct type for all of the arguments in memory.
1519 SmallVector<llvm::Type *, 6> FrameFields;
1520
John McCall7f416cc2015-09-08 08:05:57 +00001521 // The stack alignment is always 4.
1522 CharUnits StackAlign = CharUnits::fromQuantity(4);
1523
1524 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001525 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1526
1527 // Put 'this' into the struct before 'sret', if necessary.
1528 bool IsThisCall =
1529 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1530 ABIArgInfo &Ret = FI.getReturnInfo();
1531 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1532 isArgInAlloca(I->info)) {
1533 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1534 ++I;
1535 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001536
1537 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001538 if (Ret.isIndirect() && !Ret.getInReg()) {
1539 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1540 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001541 // On Windows, the hidden sret parameter is always returned in eax.
1542 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001543 }
1544
1545 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001546 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001547 ++I;
1548
1549 // Put arguments passed in memory into the struct.
1550 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001551 if (isArgInAlloca(I->info))
1552 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001553 }
1554
1555 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001556 /*isPacked=*/true),
1557 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001558}
1559
John McCall7f416cc2015-09-08 08:05:57 +00001560Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1561 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001562
John McCall7f416cc2015-09-08 08:05:57 +00001563 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001564
John McCall7f416cc2015-09-08 08:05:57 +00001565 // x86-32 changes the alignment of certain arguments on the stack.
1566 //
1567 // Just messing with TypeInfo like this works because we never pass
1568 // anything indirectly.
1569 TypeInfo.second = CharUnits::fromQuantity(
1570 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001571
John McCall7f416cc2015-09-08 08:05:57 +00001572 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1573 TypeInfo, CharUnits::fromQuantity(4),
1574 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001575}
1576
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001577bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1578 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1579 assert(Triple.getArch() == llvm::Triple::x86);
1580
1581 switch (Opts.getStructReturnConvention()) {
1582 case CodeGenOptions::SRCK_Default:
1583 break;
1584 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1585 return false;
1586 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1587 return true;
1588 }
1589
Michael Kupersteind749f232015-10-27 07:46:22 +00001590 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001591 return true;
1592
1593 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001594 case llvm::Triple::DragonFly:
1595 case llvm::Triple::FreeBSD:
1596 case llvm::Triple::OpenBSD:
1597 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001598 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001599 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001600 default:
1601 return false;
1602 }
1603}
1604
Eric Christopher162c91c2015-06-05 22:03:00 +00001605void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001606 llvm::GlobalValue *GV,
1607 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001608 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001609 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1610 // Get the LLVM function.
1611 llvm::Function *Fn = cast<llvm::Function>(GV);
1612
1613 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001614 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001615 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001616 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1617 llvm::AttributeSet::get(CGM.getLLVMContext(),
1618 llvm::AttributeSet::FunctionIndex,
1619 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001620 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001621 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1622 llvm::Function *Fn = cast<llvm::Function>(GV);
1623 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1624 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001625 }
1626}
1627
John McCallbeec5a02010-03-06 00:35:14 +00001628bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1629 CodeGen::CodeGenFunction &CGF,
1630 llvm::Value *Address) const {
1631 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001632
Chris Lattnerece04092012-02-07 00:39:47 +00001633 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001634
John McCallbeec5a02010-03-06 00:35:14 +00001635 // 0-7 are the eight integer registers; the order is different
1636 // on Darwin (for EH), but the range is the same.
1637 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001638 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001639
John McCallc8e01702013-04-16 22:48:15 +00001640 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001641 // 12-16 are st(0..4). Not sure why we stop at 4.
1642 // These have size 16, which is sizeof(long double) on
1643 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001644 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001645 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001646
John McCallbeec5a02010-03-06 00:35:14 +00001647 } else {
1648 // 9 is %eflags, which doesn't get a size on Darwin for some
1649 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001650 Builder.CreateAlignedStore(
1651 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1652 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001653
1654 // 11-16 are st(0..5). Not sure why we stop at 5.
1655 // These have size 12, which is sizeof(long double) on
1656 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001657 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001658 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1659 }
John McCallbeec5a02010-03-06 00:35:14 +00001660
1661 return false;
1662}
1663
Chris Lattner0cf24192010-06-28 20:05:43 +00001664//===----------------------------------------------------------------------===//
1665// X86-64 ABI Implementation
1666//===----------------------------------------------------------------------===//
1667
1668
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001669namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001670/// The AVX ABI level for X86 targets.
1671enum class X86AVXABILevel {
1672 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001673 AVX,
1674 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001675};
1676
1677/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1678static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1679 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001680 case X86AVXABILevel::AVX512:
1681 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001682 case X86AVXABILevel::AVX:
1683 return 256;
1684 case X86AVXABILevel::None:
1685 return 128;
1686 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001687 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001688}
1689
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001690/// X86_64ABIInfo - The X86_64 ABI information.
1691class X86_64ABIInfo : public ABIInfo {
1692 enum Class {
1693 Integer = 0,
1694 SSE,
1695 SSEUp,
1696 X87,
1697 X87Up,
1698 ComplexX87,
1699 NoClass,
1700 Memory
1701 };
1702
1703 /// merge - Implement the X86_64 ABI merging algorithm.
1704 ///
1705 /// Merge an accumulating classification \arg Accum with a field
1706 /// classification \arg Field.
1707 ///
1708 /// \param Accum - The accumulating classification. This should
1709 /// always be either NoClass or the result of a previous merge
1710 /// call. In addition, this should never be Memory (the caller
1711 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001712 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001713
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001714 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1715 ///
1716 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1717 /// final MEMORY or SSE classes when necessary.
1718 ///
1719 /// \param AggregateSize - The size of the current aggregate in
1720 /// the classification process.
1721 ///
1722 /// \param Lo - The classification for the parts of the type
1723 /// residing in the low word of the containing object.
1724 ///
1725 /// \param Hi - The classification for the parts of the type
1726 /// residing in the higher words of the containing object.
1727 ///
1728 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1729
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001730 /// classify - Determine the x86_64 register classes in which the
1731 /// given type T should be passed.
1732 ///
1733 /// \param Lo - The classification for the parts of the type
1734 /// residing in the low word of the containing object.
1735 ///
1736 /// \param Hi - The classification for the parts of the type
1737 /// residing in the high word of the containing object.
1738 ///
1739 /// \param OffsetBase - The bit offset of this type in the
1740 /// containing object. Some parameters are classified different
1741 /// depending on whether they straddle an eightbyte boundary.
1742 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001743 /// \param isNamedArg - Whether the argument in question is a "named"
1744 /// argument, as used in AMD64-ABI 3.5.7.
1745 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001746 /// If a word is unused its result will be NoClass; if a type should
1747 /// be passed in Memory then at least the classification of \arg Lo
1748 /// will be Memory.
1749 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001750 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001751 ///
1752 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1753 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001754 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1755 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001756
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001757 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001758 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1759 unsigned IROffset, QualType SourceTy,
1760 unsigned SourceOffset) const;
1761 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1762 unsigned IROffset, QualType SourceTy,
1763 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001764
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001765 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001766 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001767 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001768
1769 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001770 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001771 ///
1772 /// \param freeIntRegs - The number of free integer registers remaining
1773 /// available.
1774 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001775
Chris Lattner458b2aa2010-07-29 02:16:43 +00001776 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001777
Bill Wendling5cd41c42010-10-18 03:41:31 +00001778 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001779 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001780 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001781 unsigned &neededSSE,
1782 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001783
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001784 bool IsIllegalVectorType(QualType Ty) const;
1785
John McCalle0fda732011-04-21 01:20:55 +00001786 /// The 0.98 ABI revision clarified a lot of ambiguities,
1787 /// unfortunately in ways that were not always consistent with
1788 /// certain previous compilers. In particular, platforms which
1789 /// required strict binary compatibility with older versions of GCC
1790 /// may need to exempt themselves.
1791 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001792 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001793 }
1794
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001795 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001796 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1797 // 64-bit hardware.
1798 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001799
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001800public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001801 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1802 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001803 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001804 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001805
John McCalla729c622012-02-17 03:33:10 +00001806 bool isPassedUsingAVXType(QualType type) const {
1807 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001808 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001809 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1810 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001811 if (info.isDirect()) {
1812 llvm::Type *ty = info.getCoerceToType();
1813 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1814 return (vectorTy->getBitWidth() > 128);
1815 }
1816 return false;
1817 }
1818
Craig Topper4f12f102014-03-12 06:41:41 +00001819 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001820
John McCall7f416cc2015-09-08 08:05:57 +00001821 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1822 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001823 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1824 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001825
1826 bool has64BitPointers() const {
1827 return Has64BitPointers;
1828 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001829};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001830
Chris Lattner04dc9572010-08-31 16:44:54 +00001831/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001832class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001833public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001834 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1835 : ABIInfo(CGT),
1836 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001837
Craig Topper4f12f102014-03-12 06:41:41 +00001838 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001839
John McCall7f416cc2015-09-08 08:05:57 +00001840 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1841 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001842
1843 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1844 // FIXME: Assumes vectorcall is in use.
1845 return isX86VectorTypeForVectorCall(getContext(), Ty);
1846 }
1847
1848 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1849 uint64_t NumMembers) const override {
1850 // FIXME: Assumes vectorcall is in use.
1851 return isX86VectorCallAggregateSmallEnough(NumMembers);
1852 }
Reid Kleckner11a17192015-10-28 22:29:52 +00001853
1854private:
1855 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1856 bool IsReturnType) const;
1857
1858 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00001859};
1860
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001861class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1862public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001863 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001864 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001865
John McCalla729c622012-02-17 03:33:10 +00001866 const X86_64ABIInfo &getABIInfo() const {
1867 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1868 }
1869
Craig Topper4f12f102014-03-12 06:41:41 +00001870 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001871 return 7;
1872 }
1873
1874 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001875 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001876 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001877
John McCall943fae92010-05-27 06:19:26 +00001878 // 0-15 are the 16 integer registers.
1879 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001880 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001881 return false;
1882 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001883
Jay Foad7c57be32011-07-11 09:56:20 +00001884 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001885 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001886 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001887 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1888 }
1889
John McCalla729c622012-02-17 03:33:10 +00001890 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001891 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001892 // The default CC on x86-64 sets %al to the number of SSA
1893 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001894 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001895 // that when AVX types are involved: the ABI explicitly states it is
1896 // undefined, and it doesn't work in practice because of how the ABI
1897 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001898 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001899 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001900 for (CallArgList::const_iterator
1901 it = args.begin(), ie = args.end(); it != ie; ++it) {
1902 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1903 HasAVXType = true;
1904 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001905 }
1906 }
John McCalla729c622012-02-17 03:33:10 +00001907
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001908 if (!HasAVXType)
1909 return true;
1910 }
John McCallcbc038a2011-09-21 08:08:30 +00001911
John McCalla729c622012-02-17 03:33:10 +00001912 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001913 }
1914
Craig Topper4f12f102014-03-12 06:41:41 +00001915 llvm::Constant *
1916 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001917 unsigned Sig;
1918 if (getABIInfo().has64BitPointers())
1919 Sig = (0xeb << 0) | // jmp rel8
1920 (0x0a << 8) | // .+0x0c
1921 ('F' << 16) |
1922 ('T' << 24);
1923 else
1924 Sig = (0xeb << 0) | // jmp rel8
1925 (0x06 << 8) | // .+0x08
1926 ('F' << 16) |
1927 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001928 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1929 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001930
1931 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1932 CodeGen::CodeGenModule &CGM) const override {
1933 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1934 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1935 llvm::Function *Fn = cast<llvm::Function>(GV);
1936 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1937 }
1938 }
1939 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001940};
1941
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001942class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1943public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001944 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1945 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001946
1947 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001948 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001949 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00001950 // If the argument contains a space, enclose it in quotes.
1951 if (Lib.find(" ") != StringRef::npos)
1952 Opt += "\"" + Lib.str() + "\"";
1953 else
1954 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001955 }
1956};
1957
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001958static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001959 // If the argument does not end in .lib, automatically add the suffix.
1960 // If the argument contains a space, enclose it in quotes.
1961 // This matches the behavior of MSVC.
1962 bool Quote = (Lib.find(" ") != StringRef::npos);
1963 std::string ArgStr = Quote ? "\"" : "";
1964 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001965 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001966 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001967 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001968 return ArgStr;
1969}
1970
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001971class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1972public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001973 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00001974 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
1975 unsigned NumRegisterParameters)
1976 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001977 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001978
Eric Christopher162c91c2015-06-05 22:03:00 +00001979 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001980 CodeGen::CodeGenModule &CGM) const override;
1981
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001982 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001983 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001984 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001985 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001986 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001987
1988 void getDetectMismatchOption(llvm::StringRef Name,
1989 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001990 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001991 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001992 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001993};
1994
Hans Wennborg77dc2362015-01-20 19:45:50 +00001995static void addStackProbeSizeTargetAttribute(const Decl *D,
1996 llvm::GlobalValue *GV,
1997 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001998 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00001999 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2000 llvm::Function *Fn = cast<llvm::Function>(GV);
2001
Eric Christopher7565e0d2015-05-29 23:09:49 +00002002 Fn->addFnAttr("stack-probe-size",
2003 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002004 }
2005 }
2006}
2007
Eric Christopher162c91c2015-06-05 22:03:00 +00002008void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002009 llvm::GlobalValue *GV,
2010 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002011 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002012
2013 addStackProbeSizeTargetAttribute(D, GV, CGM);
2014}
2015
Chris Lattner04dc9572010-08-31 16:44:54 +00002016class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2017public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002018 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2019 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002020 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002021
Eric Christopher162c91c2015-06-05 22:03:00 +00002022 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002023 CodeGen::CodeGenModule &CGM) const override;
2024
Craig Topper4f12f102014-03-12 06:41:41 +00002025 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002026 return 7;
2027 }
2028
2029 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002030 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002031 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002032
Chris Lattner04dc9572010-08-31 16:44:54 +00002033 // 0-15 are the 16 integer registers.
2034 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002035 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002036 return false;
2037 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002038
2039 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002040 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002041 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002042 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002043 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002044
2045 void getDetectMismatchOption(llvm::StringRef Name,
2046 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002047 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002048 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002049 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002050};
2051
Eric Christopher162c91c2015-06-05 22:03:00 +00002052void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002053 llvm::GlobalValue *GV,
2054 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002055 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002056
Alexey Bataevd51e9932016-01-15 04:06:31 +00002057 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2058 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2059 llvm::Function *Fn = cast<llvm::Function>(GV);
2060 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2061 }
2062 }
2063
Hans Wennborg77dc2362015-01-20 19:45:50 +00002064 addStackProbeSizeTargetAttribute(D, GV, CGM);
2065}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002066}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002067
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002068void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2069 Class &Hi) const {
2070 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2071 //
2072 // (a) If one of the classes is Memory, the whole argument is passed in
2073 // memory.
2074 //
2075 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2076 // memory.
2077 //
2078 // (c) If the size of the aggregate exceeds two eightbytes and the first
2079 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2080 // argument is passed in memory. NOTE: This is necessary to keep the
2081 // ABI working for processors that don't support the __m256 type.
2082 //
2083 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2084 //
2085 // Some of these are enforced by the merging logic. Others can arise
2086 // only with unions; for example:
2087 // union { _Complex double; unsigned; }
2088 //
2089 // Note that clauses (b) and (c) were added in 0.98.
2090 //
2091 if (Hi == Memory)
2092 Lo = Memory;
2093 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2094 Lo = Memory;
2095 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2096 Lo = Memory;
2097 if (Hi == SSEUp && Lo != SSE)
2098 Hi = SSE;
2099}
2100
Chris Lattnerd776fb12010-06-28 21:43:59 +00002101X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002102 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2103 // classified recursively so that always two fields are
2104 // considered. The resulting class is calculated according to
2105 // the classes of the fields in the eightbyte:
2106 //
2107 // (a) If both classes are equal, this is the resulting class.
2108 //
2109 // (b) If one of the classes is NO_CLASS, the resulting class is
2110 // the other class.
2111 //
2112 // (c) If one of the classes is MEMORY, the result is the MEMORY
2113 // class.
2114 //
2115 // (d) If one of the classes is INTEGER, the result is the
2116 // INTEGER.
2117 //
2118 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2119 // MEMORY is used as class.
2120 //
2121 // (f) Otherwise class SSE is used.
2122
2123 // Accum should never be memory (we should have returned) or
2124 // ComplexX87 (because this cannot be passed in a structure).
2125 assert((Accum != Memory && Accum != ComplexX87) &&
2126 "Invalid accumulated classification during merge.");
2127 if (Accum == Field || Field == NoClass)
2128 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002129 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002130 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002131 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002132 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002133 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002134 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002135 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2136 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002137 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002138 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002139}
2140
Chris Lattner5c740f12010-06-30 19:14:05 +00002141void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002142 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002143 // FIXME: This code can be simplified by introducing a simple value class for
2144 // Class pairs with appropriate constructor methods for the various
2145 // situations.
2146
2147 // FIXME: Some of the split computations are wrong; unaligned vectors
2148 // shouldn't be passed in registers for example, so there is no chance they
2149 // can straddle an eightbyte. Verify & simplify.
2150
2151 Lo = Hi = NoClass;
2152
2153 Class &Current = OffsetBase < 64 ? Lo : Hi;
2154 Current = Memory;
2155
John McCall9dd450b2009-09-21 23:43:11 +00002156 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002157 BuiltinType::Kind k = BT->getKind();
2158
2159 if (k == BuiltinType::Void) {
2160 Current = NoClass;
2161 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2162 Lo = Integer;
2163 Hi = Integer;
2164 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2165 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002166 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002167 Current = SSE;
2168 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002169 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2170 if (LDF == &llvm::APFloat::IEEEquad) {
2171 Lo = SSE;
2172 Hi = SSEUp;
2173 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2174 Lo = X87;
2175 Hi = X87Up;
2176 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2177 Current = SSE;
2178 } else
2179 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002180 }
2181 // FIXME: _Decimal32 and _Decimal64 are SSE.
2182 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002183 return;
2184 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002185
Chris Lattnerd776fb12010-06-28 21:43:59 +00002186 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002187 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002188 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002189 return;
2190 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002191
Chris Lattnerd776fb12010-06-28 21:43:59 +00002192 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002193 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002194 return;
2195 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002196
Chris Lattnerd776fb12010-06-28 21:43:59 +00002197 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002198 if (Ty->isMemberFunctionPointerType()) {
2199 if (Has64BitPointers) {
2200 // If Has64BitPointers, this is an {i64, i64}, so classify both
2201 // Lo and Hi now.
2202 Lo = Hi = Integer;
2203 } else {
2204 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2205 // straddles an eightbyte boundary, Hi should be classified as well.
2206 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2207 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2208 if (EB_FuncPtr != EB_ThisAdj) {
2209 Lo = Hi = Integer;
2210 } else {
2211 Current = Integer;
2212 }
2213 }
2214 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002215 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002216 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002217 return;
2218 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002219
Chris Lattnerd776fb12010-06-28 21:43:59 +00002220 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002221 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002222 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2223 // gcc passes the following as integer:
2224 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2225 // 2 bytes - <2 x char>, <1 x short>
2226 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002227 Current = Integer;
2228
2229 // If this type crosses an eightbyte boundary, it should be
2230 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002231 uint64_t EB_Lo = (OffsetBase) / 64;
2232 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2233 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002234 Hi = Lo;
2235 } else if (Size == 64) {
2236 // gcc passes <1 x double> in memory. :(
2237 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
2238 return;
2239
2240 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00002241 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00002242 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2243 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
2244 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002245 Current = Integer;
2246 else
2247 Current = SSE;
2248
2249 // If this type crosses an eightbyte boundary, it should be
2250 // split.
2251 if (OffsetBase && OffsetBase != 64)
2252 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002253 } else if (Size == 128 ||
2254 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002255 // Arguments of 256-bits are split into four eightbyte chunks. The
2256 // least significant one belongs to class SSE and all the others to class
2257 // SSEUP. The original Lo and Hi design considers that types can't be
2258 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2259 // This design isn't correct for 256-bits, but since there're no cases
2260 // where the upper parts would need to be inspected, avoid adding
2261 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002262 //
2263 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2264 // registers if they are "named", i.e. not part of the "..." of a
2265 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002266 //
2267 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2268 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002269 Lo = SSE;
2270 Hi = SSEUp;
2271 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002272 return;
2273 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002274
Chris Lattnerd776fb12010-06-28 21:43:59 +00002275 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002276 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002277
Chris Lattner2b037972010-07-29 02:01:43 +00002278 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002279 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002280 if (Size <= 64)
2281 Current = Integer;
2282 else if (Size <= 128)
2283 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002284 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002285 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002286 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002287 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002288 } else if (ET == getContext().LongDoubleTy) {
2289 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2290 if (LDF == &llvm::APFloat::IEEEquad)
2291 Current = Memory;
2292 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2293 Current = ComplexX87;
2294 else if (LDF == &llvm::APFloat::IEEEdouble)
2295 Lo = Hi = SSE;
2296 else
2297 llvm_unreachable("unexpected long double representation!");
2298 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002299
2300 // If this complex type crosses an eightbyte boundary then it
2301 // should be split.
2302 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002303 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002304 if (Hi == NoClass && EB_Real != EB_Imag)
2305 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002306
Chris Lattnerd776fb12010-06-28 21:43:59 +00002307 return;
2308 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002309
Chris Lattner2b037972010-07-29 02:01:43 +00002310 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002311 // Arrays are treated like structures.
2312
Chris Lattner2b037972010-07-29 02:01:43 +00002313 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002314
2315 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002316 // than four eightbytes, ..., it has class MEMORY.
2317 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002318 return;
2319
2320 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2321 // fields, it has class MEMORY.
2322 //
2323 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002324 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002325 return;
2326
2327 // Otherwise implement simplified merge. We could be smarter about
2328 // this, but it isn't worth it and would be harder to verify.
2329 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002330 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002331 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002332
2333 // The only case a 256-bit wide vector could be used is when the array
2334 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2335 // to work for sizes wider than 128, early check and fallback to memory.
2336 if (Size > 128 && EltSize != 256)
2337 return;
2338
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002339 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2340 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002341 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002342 Lo = merge(Lo, FieldLo);
2343 Hi = merge(Hi, FieldHi);
2344 if (Lo == Memory || Hi == Memory)
2345 break;
2346 }
2347
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002348 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002349 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002350 return;
2351 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002352
Chris Lattnerd776fb12010-06-28 21:43:59 +00002353 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002354 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002355
2356 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002357 // than four eightbytes, ..., it has class MEMORY.
2358 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002359 return;
2360
Anders Carlsson20759ad2009-09-16 15:53:40 +00002361 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2362 // copy constructor or a non-trivial destructor, it is passed by invisible
2363 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002364 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002365 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002366
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002367 const RecordDecl *RD = RT->getDecl();
2368
2369 // Assume variable sized types are passed in memory.
2370 if (RD->hasFlexibleArrayMember())
2371 return;
2372
Chris Lattner2b037972010-07-29 02:01:43 +00002373 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002374
2375 // Reset Lo class, this will be recomputed.
2376 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002377
2378 // If this is a C++ record, classify the bases first.
2379 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002380 for (const auto &I : CXXRD->bases()) {
2381 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002382 "Unexpected base class!");
2383 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002384 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002385
2386 // Classify this field.
2387 //
2388 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2389 // single eightbyte, each is classified separately. Each eightbyte gets
2390 // initialized to class NO_CLASS.
2391 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002392 uint64_t Offset =
2393 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002394 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002395 Lo = merge(Lo, FieldLo);
2396 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002397 if (Lo == Memory || Hi == Memory) {
2398 postMerge(Size, Lo, Hi);
2399 return;
2400 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002401 }
2402 }
2403
2404 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002405 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002406 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002407 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002408 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2409 bool BitField = i->isBitField();
2410
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002411 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2412 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002413 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002414 // The only case a 256-bit wide vector could be used is when the struct
2415 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2416 // to work for sizes wider than 128, early check and fallback to memory.
2417 //
2418 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2419 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002420 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002421 return;
2422 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002423 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002424 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002425 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002426 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002427 return;
2428 }
2429
2430 // Classify this field.
2431 //
2432 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2433 // exceeds a single eightbyte, each is classified
2434 // separately. Each eightbyte gets initialized to class
2435 // NO_CLASS.
2436 Class FieldLo, FieldHi;
2437
2438 // Bit-fields require special handling, they do not force the
2439 // structure to be passed in memory even if unaligned, and
2440 // therefore they can straddle an eightbyte.
2441 if (BitField) {
2442 // Ignore padding bit-fields.
2443 if (i->isUnnamedBitfield())
2444 continue;
2445
2446 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002447 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002448
2449 uint64_t EB_Lo = Offset / 64;
2450 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002451
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002452 if (EB_Lo) {
2453 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2454 FieldLo = NoClass;
2455 FieldHi = Integer;
2456 } else {
2457 FieldLo = Integer;
2458 FieldHi = EB_Hi ? Integer : NoClass;
2459 }
2460 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002461 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002462 Lo = merge(Lo, FieldLo);
2463 Hi = merge(Hi, FieldHi);
2464 if (Lo == Memory || Hi == Memory)
2465 break;
2466 }
2467
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002468 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002469 }
2470}
2471
Chris Lattner22a931e2010-06-29 06:01:59 +00002472ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002473 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2474 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002475 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002476 // Treat an enum type as its underlying type.
2477 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2478 Ty = EnumTy->getDecl()->getIntegerType();
2479
2480 return (Ty->isPromotableIntegerType() ?
2481 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2482 }
2483
John McCall7f416cc2015-09-08 08:05:57 +00002484 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002485}
2486
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002487bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2488 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2489 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002490 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002491 if (Size <= 64 || Size > LargestVector)
2492 return true;
2493 }
2494
2495 return false;
2496}
2497
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002498ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2499 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002500 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2501 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002502 //
2503 // This assumption is optimistic, as there could be free registers available
2504 // when we need to pass this argument in memory, and LLVM could try to pass
2505 // the argument in the free register. This does not seem to happen currently,
2506 // but this code would be much safer if we could mark the argument with
2507 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002508 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002509 // Treat an enum type as its underlying type.
2510 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2511 Ty = EnumTy->getDecl()->getIntegerType();
2512
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002513 return (Ty->isPromotableIntegerType() ?
2514 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002515 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002516
Mark Lacey3825e832013-10-06 01:33:34 +00002517 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002518 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002519
Chris Lattner44c2b902011-05-22 23:21:23 +00002520 // Compute the byval alignment. We specify the alignment of the byval in all
2521 // cases so that the mid-level optimizer knows the alignment of the byval.
2522 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002523
2524 // Attempt to avoid passing indirect results using byval when possible. This
2525 // is important for good codegen.
2526 //
2527 // We do this by coercing the value into a scalar type which the backend can
2528 // handle naturally (i.e., without using byval).
2529 //
2530 // For simplicity, we currently only do this when we have exhausted all of the
2531 // free integer registers. Doing this when there are free integer registers
2532 // would require more care, as we would have to ensure that the coerced value
2533 // did not claim the unused register. That would require either reording the
2534 // arguments to the function (so that any subsequent inreg values came first),
2535 // or only doing this optimization when there were no following arguments that
2536 // might be inreg.
2537 //
2538 // We currently expect it to be rare (particularly in well written code) for
2539 // arguments to be passed on the stack when there are still free integer
2540 // registers available (this would typically imply large structs being passed
2541 // by value), so this seems like a fair tradeoff for now.
2542 //
2543 // We can revisit this if the backend grows support for 'onstack' parameter
2544 // attributes. See PR12193.
2545 if (freeIntRegs == 0) {
2546 uint64_t Size = getContext().getTypeSize(Ty);
2547
2548 // If this type fits in an eightbyte, coerce it into the matching integral
2549 // type, which will end up on the stack (with alignment 8).
2550 if (Align == 8 && Size <= 64)
2551 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2552 Size));
2553 }
2554
John McCall7f416cc2015-09-08 08:05:57 +00002555 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002556}
2557
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002558/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2559/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002560llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002561 // Wrapper structs/arrays that only contain vectors are passed just like
2562 // vectors; strip them off if present.
2563 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2564 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002565
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002566 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002567 if (isa<llvm::VectorType>(IRType) ||
2568 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002569 return IRType;
2570
2571 // We couldn't find the preferred IR vector type for 'Ty'.
2572 uint64_t Size = getContext().getTypeSize(Ty);
2573 assert((Size == 128 || Size == 256) && "Invalid type found!");
2574
2575 // Return a LLVM IR vector type based on the size of 'Ty'.
2576 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2577 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002578}
2579
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002580/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2581/// is known to either be off the end of the specified type or being in
2582/// alignment padding. The user type specified is known to be at most 128 bits
2583/// in size, and have passed through X86_64ABIInfo::classify with a successful
2584/// classification that put one of the two halves in the INTEGER class.
2585///
2586/// It is conservatively correct to return false.
2587static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2588 unsigned EndBit, ASTContext &Context) {
2589 // If the bytes being queried are off the end of the type, there is no user
2590 // data hiding here. This handles analysis of builtins, vectors and other
2591 // types that don't contain interesting padding.
2592 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2593 if (TySize <= StartBit)
2594 return true;
2595
Chris Lattner98076a22010-07-29 07:43:55 +00002596 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2597 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2598 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2599
2600 // Check each element to see if the element overlaps with the queried range.
2601 for (unsigned i = 0; i != NumElts; ++i) {
2602 // If the element is after the span we care about, then we're done..
2603 unsigned EltOffset = i*EltSize;
2604 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002605
Chris Lattner98076a22010-07-29 07:43:55 +00002606 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2607 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2608 EndBit-EltOffset, Context))
2609 return false;
2610 }
2611 // If it overlaps no elements, then it is safe to process as padding.
2612 return true;
2613 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002614
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002615 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2616 const RecordDecl *RD = RT->getDecl();
2617 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002618
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002619 // If this is a C++ record, check the bases first.
2620 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002621 for (const auto &I : CXXRD->bases()) {
2622 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002623 "Unexpected base class!");
2624 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002625 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002626
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002627 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002628 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002629 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002630
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002631 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002632 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002633 EndBit-BaseOffset, Context))
2634 return false;
2635 }
2636 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002637
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002638 // Verify that no field has data that overlaps the region of interest. Yes
2639 // this could be sped up a lot by being smarter about queried fields,
2640 // however we're only looking at structs up to 16 bytes, so we don't care
2641 // much.
2642 unsigned idx = 0;
2643 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2644 i != e; ++i, ++idx) {
2645 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002646
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002647 // If we found a field after the region we care about, then we're done.
2648 if (FieldOffset >= EndBit) break;
2649
2650 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2651 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2652 Context))
2653 return false;
2654 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002655
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002656 // If nothing in this record overlapped the area of interest, then we're
2657 // clean.
2658 return true;
2659 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002660
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002661 return false;
2662}
2663
Chris Lattnere556a712010-07-29 18:39:32 +00002664/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2665/// float member at the specified offset. For example, {int,{float}} has a
2666/// float at offset 4. It is conservatively correct for this routine to return
2667/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002668static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002669 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002670 // Base case if we find a float.
2671 if (IROffset == 0 && IRType->isFloatTy())
2672 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002673
Chris Lattnere556a712010-07-29 18:39:32 +00002674 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002675 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002676 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2677 unsigned Elt = SL->getElementContainingOffset(IROffset);
2678 IROffset -= SL->getElementOffset(Elt);
2679 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2680 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002681
Chris Lattnere556a712010-07-29 18:39:32 +00002682 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002683 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2684 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002685 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2686 IROffset -= IROffset/EltSize*EltSize;
2687 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2688 }
2689
2690 return false;
2691}
2692
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002693
2694/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2695/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002696llvm::Type *X86_64ABIInfo::
2697GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002698 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002699 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002700 // pass as float if the last 4 bytes is just padding. This happens for
2701 // structs that contain 3 floats.
2702 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2703 SourceOffset*8+64, getContext()))
2704 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002705
Chris Lattnere556a712010-07-29 18:39:32 +00002706 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2707 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2708 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002709 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2710 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002711 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002712
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002713 return llvm::Type::getDoubleTy(getVMContext());
2714}
2715
2716
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002717/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2718/// an 8-byte GPR. This means that we either have a scalar or we are talking
2719/// about the high or low part of an up-to-16-byte struct. This routine picks
2720/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002721/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2722/// etc).
2723///
2724/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2725/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2726/// the 8-byte value references. PrefType may be null.
2727///
Alp Toker9907f082014-07-09 14:06:35 +00002728/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002729/// an offset into this that we're processing (which is always either 0 or 8).
2730///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002731llvm::Type *X86_64ABIInfo::
2732GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002733 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002734 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2735 // returning an 8-byte unit starting with it. See if we can safely use it.
2736 if (IROffset == 0) {
2737 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002738 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2739 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002740 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002741
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002742 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2743 // goodness in the source type is just tail padding. This is allowed to
2744 // kick in for struct {double,int} on the int, but not on
2745 // struct{double,int,int} because we wouldn't return the second int. We
2746 // have to do this analysis on the source type because we can't depend on
2747 // unions being lowered a specific way etc.
2748 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002749 IRType->isIntegerTy(32) ||
2750 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2751 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2752 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002753
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002754 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2755 SourceOffset*8+64, getContext()))
2756 return IRType;
2757 }
2758 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002759
Chris Lattner2192fe52011-07-18 04:24:23 +00002760 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002761 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002762 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002763 if (IROffset < SL->getSizeInBytes()) {
2764 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2765 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002766
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002767 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2768 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002769 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002770 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002771
Chris Lattner2192fe52011-07-18 04:24:23 +00002772 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002773 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002774 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002775 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002776 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2777 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002778 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002779
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002780 // Okay, we don't have any better idea of what to pass, so we pass this in an
2781 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002782 unsigned TySizeInBytes =
2783 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002784
Chris Lattner3f763422010-07-29 17:34:39 +00002785 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002786
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002787 // It is always safe to classify this as an integer type up to i64 that
2788 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002789 return llvm::IntegerType::get(getVMContext(),
2790 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002791}
2792
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002793
2794/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2795/// be used as elements of a two register pair to pass or return, return a
2796/// first class aggregate to represent them. For example, if the low part of
2797/// a by-value argument should be passed as i32* and the high part as float,
2798/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002799static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002800GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002801 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002802 // In order to correctly satisfy the ABI, we need to the high part to start
2803 // at offset 8. If the high and low parts we inferred are both 4-byte types
2804 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2805 // the second element at offset 8. Check for this:
2806 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2807 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002808 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002809 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002810
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002811 // To handle this, we have to increase the size of the low part so that the
2812 // second element will start at an 8 byte offset. We can't increase the size
2813 // of the second element because it might make us access off the end of the
2814 // struct.
2815 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002816 // There are usually two sorts of types the ABI generation code can produce
2817 // for the low part of a pair that aren't 8 bytes in size: float or
2818 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2819 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002820 // Promote these to a larger type.
2821 if (Lo->isFloatTy())
2822 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2823 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002824 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2825 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002826 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2827 }
2828 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002829
Reid Kleckneree7cf842014-12-01 22:02:27 +00002830 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002831
2832
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002833 // Verify that the second element is at an 8-byte offset.
2834 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2835 "Invalid x86-64 argument pair!");
2836 return Result;
2837}
2838
Chris Lattner31faff52010-07-28 23:06:14 +00002839ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002840classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002841 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2842 // classification algorithm.
2843 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002844 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002845
2846 // Check some invariants.
2847 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002848 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2849
Craig Topper8a13c412014-05-21 05:09:00 +00002850 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002851 switch (Lo) {
2852 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002853 if (Hi == NoClass)
2854 return ABIArgInfo::getIgnore();
2855 // If the low part is just padding, it takes no register, leave ResType
2856 // null.
2857 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2858 "Unknown missing lo part");
2859 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002860
2861 case SSEUp:
2862 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002863 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002864
2865 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2866 // hidden argument.
2867 case Memory:
2868 return getIndirectReturnResult(RetTy);
2869
2870 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2871 // available register of the sequence %rax, %rdx is used.
2872 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002873 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002874
Chris Lattner1f3a0632010-07-29 21:42:50 +00002875 // If we have a sign or zero extended integer, make sure to return Extend
2876 // so that the parameter gets the right LLVM IR attributes.
2877 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2878 // Treat an enum type as its underlying type.
2879 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2880 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002881
Chris Lattner1f3a0632010-07-29 21:42:50 +00002882 if (RetTy->isIntegralOrEnumerationType() &&
2883 RetTy->isPromotableIntegerType())
2884 return ABIArgInfo::getExtend();
2885 }
Chris Lattner31faff52010-07-28 23:06:14 +00002886 break;
2887
2888 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2889 // available SSE register of the sequence %xmm0, %xmm1 is used.
2890 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002891 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002892 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002893
2894 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2895 // returned on the X87 stack in %st0 as 80-bit x87 number.
2896 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002897 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002898 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002899
2900 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2901 // part of the value is returned in %st0 and the imaginary part in
2902 // %st1.
2903 case ComplexX87:
2904 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002905 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002906 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002907 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002908 break;
2909 }
2910
Craig Topper8a13c412014-05-21 05:09:00 +00002911 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002912 switch (Hi) {
2913 // Memory was handled previously and X87 should
2914 // never occur as a hi class.
2915 case Memory:
2916 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002917 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002918
2919 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002920 case NoClass:
2921 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002922
Chris Lattner52b3c132010-09-01 00:20:33 +00002923 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002924 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002925 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2926 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002927 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002928 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002929 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002930 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2931 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002932 break;
2933
2934 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002935 // is passed in the next available eightbyte chunk if the last used
2936 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002937 //
Chris Lattner57540c52011-04-15 05:22:18 +00002938 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002939 case SSEUp:
2940 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002941 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002942 break;
2943
2944 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2945 // returned together with the previous X87 value in %st0.
2946 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002947 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002948 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002949 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002950 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002951 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002952 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002953 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2954 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002955 }
Chris Lattner31faff52010-07-28 23:06:14 +00002956 break;
2957 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002958
Chris Lattner52b3c132010-09-01 00:20:33 +00002959 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002960 // known to pass in the high eightbyte of the result. We do this by forming a
2961 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002962 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002963 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002964
Chris Lattner1f3a0632010-07-29 21:42:50 +00002965 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002966}
2967
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002968ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002969 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2970 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002971 const
2972{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002973 Ty = useFirstFieldIfTransparentUnion(Ty);
2974
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002975 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002976 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002977
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002978 // Check some invariants.
2979 // FIXME: Enforce these by construction.
2980 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002981 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2982
2983 neededInt = 0;
2984 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002985 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002986 switch (Lo) {
2987 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002988 if (Hi == NoClass)
2989 return ABIArgInfo::getIgnore();
2990 // If the low part is just padding, it takes no register, leave ResType
2991 // null.
2992 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2993 "Unknown missing lo part");
2994 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002995
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002996 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2997 // on the stack.
2998 case Memory:
2999
3000 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3001 // COMPLEX_X87, it is passed in memory.
3002 case X87:
3003 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003004 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003005 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003006 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003007
3008 case SSEUp:
3009 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003010 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003011
3012 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3013 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3014 // and %r9 is used.
3015 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003016 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003017
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003018 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003019 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003020
3021 // If we have a sign or zero extended integer, make sure to return Extend
3022 // so that the parameter gets the right LLVM IR attributes.
3023 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3024 // Treat an enum type as its underlying type.
3025 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3026 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003027
Chris Lattner1f3a0632010-07-29 21:42:50 +00003028 if (Ty->isIntegralOrEnumerationType() &&
3029 Ty->isPromotableIntegerType())
3030 return ABIArgInfo::getExtend();
3031 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003032
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003033 break;
3034
3035 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3036 // available SSE register is used, the registers are taken in the
3037 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003038 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003039 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003040 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003041 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003042 break;
3043 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003044 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003045
Craig Topper8a13c412014-05-21 05:09:00 +00003046 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003047 switch (Hi) {
3048 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003049 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003050 // which is passed in memory.
3051 case Memory:
3052 case X87:
3053 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003054 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003055
3056 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003057
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003058 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003059 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003060 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003061 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003062
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003063 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3064 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003065 break;
3066
3067 // X87Up generally doesn't occur here (long double is passed in
3068 // memory), except in situations involving unions.
3069 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003070 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003071 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003072
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003073 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3074 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003075
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003076 ++neededSSE;
3077 break;
3078
3079 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3080 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003081 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003082 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003083 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003084 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003085 break;
3086 }
3087
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003088 // If a high part was specified, merge it together with the low part. It is
3089 // known to pass in the high eightbyte of the result. We do this by forming a
3090 // first class struct aggregate with the high and low part: {low, high}
3091 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003092 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003093
Chris Lattner1f3a0632010-07-29 21:42:50 +00003094 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003095}
3096
Chris Lattner22326a12010-07-29 02:31:05 +00003097void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003098
Reid Kleckner40ca9132014-05-13 22:05:45 +00003099 if (!getCXXABI().classifyReturnType(FI))
3100 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003101
3102 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003103 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003104
3105 // If the return value is indirect, then the hidden argument is consuming one
3106 // integer register.
3107 if (FI.getReturnInfo().isIndirect())
3108 --freeIntRegs;
3109
Peter Collingbournef7706832014-12-12 23:41:25 +00003110 // The chain argument effectively gives us another free register.
3111 if (FI.isChainCall())
3112 ++freeIntRegs;
3113
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003114 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003115 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3116 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003117 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003118 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003119 it != ie; ++it, ++ArgNo) {
3120 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003121
Bill Wendling9987c0e2010-10-18 23:51:38 +00003122 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003123 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003124 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003125
3126 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3127 // eightbyte of an argument, the whole argument is passed on the
3128 // stack. If registers have already been assigned for some
3129 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003130 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003131 freeIntRegs -= neededInt;
3132 freeSSERegs -= neededSSE;
3133 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003134 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003135 }
3136 }
3137}
3138
John McCall7f416cc2015-09-08 08:05:57 +00003139static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3140 Address VAListAddr, QualType Ty) {
3141 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3142 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003143 llvm::Value *overflow_arg_area =
3144 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3145
3146 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3147 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003148 // It isn't stated explicitly in the standard, but in practice we use
3149 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003150 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3151 if (Align > CharUnits::fromQuantity(8)) {
3152 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3153 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003154 }
3155
3156 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003157 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003158 llvm::Value *Res =
3159 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003160 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003161
3162 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3163 // l->overflow_arg_area + sizeof(type).
3164 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3165 // an 8 byte boundary.
3166
3167 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003168 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003169 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003170 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3171 "overflow_arg_area.next");
3172 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3173
3174 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003175 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003176}
3177
John McCall7f416cc2015-09-08 08:05:57 +00003178Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3179 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003180 // Assume that va_list type is correct; should be pointer to LLVM type:
3181 // struct {
3182 // i32 gp_offset;
3183 // i32 fp_offset;
3184 // i8* overflow_arg_area;
3185 // i8* reg_save_area;
3186 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003187 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003188
John McCall7f416cc2015-09-08 08:05:57 +00003189 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003190 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003191 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003192
3193 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3194 // in the registers. If not go to step 7.
3195 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003196 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003197
3198 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3199 // general purpose registers needed to pass type and num_fp to hold
3200 // the number of floating point registers needed.
3201
3202 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3203 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3204 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3205 //
3206 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3207 // register save space).
3208
Craig Topper8a13c412014-05-21 05:09:00 +00003209 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003210 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3211 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003212 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003213 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003214 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3215 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003216 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003217 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3218 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003219 }
3220
3221 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003222 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003223 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3224 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003225 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3226 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003227 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3228 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003229 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3230 }
3231
3232 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3233 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3234 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3235 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3236
3237 // Emit code to load the value if it was passed in registers.
3238
3239 CGF.EmitBlock(InRegBlock);
3240
3241 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3242 // an offset of l->gp_offset and/or l->fp_offset. This may require
3243 // copying to a temporary location in case the parameter is passed
3244 // in different register classes or requires an alignment greater
3245 // than 8 for general purpose registers and 16 for XMM registers.
3246 //
3247 // FIXME: This really results in shameful code when we end up needing to
3248 // collect arguments from different places; often what should result in a
3249 // simple assembling of a structure from scattered addresses has many more
3250 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003251 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003252 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3253 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3254 "reg_save_area");
3255
3256 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003257 if (neededInt && neededSSE) {
3258 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003259 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003260 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003261 Address Tmp = CGF.CreateMemTemp(Ty);
3262 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003263 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003264 llvm::Type *TyLo = ST->getElementType(0);
3265 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003266 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003267 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003268 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3269 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003270 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3271 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003272 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3273 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003274
John McCall7f416cc2015-09-08 08:05:57 +00003275 // Copy the first element.
3276 llvm::Value *V =
3277 CGF.Builder.CreateDefaultAlignedLoad(
3278 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3279 CGF.Builder.CreateStore(V,
3280 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3281
3282 // Copy the second element.
3283 V = CGF.Builder.CreateDefaultAlignedLoad(
3284 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3285 CharUnits Offset = CharUnits::fromQuantity(
3286 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3287 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3288
3289 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003290 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003291 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3292 CharUnits::fromQuantity(8));
3293 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003294
3295 // Copy to a temporary if necessary to ensure the appropriate alignment.
3296 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003297 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003298 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003299 CharUnits TyAlign = SizeAlign.second;
3300
3301 // Copy into a temporary if the type is more aligned than the
3302 // register save area.
3303 if (TyAlign.getQuantity() > 8) {
3304 Address Tmp = CGF.CreateMemTemp(Ty);
3305 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003306 RegAddr = Tmp;
3307 }
John McCall7f416cc2015-09-08 08:05:57 +00003308
Chris Lattner0cf24192010-06-28 20:05:43 +00003309 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003310 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3311 CharUnits::fromQuantity(16));
3312 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003313 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003314 assert(neededSSE == 2 && "Invalid number of needed registers!");
3315 // SSE registers are spaced 16 bytes apart in the register save
3316 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003317 // The ABI isn't explicit about this, but it seems reasonable
3318 // to assume that the slots are 16-byte aligned, since the stack is
3319 // naturally 16-byte aligned and the prologue is expected to store
3320 // all the SSE registers to the RSA.
3321 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3322 CharUnits::fromQuantity(16));
3323 Address RegAddrHi =
3324 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3325 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003326 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003327 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003328 llvm::Value *V;
3329 Address Tmp = CGF.CreateMemTemp(Ty);
3330 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3331 V = CGF.Builder.CreateLoad(
3332 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3333 CGF.Builder.CreateStore(V,
3334 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3335 V = CGF.Builder.CreateLoad(
3336 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3337 CGF.Builder.CreateStore(V,
3338 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3339
3340 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003341 }
3342
3343 // AMD64-ABI 3.5.7p5: Step 5. Set:
3344 // l->gp_offset = l->gp_offset + num_gp * 8
3345 // l->fp_offset = l->fp_offset + num_fp * 16.
3346 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003347 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003348 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3349 gp_offset_p);
3350 }
3351 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003352 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003353 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3354 fp_offset_p);
3355 }
3356 CGF.EmitBranch(ContBlock);
3357
3358 // Emit code to load the value if it was passed in memory.
3359
3360 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003361 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003362
3363 // Return the appropriate result.
3364
3365 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003366 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3367 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003368 return ResAddr;
3369}
3370
Charles Davisc7d5c942015-09-17 20:55:33 +00003371Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3372 QualType Ty) const {
3373 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3374 CGF.getContext().getTypeInfoInChars(Ty),
3375 CharUnits::fromQuantity(8),
3376 /*allowHigherAlign*/ false);
3377}
3378
Reid Kleckner80944df2014-10-31 22:00:51 +00003379ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3380 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003381
3382 if (Ty->isVoidType())
3383 return ABIArgInfo::getIgnore();
3384
3385 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3386 Ty = EnumTy->getDecl()->getIntegerType();
3387
Reid Kleckner80944df2014-10-31 22:00:51 +00003388 TypeInfo Info = getContext().getTypeInfo(Ty);
3389 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003390 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003391
Reid Kleckner9005f412014-05-02 00:51:20 +00003392 const RecordType *RT = Ty->getAs<RecordType>();
3393 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003394 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003395 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003396 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003397 }
3398
3399 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003400 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003401
Reid Kleckner9005f412014-05-02 00:51:20 +00003402 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003403
Reid Kleckner80944df2014-10-31 22:00:51 +00003404 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3405 // other targets.
3406 const Type *Base = nullptr;
3407 uint64_t NumElts = 0;
3408 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3409 if (FreeSSERegs >= NumElts) {
3410 FreeSSERegs -= NumElts;
3411 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3412 return ABIArgInfo::getDirect();
3413 return ABIArgInfo::getExpand();
3414 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003415 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003416 }
3417
3418
Reid Klecknerec87fec2014-05-02 01:17:12 +00003419 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003420 // If the member pointer is represented by an LLVM int or ptr, pass it
3421 // directly.
3422 llvm::Type *LLTy = CGT.ConvertType(Ty);
3423 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3424 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003425 }
3426
Michael Kuperstein4f818702015-02-24 09:35:58 +00003427 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003428 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3429 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003430 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003431 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003432
Reid Kleckner9005f412014-05-02 00:51:20 +00003433 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003434 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003435 }
3436
Julien Lerouge10dcff82014-08-27 00:36:55 +00003437 // Bool type is always extended to the ABI, other builtin types are not
3438 // extended.
3439 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3440 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003441 return ABIArgInfo::getExtend();
3442
Reid Kleckner11a17192015-10-28 22:29:52 +00003443 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3444 // passes them indirectly through memory.
3445 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3446 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3447 if (LDF == &llvm::APFloat::x87DoubleExtended)
3448 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3449 }
3450
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003451 return ABIArgInfo::getDirect();
3452}
3453
3454void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003455 bool IsVectorCall =
3456 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003457
Reid Kleckner80944df2014-10-31 22:00:51 +00003458 // We can use up to 4 SSE return registers with vectorcall.
3459 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3460 if (!getCXXABI().classifyReturnType(FI))
3461 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3462
3463 // We can use up to 6 SSE register parameters with vectorcall.
3464 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003465 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003466 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003467}
3468
John McCall7f416cc2015-09-08 08:05:57 +00003469Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3470 QualType Ty) const {
3471 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3472 CGF.getContext().getTypeInfoInChars(Ty),
3473 CharUnits::fromQuantity(8),
3474 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003475}
Chris Lattner0cf24192010-06-28 20:05:43 +00003476
John McCallea8d8bb2010-03-11 00:10:12 +00003477// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003478namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003479/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3480class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003481bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003482public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003483 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3484 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003485
John McCall7f416cc2015-09-08 08:05:57 +00003486 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3487 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003488};
3489
3490class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3491public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003492 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3493 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003494
Craig Topper4f12f102014-03-12 06:41:41 +00003495 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003496 // This is recovered from gcc output.
3497 return 1; // r1 is the dedicated stack pointer
3498 }
3499
3500 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003501 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003502};
3503
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003504}
John McCallea8d8bb2010-03-11 00:10:12 +00003505
John McCall7f416cc2015-09-08 08:05:57 +00003506Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3507 QualType Ty) const {
Roman Divacky8a12d842014-11-03 18:32:54 +00003508 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3509 // TODO: Implement this. For now ignore.
3510 (void)CTy;
John McCall7f416cc2015-09-08 08:05:57 +00003511 return Address::invalid();
Roman Divacky8a12d842014-11-03 18:32:54 +00003512 }
3513
John McCall7f416cc2015-09-08 08:05:57 +00003514 // struct __va_list_tag {
3515 // unsigned char gpr;
3516 // unsigned char fpr;
3517 // unsigned short reserved;
3518 // void *overflow_arg_area;
3519 // void *reg_save_area;
3520 // };
3521
Roman Divacky8a12d842014-11-03 18:32:54 +00003522 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003523 bool isInt =
3524 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003525 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003526
3527 // All aggregates are passed indirectly? That doesn't seem consistent
3528 // with the argument-lowering code.
3529 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003530
3531 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003532
3533 // The calling convention either uses 1-2 GPRs or 1 FPR.
3534 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003535 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003536 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3537 } else {
3538 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003539 }
John McCall7f416cc2015-09-08 08:05:57 +00003540
3541 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3542
3543 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003544 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003545 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3546 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3547 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003548
Eric Christopher7565e0d2015-05-29 23:09:49 +00003549 llvm::Value *CC =
John McCall7f416cc2015-09-08 08:05:57 +00003550 Builder.CreateICmpULT(NumRegs, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003551
3552 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3553 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3554 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3555
3556 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3557
John McCall7f416cc2015-09-08 08:05:57 +00003558 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3559 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003560
John McCall7f416cc2015-09-08 08:05:57 +00003561 // Case 1: consume registers.
3562 Address RegAddr = Address::invalid();
3563 {
3564 CGF.EmitBlock(UsingRegs);
3565
3566 Address RegSaveAreaPtr =
3567 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3568 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3569 CharUnits::fromQuantity(8));
3570 assert(RegAddr.getElementType() == CGF.Int8Ty);
3571
3572 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003573 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003574 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3575 CharUnits::fromQuantity(32));
3576 }
3577
3578 // Get the address of the saved value by scaling the number of
3579 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003580 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003581 llvm::Value *RegOffset =
3582 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3583 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3584 RegAddr.getPointer(), RegOffset),
3585 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3586 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3587
3588 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003589 NumRegs =
3590 Builder.CreateAdd(NumRegs,
3591 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003592 Builder.CreateStore(NumRegs, NumRegsAddr);
3593
3594 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003595 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003596
John McCall7f416cc2015-09-08 08:05:57 +00003597 // Case 2: consume space in the overflow area.
3598 Address MemAddr = Address::invalid();
3599 {
3600 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003601
John McCall7f416cc2015-09-08 08:05:57 +00003602 // Everything in the overflow area is rounded up to a size of at least 4.
3603 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3604
3605 CharUnits Size;
3606 if (!isIndirect) {
3607 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003608 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003609 } else {
3610 Size = CGF.getPointerSize();
3611 }
3612
3613 Address OverflowAreaAddr =
3614 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003615 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003616 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003617 // Round up address of argument to alignment
3618 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3619 if (Align > OverflowAreaAlign) {
3620 llvm::Value *Ptr = OverflowArea.getPointer();
3621 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3622 Align);
3623 }
3624
John McCall7f416cc2015-09-08 08:05:57 +00003625 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3626
3627 // Increase the overflow area.
3628 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3629 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3630 CGF.EmitBranch(Cont);
3631 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003632
3633 CGF.EmitBlock(Cont);
3634
John McCall7f416cc2015-09-08 08:05:57 +00003635 // Merge the cases with a phi.
3636 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3637 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003638
John McCall7f416cc2015-09-08 08:05:57 +00003639 // Load the pointer if the argument was passed indirectly.
3640 if (isIndirect) {
3641 Result = Address(Builder.CreateLoad(Result, "aggr"),
3642 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003643 }
3644
3645 return Result;
3646}
3647
John McCallea8d8bb2010-03-11 00:10:12 +00003648bool
3649PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3650 llvm::Value *Address) const {
3651 // This is calculated from the LLVM and GCC tables and verified
3652 // against gcc output. AFAIK all ABIs use the same encoding.
3653
3654 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003655
Chris Lattnerece04092012-02-07 00:39:47 +00003656 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003657 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3658 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3659 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3660
3661 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003662 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003663
3664 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003665 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003666
3667 // 64-76 are various 4-byte special-purpose registers:
3668 // 64: mq
3669 // 65: lr
3670 // 66: ctr
3671 // 67: ap
3672 // 68-75 cr0-7
3673 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003674 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003675
3676 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003677 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003678
3679 // 109: vrsave
3680 // 110: vscr
3681 // 111: spe_acc
3682 // 112: spefscr
3683 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003684 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003685
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003686 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003687}
3688
Roman Divackyd966e722012-05-09 18:22:46 +00003689// PowerPC-64
3690
3691namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003692/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3693class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003694public:
3695 enum ABIKind {
3696 ELFv1 = 0,
3697 ELFv2
3698 };
3699
3700private:
3701 static const unsigned GPRBits = 64;
3702 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003703 bool HasQPX;
3704
3705 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3706 // will be passed in a QPX register.
3707 bool IsQPXVectorTy(const Type *Ty) const {
3708 if (!HasQPX)
3709 return false;
3710
3711 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3712 unsigned NumElements = VT->getNumElements();
3713 if (NumElements == 1)
3714 return false;
3715
3716 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3717 if (getContext().getTypeSize(Ty) <= 256)
3718 return true;
3719 } else if (VT->getElementType()->
3720 isSpecificBuiltinType(BuiltinType::Float)) {
3721 if (getContext().getTypeSize(Ty) <= 128)
3722 return true;
3723 }
3724 }
3725
3726 return false;
3727 }
3728
3729 bool IsQPXVectorTy(QualType Ty) const {
3730 return IsQPXVectorTy(Ty.getTypePtr());
3731 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003732
3733public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003734 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3735 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003736
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003737 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003738 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003739
3740 ABIArgInfo classifyReturnType(QualType RetTy) const;
3741 ABIArgInfo classifyArgumentType(QualType Ty) const;
3742
Reid Klecknere9f6a712014-10-31 17:10:41 +00003743 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3744 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3745 uint64_t Members) const override;
3746
Bill Schmidt84d37792012-10-12 19:26:17 +00003747 // TODO: We can add more logic to computeInfo to improve performance.
3748 // Example: For aggregate arguments that fit in a register, we could
3749 // use getDirectInReg (as is done below for structs containing a single
3750 // floating-point value) to avoid pushing them to memory on function
3751 // entry. This would require changing the logic in PPCISelLowering
3752 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003753 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003754 if (!getCXXABI().classifyReturnType(FI))
3755 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003756 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003757 // We rely on the default argument classification for the most part.
3758 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003759 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003760 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003761 if (T) {
3762 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003763 if (IsQPXVectorTy(T) ||
3764 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003765 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003766 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003767 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003768 continue;
3769 }
3770 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003771 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003772 }
3773 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003774
John McCall7f416cc2015-09-08 08:05:57 +00003775 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3776 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003777};
3778
3779class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003780
Bill Schmidt25cb3492012-10-03 19:18:57 +00003781public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003782 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003783 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003784 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003785
Craig Topper4f12f102014-03-12 06:41:41 +00003786 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003787 // This is recovered from gcc output.
3788 return 1; // r1 is the dedicated stack pointer
3789 }
3790
3791 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003792 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003793};
3794
Roman Divackyd966e722012-05-09 18:22:46 +00003795class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3796public:
3797 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3798
Craig Topper4f12f102014-03-12 06:41:41 +00003799 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003800 // This is recovered from gcc output.
3801 return 1; // r1 is the dedicated stack pointer
3802 }
3803
3804 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003805 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003806};
3807
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003808}
Roman Divackyd966e722012-05-09 18:22:46 +00003809
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003810// Return true if the ABI requires Ty to be passed sign- or zero-
3811// extended to 64 bits.
3812bool
3813PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3814 // Treat an enum type as its underlying type.
3815 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3816 Ty = EnumTy->getDecl()->getIntegerType();
3817
3818 // Promotable integer types are required to be promoted by the ABI.
3819 if (Ty->isPromotableIntegerType())
3820 return true;
3821
3822 // In addition to the usual promotable integer types, we also need to
3823 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3824 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3825 switch (BT->getKind()) {
3826 case BuiltinType::Int:
3827 case BuiltinType::UInt:
3828 return true;
3829 default:
3830 break;
3831 }
3832
3833 return false;
3834}
3835
John McCall7f416cc2015-09-08 08:05:57 +00003836/// isAlignedParamType - Determine whether a type requires 16-byte or
3837/// higher alignment in the parameter area. Always returns at least 8.
3838CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003839 // Complex types are passed just like their elements.
3840 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3841 Ty = CTy->getElementType();
3842
3843 // Only vector types of size 16 bytes need alignment (larger types are
3844 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003845 if (IsQPXVectorTy(Ty)) {
3846 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003847 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003848
John McCall7f416cc2015-09-08 08:05:57 +00003849 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003850 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00003851 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003852 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003853
3854 // For single-element float/vector structs, we consider the whole type
3855 // to have the same alignment requirements as its single element.
3856 const Type *AlignAsType = nullptr;
3857 const Type *EltType = isSingleElementStruct(Ty, getContext());
3858 if (EltType) {
3859 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003860 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003861 getContext().getTypeSize(EltType) == 128) ||
3862 (BT && BT->isFloatingPoint()))
3863 AlignAsType = EltType;
3864 }
3865
Ulrich Weigandb7122372014-07-21 00:48:09 +00003866 // Likewise for ELFv2 homogeneous aggregates.
3867 const Type *Base = nullptr;
3868 uint64_t Members = 0;
3869 if (!AlignAsType && Kind == ELFv2 &&
3870 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3871 AlignAsType = Base;
3872
Ulrich Weigand581badc2014-07-10 17:20:07 +00003873 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003874 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3875 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003876 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003877
John McCall7f416cc2015-09-08 08:05:57 +00003878 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003879 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00003880 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003881 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003882
3883 // Otherwise, we only need alignment for any aggregate type that
3884 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003885 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3886 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00003887 return CharUnits::fromQuantity(32);
3888 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003889 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003890
John McCall7f416cc2015-09-08 08:05:57 +00003891 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00003892}
3893
Ulrich Weigandb7122372014-07-21 00:48:09 +00003894/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3895/// aggregate. Base is set to the base element type, and Members is set
3896/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003897bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3898 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003899 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3900 uint64_t NElements = AT->getSize().getZExtValue();
3901 if (NElements == 0)
3902 return false;
3903 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3904 return false;
3905 Members *= NElements;
3906 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3907 const RecordDecl *RD = RT->getDecl();
3908 if (RD->hasFlexibleArrayMember())
3909 return false;
3910
3911 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003912
3913 // If this is a C++ record, check the bases first.
3914 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3915 for (const auto &I : CXXRD->bases()) {
3916 // Ignore empty records.
3917 if (isEmptyRecord(getContext(), I.getType(), true))
3918 continue;
3919
3920 uint64_t FldMembers;
3921 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3922 return false;
3923
3924 Members += FldMembers;
3925 }
3926 }
3927
Ulrich Weigandb7122372014-07-21 00:48:09 +00003928 for (const auto *FD : RD->fields()) {
3929 // Ignore (non-zero arrays of) empty records.
3930 QualType FT = FD->getType();
3931 while (const ConstantArrayType *AT =
3932 getContext().getAsConstantArrayType(FT)) {
3933 if (AT->getSize().getZExtValue() == 0)
3934 return false;
3935 FT = AT->getElementType();
3936 }
3937 if (isEmptyRecord(getContext(), FT, true))
3938 continue;
3939
3940 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3941 if (getContext().getLangOpts().CPlusPlus &&
3942 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3943 continue;
3944
3945 uint64_t FldMembers;
3946 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3947 return false;
3948
3949 Members = (RD->isUnion() ?
3950 std::max(Members, FldMembers) : Members + FldMembers);
3951 }
3952
3953 if (!Base)
3954 return false;
3955
3956 // Ensure there is no padding.
3957 if (getContext().getTypeSize(Base) * Members !=
3958 getContext().getTypeSize(Ty))
3959 return false;
3960 } else {
3961 Members = 1;
3962 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3963 Members = 2;
3964 Ty = CT->getElementType();
3965 }
3966
Reid Klecknere9f6a712014-10-31 17:10:41 +00003967 // Most ABIs only support float, double, and some vector type widths.
3968 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003969 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003970
3971 // The base type must be the same for all members. Types that
3972 // agree in both total size and mode (float vs. vector) are
3973 // treated as being equivalent here.
3974 const Type *TyPtr = Ty.getTypePtr();
3975 if (!Base)
3976 Base = TyPtr;
3977
3978 if (Base->isVectorType() != TyPtr->isVectorType() ||
3979 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3980 return false;
3981 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003982 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3983}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003984
Reid Klecknere9f6a712014-10-31 17:10:41 +00003985bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3986 // Homogeneous aggregates for ELFv2 must have base types of float,
3987 // double, long double, or 128-bit vectors.
3988 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3989 if (BT->getKind() == BuiltinType::Float ||
3990 BT->getKind() == BuiltinType::Double ||
3991 BT->getKind() == BuiltinType::LongDouble)
3992 return true;
3993 }
3994 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003995 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003996 return true;
3997 }
3998 return false;
3999}
4000
4001bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4002 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004003 // Vector types require one register, floating point types require one
4004 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004005 uint32_t NumRegs =
4006 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004007
4008 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004009 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004010}
4011
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004012ABIArgInfo
4013PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004014 Ty = useFirstFieldIfTransparentUnion(Ty);
4015
Bill Schmidt90b22c92012-11-27 02:46:43 +00004016 if (Ty->isAnyComplexType())
4017 return ABIArgInfo::getDirect();
4018
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004019 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4020 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004021 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004022 uint64_t Size = getContext().getTypeSize(Ty);
4023 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004024 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004025 else if (Size < 128) {
4026 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4027 return ABIArgInfo::getDirect(CoerceTy);
4028 }
4029 }
4030
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004031 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004032 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004033 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004034
John McCall7f416cc2015-09-08 08:05:57 +00004035 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4036 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004037
4038 // ELFv2 homogeneous aggregates are passed as array types.
4039 const Type *Base = nullptr;
4040 uint64_t Members = 0;
4041 if (Kind == ELFv2 &&
4042 isHomogeneousAggregate(Ty, Base, Members)) {
4043 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4044 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4045 return ABIArgInfo::getDirect(CoerceTy);
4046 }
4047
Ulrich Weigand601957f2014-07-21 00:56:36 +00004048 // If an aggregate may end up fully in registers, we do not
4049 // use the ByVal method, but pass the aggregate as array.
4050 // This is usually beneficial since we avoid forcing the
4051 // back-end to store the argument to memory.
4052 uint64_t Bits = getContext().getTypeSize(Ty);
4053 if (Bits > 0 && Bits <= 8 * GPRBits) {
4054 llvm::Type *CoerceTy;
4055
4056 // Types up to 8 bytes are passed as integer type (which will be
4057 // properly aligned in the argument save area doubleword).
4058 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004059 CoerceTy =
4060 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004061 // Larger types are passed as arrays, with the base type selected
4062 // according to the required alignment in the save area.
4063 else {
4064 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004065 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004066 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4067 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4068 }
4069
4070 return ABIArgInfo::getDirect(CoerceTy);
4071 }
4072
Ulrich Weigandb7122372014-07-21 00:48:09 +00004073 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004074 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4075 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004076 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004077 }
4078
4079 return (isPromotableTypeForABI(Ty) ?
4080 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4081}
4082
4083ABIArgInfo
4084PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4085 if (RetTy->isVoidType())
4086 return ABIArgInfo::getIgnore();
4087
Bill Schmidta3d121c2012-12-17 04:20:17 +00004088 if (RetTy->isAnyComplexType())
4089 return ABIArgInfo::getDirect();
4090
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004091 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4092 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004093 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004094 uint64_t Size = getContext().getTypeSize(RetTy);
4095 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004096 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004097 else if (Size < 128) {
4098 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4099 return ABIArgInfo::getDirect(CoerceTy);
4100 }
4101 }
4102
Ulrich Weigandb7122372014-07-21 00:48:09 +00004103 if (isAggregateTypeForABI(RetTy)) {
4104 // ELFv2 homogeneous aggregates are returned as array types.
4105 const Type *Base = nullptr;
4106 uint64_t Members = 0;
4107 if (Kind == ELFv2 &&
4108 isHomogeneousAggregate(RetTy, Base, Members)) {
4109 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4110 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4111 return ABIArgInfo::getDirect(CoerceTy);
4112 }
4113
4114 // ELFv2 small aggregates are returned in up to two registers.
4115 uint64_t Bits = getContext().getTypeSize(RetTy);
4116 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4117 if (Bits == 0)
4118 return ABIArgInfo::getIgnore();
4119
4120 llvm::Type *CoerceTy;
4121 if (Bits > GPRBits) {
4122 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004123 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004124 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004125 CoerceTy =
4126 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004127 return ABIArgInfo::getDirect(CoerceTy);
4128 }
4129
4130 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004131 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004132 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004133
4134 return (isPromotableTypeForABI(RetTy) ?
4135 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4136}
4137
Bill Schmidt25cb3492012-10-03 19:18:57 +00004138// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004139Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4140 QualType Ty) const {
4141 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4142 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004143
John McCall7f416cc2015-09-08 08:05:57 +00004144 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004145
Bill Schmidt924c4782013-01-14 17:45:36 +00004146 // If we have a complex type and the base type is smaller than 8 bytes,
4147 // the ABI calls for the real and imaginary parts to be right-adjusted
4148 // in separate doublewords. However, Clang expects us to produce a
4149 // pointer to a structure with the two parts packed tightly. So generate
4150 // loads of the real and imaginary parts relative to the va_list pointer,
4151 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004152 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4153 CharUnits EltSize = TypeInfo.first / 2;
4154 if (EltSize < SlotSize) {
4155 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4156 SlotSize * 2, SlotSize,
4157 SlotSize, /*AllowHigher*/ true);
4158
4159 Address RealAddr = Addr;
4160 Address ImagAddr = RealAddr;
4161 if (CGF.CGM.getDataLayout().isBigEndian()) {
4162 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4163 SlotSize - EltSize);
4164 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4165 2 * SlotSize - EltSize);
4166 } else {
4167 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4168 }
4169
4170 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4171 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4172 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4173 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4174 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4175
4176 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4177 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4178 /*init*/ true);
4179 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004180 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004181 }
4182
John McCall7f416cc2015-09-08 08:05:57 +00004183 // Otherwise, just use the general rule.
4184 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4185 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004186}
4187
4188static bool
4189PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4190 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004191 // This is calculated from the LLVM and GCC tables and verified
4192 // against gcc output. AFAIK all ABIs use the same encoding.
4193
4194 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4195
4196 llvm::IntegerType *i8 = CGF.Int8Ty;
4197 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4198 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4199 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4200
4201 // 0-31: r0-31, the 8-byte general-purpose registers
4202 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4203
4204 // 32-63: fp0-31, the 8-byte floating-point registers
4205 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4206
4207 // 64-76 are various 4-byte special-purpose registers:
4208 // 64: mq
4209 // 65: lr
4210 // 66: ctr
4211 // 67: ap
4212 // 68-75 cr0-7
4213 // 76: xer
4214 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4215
4216 // 77-108: v0-31, the 16-byte vector registers
4217 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4218
4219 // 109: vrsave
4220 // 110: vscr
4221 // 111: spe_acc
4222 // 112: spefscr
4223 // 113: sfp
4224 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4225
4226 return false;
4227}
John McCallea8d8bb2010-03-11 00:10:12 +00004228
Bill Schmidt25cb3492012-10-03 19:18:57 +00004229bool
4230PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4231 CodeGen::CodeGenFunction &CGF,
4232 llvm::Value *Address) const {
4233
4234 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4235}
4236
4237bool
4238PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4239 llvm::Value *Address) const {
4240
4241 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4242}
4243
Chris Lattner0cf24192010-06-28 20:05:43 +00004244//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004245// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004246//===----------------------------------------------------------------------===//
4247
4248namespace {
4249
Tim Northover573cbee2014-05-24 12:52:07 +00004250class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004251public:
4252 enum ABIKind {
4253 AAPCS = 0,
4254 DarwinPCS
4255 };
4256
4257private:
4258 ABIKind Kind;
4259
4260public:
Tim Northover573cbee2014-05-24 12:52:07 +00004261 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004262
4263private:
4264 ABIKind getABIKind() const { return Kind; }
4265 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4266
4267 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004268 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004269 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4270 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4271 uint64_t Members) const override;
4272
Tim Northovera2ee4332014-03-29 15:09:45 +00004273 bool isIllegalVectorType(QualType Ty) const;
4274
David Blaikie1cbb9712014-11-14 19:09:44 +00004275 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004276 if (!getCXXABI().classifyReturnType(FI))
4277 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004278
Tim Northoverb047bfa2014-11-27 21:02:49 +00004279 for (auto &it : FI.arguments())
4280 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004281 }
4282
John McCall7f416cc2015-09-08 08:05:57 +00004283 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4284 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004285
John McCall7f416cc2015-09-08 08:05:57 +00004286 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4287 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004288
John McCall7f416cc2015-09-08 08:05:57 +00004289 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4290 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004291 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4292 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4293 }
4294};
4295
Tim Northover573cbee2014-05-24 12:52:07 +00004296class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004297public:
Tim Northover573cbee2014-05-24 12:52:07 +00004298 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4299 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004300
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004301 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004302 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4303 }
4304
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004305 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4306 return 31;
4307 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004308
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004309 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004310};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004311}
Tim Northovera2ee4332014-03-29 15:09:45 +00004312
Tim Northoverb047bfa2014-11-27 21:02:49 +00004313ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004314 Ty = useFirstFieldIfTransparentUnion(Ty);
4315
Tim Northovera2ee4332014-03-29 15:09:45 +00004316 // Handle illegal vector types here.
4317 if (isIllegalVectorType(Ty)) {
4318 uint64_t Size = getContext().getTypeSize(Ty);
4319 if (Size <= 32) {
4320 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004321 return ABIArgInfo::getDirect(ResType);
4322 }
4323 if (Size == 64) {
4324 llvm::Type *ResType =
4325 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004326 return ABIArgInfo::getDirect(ResType);
4327 }
4328 if (Size == 128) {
4329 llvm::Type *ResType =
4330 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004331 return ABIArgInfo::getDirect(ResType);
4332 }
John McCall7f416cc2015-09-08 08:05:57 +00004333 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004334 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004335
4336 if (!isAggregateTypeForABI(Ty)) {
4337 // Treat an enum type as its underlying type.
4338 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4339 Ty = EnumTy->getDecl()->getIntegerType();
4340
Tim Northovera2ee4332014-03-29 15:09:45 +00004341 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4342 ? ABIArgInfo::getExtend()
4343 : ABIArgInfo::getDirect());
4344 }
4345
4346 // Structures with either a non-trivial destructor or a non-trivial
4347 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004348 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004349 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4350 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004351 }
4352
4353 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4354 // elsewhere for GNU compatibility.
4355 if (isEmptyRecord(getContext(), Ty, true)) {
4356 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4357 return ABIArgInfo::getIgnore();
4358
Tim Northovera2ee4332014-03-29 15:09:45 +00004359 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4360 }
4361
4362 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004363 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004364 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004365 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004366 return ABIArgInfo::getDirect(
4367 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004368 }
4369
4370 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4371 uint64_t Size = getContext().getTypeSize(Ty);
4372 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004373 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004374 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004375
Tim Northovera2ee4332014-03-29 15:09:45 +00004376 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4377 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004378 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004379 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4380 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4381 }
4382 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4383 }
4384
John McCall7f416cc2015-09-08 08:05:57 +00004385 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004386}
4387
Tim Northover573cbee2014-05-24 12:52:07 +00004388ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004389 if (RetTy->isVoidType())
4390 return ABIArgInfo::getIgnore();
4391
4392 // Large vector types should be returned via memory.
4393 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004394 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004395
4396 if (!isAggregateTypeForABI(RetTy)) {
4397 // Treat an enum type as its underlying type.
4398 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4399 RetTy = EnumTy->getDecl()->getIntegerType();
4400
Tim Northover4dab6982014-04-18 13:46:08 +00004401 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4402 ? ABIArgInfo::getExtend()
4403 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004404 }
4405
Tim Northovera2ee4332014-03-29 15:09:45 +00004406 if (isEmptyRecord(getContext(), RetTy, true))
4407 return ABIArgInfo::getIgnore();
4408
Craig Topper8a13c412014-05-21 05:09:00 +00004409 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004410 uint64_t Members = 0;
4411 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004412 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4413 return ABIArgInfo::getDirect();
4414
4415 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4416 uint64_t Size = getContext().getTypeSize(RetTy);
4417 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004418 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004419 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004420
4421 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4422 // For aggregates with 16-byte alignment, we use i128.
4423 if (Alignment < 128 && Size == 128) {
4424 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4425 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4426 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004427 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4428 }
4429
John McCall7f416cc2015-09-08 08:05:57 +00004430 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004431}
4432
Tim Northover573cbee2014-05-24 12:52:07 +00004433/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4434bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004435 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4436 // Check whether VT is legal.
4437 unsigned NumElements = VT->getNumElements();
4438 uint64_t Size = getContext().getTypeSize(VT);
4439 // NumElements should be power of 2 between 1 and 16.
4440 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4441 return true;
4442 return Size != 64 && (Size != 128 || NumElements == 1);
4443 }
4444 return false;
4445}
4446
Reid Klecknere9f6a712014-10-31 17:10:41 +00004447bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4448 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4449 // point type or a short-vector type. This is the same as the 32-bit ABI,
4450 // but with the difference that any floating-point type is allowed,
4451 // including __fp16.
4452 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4453 if (BT->isFloatingPoint())
4454 return true;
4455 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4456 unsigned VecSize = getContext().getTypeSize(VT);
4457 if (VecSize == 64 || VecSize == 128)
4458 return true;
4459 }
4460 return false;
4461}
4462
4463bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4464 uint64_t Members) const {
4465 return Members <= 4;
4466}
4467
John McCall7f416cc2015-09-08 08:05:57 +00004468Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004469 QualType Ty,
4470 CodeGenFunction &CGF) const {
4471 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004472 bool IsIndirect = AI.isIndirect();
4473
Tim Northoverb047bfa2014-11-27 21:02:49 +00004474 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4475 if (IsIndirect)
4476 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4477 else if (AI.getCoerceToType())
4478 BaseTy = AI.getCoerceToType();
4479
4480 unsigned NumRegs = 1;
4481 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4482 BaseTy = ArrTy->getElementType();
4483 NumRegs = ArrTy->getNumElements();
4484 }
4485 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4486
Tim Northovera2ee4332014-03-29 15:09:45 +00004487 // The AArch64 va_list type and handling is specified in the Procedure Call
4488 // Standard, section B.4:
4489 //
4490 // struct {
4491 // void *__stack;
4492 // void *__gr_top;
4493 // void *__vr_top;
4494 // int __gr_offs;
4495 // int __vr_offs;
4496 // };
4497
4498 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4499 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4500 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4501 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004502
John McCall7f416cc2015-09-08 08:05:57 +00004503 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4504 CharUnits TyAlign = TyInfo.second;
4505
4506 Address reg_offs_p = Address::invalid();
4507 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004508 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004509 CharUnits reg_top_offset;
4510 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004511 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004512 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004513 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004514 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4515 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004516 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4517 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004518 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004519 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004520 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004521 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004522 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004523 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4524 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004525 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4526 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004527 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004528 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004529 }
4530
4531 //=======================================
4532 // Find out where argument was passed
4533 //=======================================
4534
4535 // If reg_offs >= 0 we're already using the stack for this type of
4536 // argument. We don't want to keep updating reg_offs (in case it overflows,
4537 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4538 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004539 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004540 UsingStack = CGF.Builder.CreateICmpSGE(
4541 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4542
4543 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4544
4545 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004546 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004547 CGF.EmitBlock(MaybeRegBlock);
4548
4549 // Integer arguments may need to correct register alignment (for example a
4550 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4551 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004552 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4553 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004554
4555 reg_offs = CGF.Builder.CreateAdd(
4556 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4557 "align_regoffs");
4558 reg_offs = CGF.Builder.CreateAnd(
4559 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4560 "aligned_regoffs");
4561 }
4562
4563 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004564 // The fact that this is done unconditionally reflects the fact that
4565 // allocating an argument to the stack also uses up all the remaining
4566 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004567 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004568 NewOffset = CGF.Builder.CreateAdd(
4569 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4570 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4571
4572 // Now we're in a position to decide whether this argument really was in
4573 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004574 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004575 InRegs = CGF.Builder.CreateICmpSLE(
4576 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4577
4578 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4579
4580 //=======================================
4581 // Argument was in registers
4582 //=======================================
4583
4584 // Now we emit the code for if the argument was originally passed in
4585 // registers. First start the appropriate block:
4586 CGF.EmitBlock(InRegBlock);
4587
John McCall7f416cc2015-09-08 08:05:57 +00004588 llvm::Value *reg_top = nullptr;
4589 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4590 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004591 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004592 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4593 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4594 Address RegAddr = Address::invalid();
4595 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004596
4597 if (IsIndirect) {
4598 // If it's been passed indirectly (actually a struct), whatever we find from
4599 // stored registers or on the stack will actually be a struct **.
4600 MemTy = llvm::PointerType::getUnqual(MemTy);
4601 }
4602
Craig Topper8a13c412014-05-21 05:09:00 +00004603 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004604 uint64_t NumMembers = 0;
4605 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004606 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004607 // Homogeneous aggregates passed in registers will have their elements split
4608 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4609 // qN+1, ...). We reload and store into a temporary local variable
4610 // contiguously.
4611 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004612 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004613 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4614 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004615 Address Tmp = CGF.CreateTempAlloca(HFATy,
4616 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004617
John McCall7f416cc2015-09-08 08:05:57 +00004618 // On big-endian platforms, the value will be right-aligned in its slot.
4619 int Offset = 0;
4620 if (CGF.CGM.getDataLayout().isBigEndian() &&
4621 BaseTyInfo.first.getQuantity() < 16)
4622 Offset = 16 - BaseTyInfo.first.getQuantity();
4623
Tim Northovera2ee4332014-03-29 15:09:45 +00004624 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004625 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4626 Address LoadAddr =
4627 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4628 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4629
4630 Address StoreAddr =
4631 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004632
4633 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4634 CGF.Builder.CreateStore(Elem, StoreAddr);
4635 }
4636
John McCall7f416cc2015-09-08 08:05:57 +00004637 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004638 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004639 // Otherwise the object is contiguous in memory.
4640
4641 // It might be right-aligned in its slot.
4642 CharUnits SlotSize = BaseAddr.getAlignment();
4643 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004644 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004645 TyInfo.first < SlotSize) {
4646 CharUnits Offset = SlotSize - TyInfo.first;
4647 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004648 }
4649
John McCall7f416cc2015-09-08 08:05:57 +00004650 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004651 }
4652
4653 CGF.EmitBranch(ContBlock);
4654
4655 //=======================================
4656 // Argument was on the stack
4657 //=======================================
4658 CGF.EmitBlock(OnStackBlock);
4659
John McCall7f416cc2015-09-08 08:05:57 +00004660 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4661 CharUnits::Zero(), "stack_p");
4662 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004663
John McCall7f416cc2015-09-08 08:05:57 +00004664 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004665 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004666 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4667 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004668
John McCall7f416cc2015-09-08 08:05:57 +00004669 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004670
John McCall7f416cc2015-09-08 08:05:57 +00004671 OnStackPtr = CGF.Builder.CreateAdd(
4672 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004673 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004674 OnStackPtr = CGF.Builder.CreateAnd(
4675 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004676 "align_stack");
4677
John McCall7f416cc2015-09-08 08:05:57 +00004678 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004679 }
John McCall7f416cc2015-09-08 08:05:57 +00004680 Address OnStackAddr(OnStackPtr,
4681 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004682
John McCall7f416cc2015-09-08 08:05:57 +00004683 // All stack slots are multiples of 8 bytes.
4684 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4685 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004686 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004687 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004688 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004689 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004690
John McCall7f416cc2015-09-08 08:05:57 +00004691 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004692 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004693 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004694
4695 // Write the new value of __stack for the next call to va_arg
4696 CGF.Builder.CreateStore(NewStack, stack_p);
4697
4698 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004699 TyInfo.first < StackSlotSize) {
4700 CharUnits Offset = StackSlotSize - TyInfo.first;
4701 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004702 }
4703
John McCall7f416cc2015-09-08 08:05:57 +00004704 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004705
4706 CGF.EmitBranch(ContBlock);
4707
4708 //=======================================
4709 // Tidy up
4710 //=======================================
4711 CGF.EmitBlock(ContBlock);
4712
John McCall7f416cc2015-09-08 08:05:57 +00004713 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4714 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004715
4716 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004717 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4718 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004719
4720 return ResAddr;
4721}
4722
John McCall7f416cc2015-09-08 08:05:57 +00004723Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4724 CodeGenFunction &CGF) const {
4725 // The backend's lowering doesn't support va_arg for aggregates or
4726 // illegal vector types. Lower VAArg here for these cases and use
4727 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004728 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00004729 return Address::invalid();
Tim Northovera2ee4332014-03-29 15:09:45 +00004730
John McCall7f416cc2015-09-08 08:05:57 +00004731 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004732
John McCall7f416cc2015-09-08 08:05:57 +00004733 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004734 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004735 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4736 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4737 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004738 }
4739
John McCall7f416cc2015-09-08 08:05:57 +00004740 // The size of the actual thing passed, which might end up just
4741 // being a pointer for indirect types.
4742 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4743
4744 // Arguments bigger than 16 bytes which aren't homogeneous
4745 // aggregates should be passed indirectly.
4746 bool IsIndirect = false;
4747 if (TyInfo.first.getQuantity() > 16) {
4748 const Type *Base = nullptr;
4749 uint64_t Members = 0;
4750 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004751 }
4752
John McCall7f416cc2015-09-08 08:05:57 +00004753 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4754 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004755}
4756
4757//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004758// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004759//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004760
4761namespace {
4762
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004763class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004764public:
4765 enum ABIKind {
4766 APCS = 0,
4767 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004768 AAPCS_VFP = 2,
4769 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004770 };
4771
4772private:
4773 ABIKind Kind;
4774
4775public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004776 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004777 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004778 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004779
John McCall3480ef22011-08-30 01:42:09 +00004780 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004781 switch (getTarget().getTriple().getEnvironment()) {
4782 case llvm::Triple::Android:
4783 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004784 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004785 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004786 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004787 return true;
4788 default:
4789 return false;
4790 }
John McCall3480ef22011-08-30 01:42:09 +00004791 }
4792
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004793 bool isEABIHF() const {
4794 switch (getTarget().getTriple().getEnvironment()) {
4795 case llvm::Triple::EABIHF:
4796 case llvm::Triple::GNUEABIHF:
4797 return true;
4798 default:
4799 return false;
4800 }
4801 }
4802
Stephen Hines8267e7d2015-12-04 01:39:30 +00004803 bool isAndroid() const {
4804 return (getTarget().getTriple().getEnvironment() ==
4805 llvm::Triple::Android);
4806 }
4807
Daniel Dunbar020daa92009-09-12 01:00:39 +00004808 ABIKind getABIKind() const { return Kind; }
4809
Tim Northovera484bc02013-10-01 14:34:25 +00004810private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004811 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004812 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004813 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004814
Reid Klecknere9f6a712014-10-31 17:10:41 +00004815 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4816 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4817 uint64_t Members) const override;
4818
Craig Topper4f12f102014-03-12 06:41:41 +00004819 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004820
John McCall7f416cc2015-09-08 08:05:57 +00004821 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4822 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004823
4824 llvm::CallingConv::ID getLLVMDefaultCC() const;
4825 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004826 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004827};
4828
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004829class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4830public:
Chris Lattner2b037972010-07-29 02:01:43 +00004831 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4832 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004833
John McCall3480ef22011-08-30 01:42:09 +00004834 const ARMABIInfo &getABIInfo() const {
4835 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4836 }
4837
Craig Topper4f12f102014-03-12 06:41:41 +00004838 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004839 return 13;
4840 }
Roman Divackyc1617352011-05-18 19:36:54 +00004841
Craig Topper4f12f102014-03-12 06:41:41 +00004842 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004843 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4844 }
4845
Roman Divackyc1617352011-05-18 19:36:54 +00004846 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004847 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004848 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004849
4850 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004851 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004852 return false;
4853 }
John McCall3480ef22011-08-30 01:42:09 +00004854
Craig Topper4f12f102014-03-12 06:41:41 +00004855 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004856 if (getABIInfo().isEABI()) return 88;
4857 return TargetCodeGenInfo::getSizeOfUnwindException();
4858 }
Tim Northovera484bc02013-10-01 14:34:25 +00004859
Eric Christopher162c91c2015-06-05 22:03:00 +00004860 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004861 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00004862 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00004863 if (!FD)
4864 return;
4865
4866 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4867 if (!Attr)
4868 return;
4869
4870 const char *Kind;
4871 switch (Attr->getInterrupt()) {
4872 case ARMInterruptAttr::Generic: Kind = ""; break;
4873 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4874 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4875 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4876 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4877 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4878 }
4879
4880 llvm::Function *Fn = cast<llvm::Function>(GV);
4881
4882 Fn->addFnAttr("interrupt", Kind);
4883
Tim Northover5627d392015-10-30 16:30:45 +00004884 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
4885 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00004886 return;
4887
4888 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4889 // however this is not necessarily true on taking any interrupt. Instruct
4890 // the backend to perform a realignment as part of the function prologue.
4891 llvm::AttrBuilder B;
4892 B.addStackAlignmentAttr(8);
4893 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4894 llvm::AttributeSet::get(CGM.getLLVMContext(),
4895 llvm::AttributeSet::FunctionIndex,
4896 B));
4897 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004898};
4899
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004900class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004901public:
4902 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4903 : ARMTargetCodeGenInfo(CGT, K) {}
4904
Eric Christopher162c91c2015-06-05 22:03:00 +00004905 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004906 CodeGen::CodeGenModule &CGM) const override;
4907};
4908
Eric Christopher162c91c2015-06-05 22:03:00 +00004909void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004910 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004911 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004912 addStackProbeSizeTargetAttribute(D, GV, CGM);
4913}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004914}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004915
Chris Lattner22326a12010-07-29 02:31:05 +00004916void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004917 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004918 FI.getReturnInfo() =
4919 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004920
Tim Northoverbc784d12015-02-24 17:22:40 +00004921 for (auto &I : FI.arguments())
4922 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004923
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004924 // Always honor user-specified calling convention.
4925 if (FI.getCallingConvention() != llvm::CallingConv::C)
4926 return;
4927
John McCall882987f2013-02-28 19:01:20 +00004928 llvm::CallingConv::ID cc = getRuntimeCC();
4929 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004930 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004931}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004932
John McCall882987f2013-02-28 19:01:20 +00004933/// Return the default calling convention that LLVM will use.
4934llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4935 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00004936 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00004937 return llvm::CallingConv::ARM_AAPCS_VFP;
4938 else if (isEABI())
4939 return llvm::CallingConv::ARM_AAPCS;
4940 else
4941 return llvm::CallingConv::ARM_APCS;
4942}
4943
4944/// Return the calling convention that our ABI would like us to use
4945/// as the C calling convention.
4946llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004947 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004948 case APCS: return llvm::CallingConv::ARM_APCS;
4949 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4950 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00004951 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004952 }
John McCall882987f2013-02-28 19:01:20 +00004953 llvm_unreachable("bad ABI kind");
4954}
4955
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004956void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004957 assert(getRuntimeCC() == llvm::CallingConv::C);
4958
4959 // Don't muddy up the IR with a ton of explicit annotations if
4960 // they'd just match what LLVM will infer from the triple.
4961 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4962 if (abiCC != getLLVMDefaultCC())
4963 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004964
Tim Northover5627d392015-10-30 16:30:45 +00004965 // AAPCS apparently requires runtime support functions to be soft-float, but
4966 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
4967 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
4968 switch (getABIKind()) {
4969 case APCS:
4970 case AAPCS16_VFP:
4971 if (abiCC != getLLVMDefaultCC())
4972 BuiltinCC = abiCC;
4973 break;
4974 case AAPCS:
4975 case AAPCS_VFP:
4976 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
4977 break;
4978 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004979}
4980
Tim Northoverbc784d12015-02-24 17:22:40 +00004981ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4982 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004983 // 6.1.2.1 The following argument types are VFP CPRCs:
4984 // A single-precision floating-point type (including promoted
4985 // half-precision types); A double-precision floating-point type;
4986 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4987 // with a Base Type of a single- or double-precision floating-point type,
4988 // 64-bit containerized vectors or 128-bit containerized vectors with one
4989 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004990 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004991
Reid Klecknerb1be6832014-11-15 01:41:41 +00004992 Ty = useFirstFieldIfTransparentUnion(Ty);
4993
Manman Renfef9e312012-10-16 19:18:39 +00004994 // Handle illegal vector types here.
4995 if (isIllegalVectorType(Ty)) {
4996 uint64_t Size = getContext().getTypeSize(Ty);
4997 if (Size <= 32) {
4998 llvm::Type *ResType =
4999 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005000 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005001 }
5002 if (Size == 64) {
5003 llvm::Type *ResType = llvm::VectorType::get(
5004 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005005 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005006 }
5007 if (Size == 128) {
5008 llvm::Type *ResType = llvm::VectorType::get(
5009 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005010 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005011 }
John McCall7f416cc2015-09-08 08:05:57 +00005012 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005013 }
5014
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005015 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5016 // unspecified. This is not done for OpenCL as it handles the half type
5017 // natively, and does not need to interwork with AAPCS code.
5018 if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
5019 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5020 llvm::Type::getFloatTy(getVMContext()) :
5021 llvm::Type::getInt32Ty(getVMContext());
5022 return ABIArgInfo::getDirect(ResType);
5023 }
5024
John McCalla1dee5302010-08-22 10:59:02 +00005025 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005026 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005027 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005028 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005029 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005030
Tim Northover5a1558e2014-11-07 22:30:50 +00005031 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5032 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005033 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005034
Oliver Stannard405bded2014-02-11 09:25:50 +00005035 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005036 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005037 }
Tim Northover1060eae2013-06-21 22:49:34 +00005038
Daniel Dunbar09d33622009-09-14 21:54:03 +00005039 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005040 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005041 return ABIArgInfo::getIgnore();
5042
Tim Northover5a1558e2014-11-07 22:30:50 +00005043 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005044 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5045 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005046 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005047 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005048 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005049 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005050 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005051 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005052 }
Tim Northover5627d392015-10-30 16:30:45 +00005053 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5054 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5055 // this convention even for a variadic function: the backend will use GPRs
5056 // if needed.
5057 const Type *Base = nullptr;
5058 uint64_t Members = 0;
5059 if (isHomogeneousAggregate(Ty, Base, Members)) {
5060 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5061 llvm::Type *Ty =
5062 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5063 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5064 }
5065 }
5066
5067 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5068 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5069 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5070 // bigger than 128-bits, they get placed in space allocated by the caller,
5071 // and a pointer is passed.
5072 return ABIArgInfo::getIndirect(
5073 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005074 }
5075
Manman Ren6c30e132012-08-13 21:23:55 +00005076 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005077 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5078 // most 8-byte. We realign the indirect argument if type alignment is bigger
5079 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005080 uint64_t ABIAlign = 4;
5081 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5082 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005083 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005084 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005085
Manman Ren8cd99812012-11-06 04:58:01 +00005086 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005087 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005088 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5089 /*ByVal=*/true,
5090 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005091 }
5092
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005093 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005094 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005095 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005096 // FIXME: Try to match the types of the arguments more accurately where
5097 // we can.
5098 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005099 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5100 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005101 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005102 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5103 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005104 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005105
Tim Northover5a1558e2014-11-07 22:30:50 +00005106 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005107}
5108
Chris Lattner458b2aa2010-07-29 02:16:43 +00005109static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005110 llvm::LLVMContext &VMContext) {
5111 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5112 // is called integer-like if its size is less than or equal to one word, and
5113 // the offset of each of its addressable sub-fields is zero.
5114
5115 uint64_t Size = Context.getTypeSize(Ty);
5116
5117 // Check that the type fits in a word.
5118 if (Size > 32)
5119 return false;
5120
5121 // FIXME: Handle vector types!
5122 if (Ty->isVectorType())
5123 return false;
5124
Daniel Dunbard53bac72009-09-14 02:20:34 +00005125 // Float types are never treated as "integer like".
5126 if (Ty->isRealFloatingType())
5127 return false;
5128
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005129 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005130 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005131 return true;
5132
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005133 // Small complex integer types are "integer like".
5134 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5135 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005136
5137 // Single element and zero sized arrays should be allowed, by the definition
5138 // above, but they are not.
5139
5140 // Otherwise, it must be a record type.
5141 const RecordType *RT = Ty->getAs<RecordType>();
5142 if (!RT) return false;
5143
5144 // Ignore records with flexible arrays.
5145 const RecordDecl *RD = RT->getDecl();
5146 if (RD->hasFlexibleArrayMember())
5147 return false;
5148
5149 // Check that all sub-fields are at offset 0, and are themselves "integer
5150 // like".
5151 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5152
5153 bool HadField = false;
5154 unsigned idx = 0;
5155 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5156 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005157 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005158
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005159 // Bit-fields are not addressable, we only need to verify they are "integer
5160 // like". We still have to disallow a subsequent non-bitfield, for example:
5161 // struct { int : 0; int x }
5162 // is non-integer like according to gcc.
5163 if (FD->isBitField()) {
5164 if (!RD->isUnion())
5165 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005166
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005167 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5168 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005169
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005170 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005171 }
5172
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005173 // Check if this field is at offset 0.
5174 if (Layout.getFieldOffset(idx) != 0)
5175 return false;
5176
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005177 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5178 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005179
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005180 // Only allow at most one field in a structure. This doesn't match the
5181 // wording above, but follows gcc in situations with a field following an
5182 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005183 if (!RD->isUnion()) {
5184 if (HadField)
5185 return false;
5186
5187 HadField = true;
5188 }
5189 }
5190
5191 return true;
5192}
5193
Oliver Stannard405bded2014-02-11 09:25:50 +00005194ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5195 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005196 bool IsEffectivelyAAPCS_VFP =
5197 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005198
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005199 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005200 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005201
Daniel Dunbar19964db2010-09-23 01:54:32 +00005202 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005203 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005204 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005205 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005206
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005207 // __fp16 gets returned as if it were an int or float, but with the top 16
5208 // bits unspecified. This is not done for OpenCL as it handles the half type
5209 // natively, and does not need to interwork with AAPCS code.
5210 if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
5211 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5212 llvm::Type::getFloatTy(getVMContext()) :
5213 llvm::Type::getInt32Ty(getVMContext());
5214 return ABIArgInfo::getDirect(ResType);
5215 }
5216
John McCalla1dee5302010-08-22 10:59:02 +00005217 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005218 // Treat an enum type as its underlying type.
5219 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5220 RetTy = EnumTy->getDecl()->getIntegerType();
5221
Tim Northover5a1558e2014-11-07 22:30:50 +00005222 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5223 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005224 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005225
5226 // Are we following APCS?
5227 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005228 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005229 return ABIArgInfo::getIgnore();
5230
Daniel Dunbareedf1512010-02-01 23:31:19 +00005231 // Complex types are all returned as packed integers.
5232 //
5233 // FIXME: Consider using 2 x vector types if the back end handles them
5234 // correctly.
5235 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005236 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5237 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005238
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005239 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005240 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005241 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005242 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005243 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005244 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005245 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005246 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5247 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005248 }
5249
5250 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005251 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005252 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005253
5254 // Otherwise this is an AAPCS variant.
5255
Chris Lattner458b2aa2010-07-29 02:16:43 +00005256 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005257 return ABIArgInfo::getIgnore();
5258
Bob Wilson1d9269a2011-11-02 04:51:36 +00005259 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005260 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005261 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005262 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005263 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005264 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005265 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005266 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005267 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005268 }
5269
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005270 // Aggregates <= 4 bytes are returned in r0; other aggregates
5271 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005272 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005273 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005274 if (getDataLayout().isBigEndian())
5275 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005276 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005277
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005278 // Return in the smallest viable integer type.
5279 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005280 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005281 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005282 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5283 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005284 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5285 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5286 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005287 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005288 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005289 }
5290
John McCall7f416cc2015-09-08 08:05:57 +00005291 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005292}
5293
Manman Renfef9e312012-10-16 19:18:39 +00005294/// isIllegalVector - check whether Ty is an illegal vector type.
5295bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005296 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5297 if (isAndroid()) {
5298 // Android shipped using Clang 3.1, which supported a slightly different
5299 // vector ABI. The primary differences were that 3-element vector types
5300 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5301 // accepts that legacy behavior for Android only.
5302 // Check whether VT is legal.
5303 unsigned NumElements = VT->getNumElements();
5304 // NumElements should be power of 2 or equal to 3.
5305 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5306 return true;
5307 } else {
5308 // Check whether VT is legal.
5309 unsigned NumElements = VT->getNumElements();
5310 uint64_t Size = getContext().getTypeSize(VT);
5311 // NumElements should be power of 2.
5312 if (!llvm::isPowerOf2_32(NumElements))
5313 return true;
5314 // Size should be greater than 32 bits.
5315 return Size <= 32;
5316 }
Manman Renfef9e312012-10-16 19:18:39 +00005317 }
5318 return false;
5319}
5320
Reid Klecknere9f6a712014-10-31 17:10:41 +00005321bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5322 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5323 // double, or 64-bit or 128-bit vectors.
5324 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5325 if (BT->getKind() == BuiltinType::Float ||
5326 BT->getKind() == BuiltinType::Double ||
5327 BT->getKind() == BuiltinType::LongDouble)
5328 return true;
5329 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5330 unsigned VecSize = getContext().getTypeSize(VT);
5331 if (VecSize == 64 || VecSize == 128)
5332 return true;
5333 }
5334 return false;
5335}
5336
5337bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5338 uint64_t Members) const {
5339 return Members <= 4;
5340}
5341
John McCall7f416cc2015-09-08 08:05:57 +00005342Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5343 QualType Ty) const {
5344 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005345
John McCall7f416cc2015-09-08 08:05:57 +00005346 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005347 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005348 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5349 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5350 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005351 }
5352
John McCall7f416cc2015-09-08 08:05:57 +00005353 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5354 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005355
John McCall7f416cc2015-09-08 08:05:57 +00005356 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5357 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005358 const Type *Base = nullptr;
5359 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005360 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5361 IsIndirect = true;
5362
Tim Northover5627d392015-10-30 16:30:45 +00005363 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5364 // allocated by the caller.
5365 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5366 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5367 !isHomogeneousAggregate(Ty, Base, Members)) {
5368 IsIndirect = true;
5369
John McCall7f416cc2015-09-08 08:05:57 +00005370 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005371 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5372 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005373 // Our callers should be prepared to handle an under-aligned address.
5374 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5375 getABIKind() == ARMABIInfo::AAPCS) {
5376 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5377 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005378 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5379 // ARMv7k allows type alignment up to 16 bytes.
5380 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5381 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005382 } else {
5383 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005384 }
John McCall7f416cc2015-09-08 08:05:57 +00005385 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005386
John McCall7f416cc2015-09-08 08:05:57 +00005387 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5388 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005389}
5390
Chris Lattner0cf24192010-06-28 20:05:43 +00005391//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005392// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005393//===----------------------------------------------------------------------===//
5394
5395namespace {
5396
Justin Holewinski83e96682012-05-24 17:43:12 +00005397class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005398public:
Justin Holewinski36837432013-03-30 14:38:24 +00005399 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005400
5401 ABIArgInfo classifyReturnType(QualType RetTy) const;
5402 ABIArgInfo classifyArgumentType(QualType Ty) const;
5403
Craig Topper4f12f102014-03-12 06:41:41 +00005404 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005405 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5406 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005407};
5408
Justin Holewinski83e96682012-05-24 17:43:12 +00005409class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005410public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005411 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5412 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005413
Eric Christopher162c91c2015-06-05 22:03:00 +00005414 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005415 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005416private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005417 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5418 // resulting MDNode to the nvvm.annotations MDNode.
5419 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005420};
5421
Justin Holewinski83e96682012-05-24 17:43:12 +00005422ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005423 if (RetTy->isVoidType())
5424 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005425
5426 // note: this is different from default ABI
5427 if (!RetTy->isScalarType())
5428 return ABIArgInfo::getDirect();
5429
5430 // Treat an enum type as its underlying type.
5431 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5432 RetTy = EnumTy->getDecl()->getIntegerType();
5433
5434 return (RetTy->isPromotableIntegerType() ?
5435 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005436}
5437
Justin Holewinski83e96682012-05-24 17:43:12 +00005438ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005439 // Treat an enum type as its underlying type.
5440 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5441 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005442
Eli Bendersky95338a02014-10-29 13:43:21 +00005443 // Return aggregates type as indirect by value
5444 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005445 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005446
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005447 return (Ty->isPromotableIntegerType() ?
5448 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005449}
5450
Justin Holewinski83e96682012-05-24 17:43:12 +00005451void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005452 if (!getCXXABI().classifyReturnType(FI))
5453 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005454 for (auto &I : FI.arguments())
5455 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005456
5457 // Always honor user-specified calling convention.
5458 if (FI.getCallingConvention() != llvm::CallingConv::C)
5459 return;
5460
John McCall882987f2013-02-28 19:01:20 +00005461 FI.setEffectiveCallingConvention(getRuntimeCC());
5462}
5463
John McCall7f416cc2015-09-08 08:05:57 +00005464Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5465 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005466 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005467}
5468
Justin Holewinski83e96682012-05-24 17:43:12 +00005469void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005470setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005471 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005472 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005473 if (!FD) return;
5474
5475 llvm::Function *F = cast<llvm::Function>(GV);
5476
5477 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005478 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005479 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005480 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005481 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005482 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005483 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5484 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005485 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005486 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005487 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005488 }
Justin Holewinski38031972011-10-05 17:58:44 +00005489
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005490 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005491 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005492 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005493 // __global__ functions cannot be called from the device, we do not
5494 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005495 if (FD->hasAttr<CUDAGlobalAttr>()) {
5496 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5497 addNVVMMetadata(F, "kernel", 1);
5498 }
Artem Belevich7093e402015-04-21 22:55:54 +00005499 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005500 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005501 llvm::APSInt MaxThreads(32);
5502 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5503 if (MaxThreads > 0)
5504 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5505
5506 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5507 // not specified in __launch_bounds__ or if the user specified a 0 value,
5508 // we don't have to add a PTX directive.
5509 if (Attr->getMinBlocks()) {
5510 llvm::APSInt MinBlocks(32);
5511 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5512 if (MinBlocks > 0)
5513 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5514 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005515 }
5516 }
Justin Holewinski38031972011-10-05 17:58:44 +00005517 }
5518}
5519
Eli Benderskye06a2c42014-04-15 16:57:05 +00005520void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5521 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005522 llvm::Module *M = F->getParent();
5523 llvm::LLVMContext &Ctx = M->getContext();
5524
5525 // Get "nvvm.annotations" metadata node
5526 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5527
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005528 llvm::Metadata *MDVals[] = {
5529 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5530 llvm::ConstantAsMetadata::get(
5531 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005532 // Append metadata to nvvm.annotations
5533 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5534}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005535}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005536
5537//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005538// SystemZ ABI Implementation
5539//===----------------------------------------------------------------------===//
5540
5541namespace {
5542
5543class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005544 bool HasVector;
5545
Ulrich Weigand47445072013-05-06 16:26:41 +00005546public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005547 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5548 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005549
5550 bool isPromotableIntegerType(QualType Ty) const;
5551 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005552 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005553 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005554 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005555
5556 ABIArgInfo classifyReturnType(QualType RetTy) const;
5557 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5558
Craig Topper4f12f102014-03-12 06:41:41 +00005559 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005560 if (!getCXXABI().classifyReturnType(FI))
5561 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005562 for (auto &I : FI.arguments())
5563 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005564 }
5565
John McCall7f416cc2015-09-08 08:05:57 +00005566 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5567 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005568};
5569
5570class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5571public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005572 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5573 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005574};
5575
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005576}
Ulrich Weigand47445072013-05-06 16:26:41 +00005577
5578bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5579 // Treat an enum type as its underlying type.
5580 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5581 Ty = EnumTy->getDecl()->getIntegerType();
5582
5583 // Promotable integer types are required to be promoted by the ABI.
5584 if (Ty->isPromotableIntegerType())
5585 return true;
5586
5587 // 32-bit values must also be promoted.
5588 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5589 switch (BT->getKind()) {
5590 case BuiltinType::Int:
5591 case BuiltinType::UInt:
5592 return true;
5593 default:
5594 return false;
5595 }
5596 return false;
5597}
5598
5599bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005600 return (Ty->isAnyComplexType() ||
5601 Ty->isVectorType() ||
5602 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005603}
5604
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005605bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5606 return (HasVector &&
5607 Ty->isVectorType() &&
5608 getContext().getTypeSize(Ty) <= 128);
5609}
5610
Ulrich Weigand47445072013-05-06 16:26:41 +00005611bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5612 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5613 switch (BT->getKind()) {
5614 case BuiltinType::Float:
5615 case BuiltinType::Double:
5616 return true;
5617 default:
5618 return false;
5619 }
5620
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005621 return false;
5622}
5623
5624QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005625 if (const RecordType *RT = Ty->getAsStructureType()) {
5626 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005627 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005628
5629 // If this is a C++ record, check the bases first.
5630 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005631 for (const auto &I : CXXRD->bases()) {
5632 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005633
5634 // Empty bases don't affect things either way.
5635 if (isEmptyRecord(getContext(), Base, true))
5636 continue;
5637
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005638 if (!Found.isNull())
5639 return Ty;
5640 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005641 }
5642
5643 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005644 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005645 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005646 // Unlike isSingleElementStruct(), empty structure and array fields
5647 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005648 if (getContext().getLangOpts().CPlusPlus &&
5649 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5650 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005651
5652 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005653 // Nested structures still do though.
5654 if (!Found.isNull())
5655 return Ty;
5656 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005657 }
5658
5659 // Unlike isSingleElementStruct(), trailing padding is allowed.
5660 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005661 if (!Found.isNull())
5662 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005663 }
5664
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005665 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005666}
5667
John McCall7f416cc2015-09-08 08:05:57 +00005668Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5669 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005670 // Assume that va_list type is correct; should be pointer to LLVM type:
5671 // struct {
5672 // i64 __gpr;
5673 // i64 __fpr;
5674 // i8 *__overflow_arg_area;
5675 // i8 *__reg_save_area;
5676 // };
5677
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005678 // Every non-vector argument occupies 8 bytes and is passed by preference
5679 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5680 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005681 Ty = getContext().getCanonicalType(Ty);
5682 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005683 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005684 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005685 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005686 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005687 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005688 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005689 CharUnits UnpaddedSize;
5690 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005691 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005692 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5693 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005694 } else {
5695 if (AI.getCoerceToType())
5696 ArgTy = AI.getCoerceToType();
5697 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005698 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005699 UnpaddedSize = TyInfo.first;
5700 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005701 }
John McCall7f416cc2015-09-08 08:05:57 +00005702 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5703 if (IsVector && UnpaddedSize > PaddedSize)
5704 PaddedSize = CharUnits::fromQuantity(16);
5705 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005706
John McCall7f416cc2015-09-08 08:05:57 +00005707 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005708
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005709 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005710 llvm::Value *PaddedSizeV =
5711 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005712
5713 if (IsVector) {
5714 // Work out the address of a vector argument on the stack.
5715 // Vector arguments are always passed in the high bits of a
5716 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005717 Address OverflowArgAreaPtr =
5718 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005719 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005720 Address OverflowArgArea =
5721 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5722 TyInfo.second);
5723 Address MemAddr =
5724 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005725
5726 // Update overflow_arg_area_ptr pointer
5727 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005728 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5729 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005730 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5731
5732 return MemAddr;
5733 }
5734
John McCall7f416cc2015-09-08 08:05:57 +00005735 assert(PaddedSize.getQuantity() == 8);
5736
5737 unsigned MaxRegs, RegCountField, RegSaveIndex;
5738 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005739 if (InFPRs) {
5740 MaxRegs = 4; // Maximum of 4 FPR arguments
5741 RegCountField = 1; // __fpr
5742 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005743 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005744 } else {
5745 MaxRegs = 5; // Maximum of 5 GPR arguments
5746 RegCountField = 0; // __gpr
5747 RegSaveIndex = 2; // save offset for r2
5748 RegPadding = Padding; // values are passed in the low bits of a GPR
5749 }
5750
John McCall7f416cc2015-09-08 08:05:57 +00005751 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5752 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5753 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005754 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005755 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5756 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005757 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005758
5759 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5760 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5761 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5762 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5763
5764 // Emit code to load the value if it was passed in registers.
5765 CGF.EmitBlock(InRegBlock);
5766
5767 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005768 llvm::Value *ScaledRegCount =
5769 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5770 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005771 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5772 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005773 llvm::Value *RegOffset =
5774 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005775 Address RegSaveAreaPtr =
5776 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5777 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005778 llvm::Value *RegSaveArea =
5779 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005780 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5781 "raw_reg_addr"),
5782 PaddedSize);
5783 Address RegAddr =
5784 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005785
5786 // Update the register count
5787 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5788 llvm::Value *NewRegCount =
5789 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5790 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5791 CGF.EmitBranch(ContBlock);
5792
5793 // Emit code to load the value if it was passed in memory.
5794 CGF.EmitBlock(InMemBlock);
5795
5796 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005797 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5798 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5799 Address OverflowArgArea =
5800 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5801 PaddedSize);
5802 Address RawMemAddr =
5803 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5804 Address MemAddr =
5805 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005806
5807 // Update overflow_arg_area_ptr pointer
5808 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005809 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5810 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005811 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5812 CGF.EmitBranch(ContBlock);
5813
5814 // Return the appropriate result.
5815 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005816 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5817 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005818
5819 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005820 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5821 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005822
5823 return ResAddr;
5824}
5825
Ulrich Weigand47445072013-05-06 16:26:41 +00005826ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5827 if (RetTy->isVoidType())
5828 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005829 if (isVectorArgumentType(RetTy))
5830 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005831 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00005832 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005833 return (isPromotableIntegerType(RetTy) ?
5834 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5835}
5836
5837ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5838 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005839 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00005840 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00005841
5842 // Integers and enums are extended to full register width.
5843 if (isPromotableIntegerType(Ty))
5844 return ABIArgInfo::getExtend();
5845
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005846 // Handle vector types and vector-like structure types. Note that
5847 // as opposed to float-like structure types, we do not allow any
5848 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005849 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005850 QualType SingleElementTy = GetSingleElementType(Ty);
5851 if (isVectorArgumentType(SingleElementTy) &&
5852 getContext().getTypeSize(SingleElementTy) == Size)
5853 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5854
5855 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005856 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00005857 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005858
5859 // Handle small structures.
5860 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5861 // Structures with flexible arrays have variable length, so really
5862 // fail the size test above.
5863 const RecordDecl *RD = RT->getDecl();
5864 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00005865 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005866
5867 // The structure is passed as an unextended integer, a float, or a double.
5868 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005869 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005870 assert(Size == 32 || Size == 64);
5871 if (Size == 32)
5872 PassTy = llvm::Type::getFloatTy(getVMContext());
5873 else
5874 PassTy = llvm::Type::getDoubleTy(getVMContext());
5875 } else
5876 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5877 return ABIArgInfo::getDirect(PassTy);
5878 }
5879
5880 // Non-structure compounds are passed indirectly.
5881 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005882 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005883
Craig Topper8a13c412014-05-21 05:09:00 +00005884 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005885}
5886
5887//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005888// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005889//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005890
5891namespace {
5892
5893class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5894public:
Chris Lattner2b037972010-07-29 02:01:43 +00005895 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5896 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005897 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005898 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005899};
5900
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005901}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005902
Eric Christopher162c91c2015-06-05 22:03:00 +00005903void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005904 llvm::GlobalValue *GV,
5905 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005906 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005907 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5908 // Handle 'interrupt' attribute:
5909 llvm::Function *F = cast<llvm::Function>(GV);
5910
5911 // Step 1: Set ISR calling convention.
5912 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5913
5914 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005915 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005916
5917 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005918 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005919 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5920 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005921 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005922 }
5923}
5924
Chris Lattner0cf24192010-06-28 20:05:43 +00005925//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005926// MIPS ABI Implementation. This works for both little-endian and
5927// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005928//===----------------------------------------------------------------------===//
5929
John McCall943fae92010-05-27 06:19:26 +00005930namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005931class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005932 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005933 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5934 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005935 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005936 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005937 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005938 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005939public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005940 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005941 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005942 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005943
5944 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005945 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005946 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005947 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5948 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005949 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005950};
5951
John McCall943fae92010-05-27 06:19:26 +00005952class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005953 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005954public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005955 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5956 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005957 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005958
Craig Topper4f12f102014-03-12 06:41:41 +00005959 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005960 return 29;
5961 }
5962
Eric Christopher162c91c2015-06-05 22:03:00 +00005963 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005964 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005965 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005966 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005967 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005968 if (FD->hasAttr<Mips16Attr>()) {
5969 Fn->addFnAttr("mips16");
5970 }
5971 else if (FD->hasAttr<NoMips16Attr>()) {
5972 Fn->addFnAttr("nomips16");
5973 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005974
5975 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
5976 if (!Attr)
5977 return;
5978
5979 const char *Kind;
5980 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005981 case MipsInterruptAttr::eic: Kind = "eic"; break;
5982 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
5983 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
5984 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
5985 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
5986 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
5987 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
5988 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
5989 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
5990 }
5991
5992 Fn->addFnAttr("interrupt", Kind);
5993
Reed Kotler373feca2013-01-16 17:10:28 +00005994 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005995
John McCall943fae92010-05-27 06:19:26 +00005996 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005997 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005998
Craig Topper4f12f102014-03-12 06:41:41 +00005999 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006000 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006001 }
John McCall943fae92010-05-27 06:19:26 +00006002};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006003}
John McCall943fae92010-05-27 06:19:26 +00006004
Eric Christopher7565e0d2015-05-29 23:09:49 +00006005void MipsABIInfo::CoerceToIntArgs(
6006 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006007 llvm::IntegerType *IntTy =
6008 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006009
6010 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6011 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6012 ArgList.push_back(IntTy);
6013
6014 // If necessary, add one more integer type to ArgList.
6015 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6016
6017 if (R)
6018 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006019}
6020
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006021// In N32/64, an aligned double precision floating point field is passed in
6022// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006023llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006024 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6025
6026 if (IsO32) {
6027 CoerceToIntArgs(TySize, ArgList);
6028 return llvm::StructType::get(getVMContext(), ArgList);
6029 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006030
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006031 if (Ty->isComplexType())
6032 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006033
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006034 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006035
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006036 // Unions/vectors are passed in integer registers.
6037 if (!RT || !RT->isStructureOrClassType()) {
6038 CoerceToIntArgs(TySize, ArgList);
6039 return llvm::StructType::get(getVMContext(), ArgList);
6040 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006041
6042 const RecordDecl *RD = RT->getDecl();
6043 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006044 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006045
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006046 uint64_t LastOffset = 0;
6047 unsigned idx = 0;
6048 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6049
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006050 // Iterate over fields in the struct/class and check if there are any aligned
6051 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006052 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6053 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006054 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006055 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6056
6057 if (!BT || BT->getKind() != BuiltinType::Double)
6058 continue;
6059
6060 uint64_t Offset = Layout.getFieldOffset(idx);
6061 if (Offset % 64) // Ignore doubles that are not aligned.
6062 continue;
6063
6064 // Add ((Offset - LastOffset) / 64) args of type i64.
6065 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6066 ArgList.push_back(I64);
6067
6068 // Add double type.
6069 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6070 LastOffset = Offset + 64;
6071 }
6072
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006073 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6074 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006075
6076 return llvm::StructType::get(getVMContext(), ArgList);
6077}
6078
Akira Hatanakaddd66342013-10-29 18:41:15 +00006079llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6080 uint64_t Offset) const {
6081 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006082 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006083
Akira Hatanakaddd66342013-10-29 18:41:15 +00006084 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006085}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006086
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006087ABIArgInfo
6088MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006089 Ty = useFirstFieldIfTransparentUnion(Ty);
6090
Akira Hatanaka1632af62012-01-09 19:31:25 +00006091 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006092 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006093 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006094
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006095 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6096 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006097 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6098 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006099
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006100 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006101 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006102 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006103 return ABIArgInfo::getIgnore();
6104
Mark Lacey3825e832013-10-06 01:33:34 +00006105 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006106 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006107 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006108 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006109
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006110 // If we have reached here, aggregates are passed directly by coercing to
6111 // another structure type. Padding is inserted if the offset of the
6112 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006113 ABIArgInfo ArgInfo =
6114 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6115 getPaddingType(OrigOffset, CurrOffset));
6116 ArgInfo.setInReg(true);
6117 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006118 }
6119
6120 // Treat an enum type as its underlying type.
6121 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6122 Ty = EnumTy->getDecl()->getIntegerType();
6123
Daniel Sanders5b445b32014-10-24 14:42:42 +00006124 // All integral types are promoted to the GPR width.
6125 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006126 return ABIArgInfo::getExtend();
6127
Akira Hatanakaddd66342013-10-29 18:41:15 +00006128 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006129 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006130}
6131
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006132llvm::Type*
6133MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006134 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006135 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006136
Akira Hatanakab6f74432012-02-09 18:49:26 +00006137 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006138 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006139 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6140 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006141
Akira Hatanakab6f74432012-02-09 18:49:26 +00006142 // N32/64 returns struct/classes in floating point registers if the
6143 // following conditions are met:
6144 // 1. The size of the struct/class is no larger than 128-bit.
6145 // 2. The struct/class has one or two fields all of which are floating
6146 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006147 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006148 //
6149 // Any other composite results are returned in integer registers.
6150 //
6151 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6152 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6153 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006154 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006155
Akira Hatanakab6f74432012-02-09 18:49:26 +00006156 if (!BT || !BT->isFloatingPoint())
6157 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006158
David Blaikie2d7c57e2012-04-30 02:36:29 +00006159 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006160 }
6161
6162 if (b == e)
6163 return llvm::StructType::get(getVMContext(), RTList,
6164 RD->hasAttr<PackedAttr>());
6165
6166 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006167 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006168 }
6169
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006170 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006171 return llvm::StructType::get(getVMContext(), RTList);
6172}
6173
Akira Hatanakab579fe52011-06-02 00:09:17 +00006174ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006175 uint64_t Size = getContext().getTypeSize(RetTy);
6176
Daniel Sandersed39f582014-09-04 13:28:14 +00006177 if (RetTy->isVoidType())
6178 return ABIArgInfo::getIgnore();
6179
6180 // O32 doesn't treat zero-sized structs differently from other structs.
6181 // However, N32/N64 ignores zero sized return values.
6182 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006183 return ABIArgInfo::getIgnore();
6184
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006185 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006186 if (Size <= 128) {
6187 if (RetTy->isAnyComplexType())
6188 return ABIArgInfo::getDirect();
6189
Daniel Sanderse5018b62014-09-04 15:05:39 +00006190 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006191 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006192 if (!IsO32 ||
6193 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6194 ABIArgInfo ArgInfo =
6195 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6196 ArgInfo.setInReg(true);
6197 return ArgInfo;
6198 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006199 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006200
John McCall7f416cc2015-09-08 08:05:57 +00006201 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006202 }
6203
6204 // Treat an enum type as its underlying type.
6205 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6206 RetTy = EnumTy->getDecl()->getIntegerType();
6207
6208 return (RetTy->isPromotableIntegerType() ?
6209 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6210}
6211
6212void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006213 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006214 if (!getCXXABI().classifyReturnType(FI))
6215 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006216
Eric Christopher7565e0d2015-05-29 23:09:49 +00006217 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006218 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006219
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006220 for (auto &I : FI.arguments())
6221 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006222}
6223
John McCall7f416cc2015-09-08 08:05:57 +00006224Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6225 QualType OrigTy) const {
6226 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006227
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006228 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6229 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006230 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006231 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006232 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006233 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006234 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006235 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006236 DidPromote = true;
6237 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6238 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006239 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006240
John McCall7f416cc2015-09-08 08:05:57 +00006241 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006242
John McCall7f416cc2015-09-08 08:05:57 +00006243 // The alignment of things in the argument area is never larger than
6244 // StackAlignInBytes.
6245 TyInfo.second =
6246 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6247
6248 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6249 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6250
6251 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6252 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6253
6254
6255 // If there was a promotion, "unpromote" into a temporary.
6256 // TODO: can we just use a pointer into a subset of the original slot?
6257 if (DidPromote) {
6258 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6259 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6260
6261 // Truncate down to the right width.
6262 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6263 : CGF.IntPtrTy);
6264 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6265 if (OrigTy->isPointerType())
6266 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6267
6268 CGF.Builder.CreateStore(V, Temp);
6269 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006270 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006271
John McCall7f416cc2015-09-08 08:05:57 +00006272 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006273}
6274
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006275bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6276 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006277
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006278 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6279 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6280 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006281
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006282 return false;
6283}
6284
John McCall943fae92010-05-27 06:19:26 +00006285bool
6286MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6287 llvm::Value *Address) const {
6288 // This information comes from gcc's implementation, which seems to
6289 // as canonical as it gets.
6290
John McCall943fae92010-05-27 06:19:26 +00006291 // Everything on MIPS is 4 bytes. Double-precision FP registers
6292 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006293 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006294
6295 // 0-31 are the general purpose registers, $0 - $31.
6296 // 32-63 are the floating-point registers, $f0 - $f31.
6297 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6298 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006299 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006300
6301 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6302 // They are one bit wide and ignored here.
6303
6304 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6305 // (coprocessor 1 is the FP unit)
6306 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6307 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6308 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006309 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006310 return false;
6311}
6312
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006313//===----------------------------------------------------------------------===//
6314// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006315// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006316// handling.
6317//===----------------------------------------------------------------------===//
6318
6319namespace {
6320
6321class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6322public:
6323 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6324 : DefaultTargetCodeGenInfo(CGT) {}
6325
Eric Christopher162c91c2015-06-05 22:03:00 +00006326 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006327 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006328};
6329
Eric Christopher162c91c2015-06-05 22:03:00 +00006330void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006331 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006332 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006333 if (!FD) return;
6334
6335 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006336
David Blaikiebbafb8a2012-03-11 07:00:24 +00006337 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006338 if (FD->hasAttr<OpenCLKernelAttr>()) {
6339 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006340 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006341 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6342 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006343 // Convert the reqd_work_group_size() attributes to metadata.
6344 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006345 llvm::NamedMDNode *OpenCLMetadata =
6346 M.getModule().getOrInsertNamedMetadata(
6347 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006348
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006349 SmallVector<llvm::Metadata *, 5> Operands;
6350 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006351
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006352 Operands.push_back(
6353 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6354 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6355 Operands.push_back(
6356 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6357 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6358 Operands.push_back(
6359 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6360 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006361
Eric Christopher7565e0d2015-05-29 23:09:49 +00006362 // Add a boolean constant operand for "required" (true) or "hint"
6363 // (false) for implementing the work_group_size_hint attr later.
6364 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006365 Operands.push_back(
6366 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006367 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6368 }
6369 }
6370 }
6371}
6372
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006373}
John McCall943fae92010-05-27 06:19:26 +00006374
Tony Linthicum76329bf2011-12-12 21:14:55 +00006375//===----------------------------------------------------------------------===//
6376// Hexagon ABI Implementation
6377//===----------------------------------------------------------------------===//
6378
6379namespace {
6380
6381class HexagonABIInfo : public ABIInfo {
6382
6383
6384public:
6385 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6386
6387private:
6388
6389 ABIArgInfo classifyReturnType(QualType RetTy) const;
6390 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6391
Craig Topper4f12f102014-03-12 06:41:41 +00006392 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006393
John McCall7f416cc2015-09-08 08:05:57 +00006394 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6395 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006396};
6397
6398class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6399public:
6400 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6401 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6402
Craig Topper4f12f102014-03-12 06:41:41 +00006403 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006404 return 29;
6405 }
6406};
6407
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006408}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006409
6410void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006411 if (!getCXXABI().classifyReturnType(FI))
6412 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006413 for (auto &I : FI.arguments())
6414 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006415}
6416
6417ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6418 if (!isAggregateTypeForABI(Ty)) {
6419 // Treat an enum type as its underlying type.
6420 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6421 Ty = EnumTy->getDecl()->getIntegerType();
6422
6423 return (Ty->isPromotableIntegerType() ?
6424 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6425 }
6426
6427 // Ignore empty records.
6428 if (isEmptyRecord(getContext(), Ty, true))
6429 return ABIArgInfo::getIgnore();
6430
Mark Lacey3825e832013-10-06 01:33:34 +00006431 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006432 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006433
6434 uint64_t Size = getContext().getTypeSize(Ty);
6435 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006436 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006437 // Pass in the smallest viable integer type.
6438 else if (Size > 32)
6439 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6440 else if (Size > 16)
6441 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6442 else if (Size > 8)
6443 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6444 else
6445 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6446}
6447
6448ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6449 if (RetTy->isVoidType())
6450 return ABIArgInfo::getIgnore();
6451
6452 // Large vector types should be returned via memory.
6453 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006454 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006455
6456 if (!isAggregateTypeForABI(RetTy)) {
6457 // Treat an enum type as its underlying type.
6458 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6459 RetTy = EnumTy->getDecl()->getIntegerType();
6460
6461 return (RetTy->isPromotableIntegerType() ?
6462 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6463 }
6464
Tony Linthicum76329bf2011-12-12 21:14:55 +00006465 if (isEmptyRecord(getContext(), RetTy, true))
6466 return ABIArgInfo::getIgnore();
6467
6468 // Aggregates <= 8 bytes are returned in r0; other aggregates
6469 // are returned indirectly.
6470 uint64_t Size = getContext().getTypeSize(RetTy);
6471 if (Size <= 64) {
6472 // Return in the smallest viable integer type.
6473 if (Size <= 8)
6474 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6475 if (Size <= 16)
6476 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6477 if (Size <= 32)
6478 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6479 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6480 }
6481
John McCall7f416cc2015-09-08 08:05:57 +00006482 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006483}
6484
John McCall7f416cc2015-09-08 08:05:57 +00006485Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6486 QualType Ty) const {
6487 // FIXME: Someone needs to audit that this handle alignment correctly.
6488 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6489 getContext().getTypeInfoInChars(Ty),
6490 CharUnits::fromQuantity(4),
6491 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006492}
6493
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006494//===----------------------------------------------------------------------===//
6495// AMDGPU ABI Implementation
6496//===----------------------------------------------------------------------===//
6497
6498namespace {
6499
6500class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6501public:
6502 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6503 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006504 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006505 CodeGen::CodeGenModule &M) const override;
6506};
6507
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006508}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006509
Eric Christopher162c91c2015-06-05 22:03:00 +00006510void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006511 const Decl *D,
6512 llvm::GlobalValue *GV,
6513 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006514 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006515 if (!FD)
6516 return;
6517
6518 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6519 llvm::Function *F = cast<llvm::Function>(GV);
6520 uint32_t NumVGPR = Attr->getNumVGPR();
6521 if (NumVGPR != 0)
6522 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6523 }
6524
6525 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6526 llvm::Function *F = cast<llvm::Function>(GV);
6527 unsigned NumSGPR = Attr->getNumSGPR();
6528 if (NumSGPR != 0)
6529 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6530 }
6531}
6532
Tony Linthicum76329bf2011-12-12 21:14:55 +00006533
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006534//===----------------------------------------------------------------------===//
6535// SPARC v9 ABI Implementation.
6536// Based on the SPARC Compliance Definition version 2.4.1.
6537//
6538// Function arguments a mapped to a nominal "parameter array" and promoted to
6539// registers depending on their type. Each argument occupies 8 or 16 bytes in
6540// the array, structs larger than 16 bytes are passed indirectly.
6541//
6542// One case requires special care:
6543//
6544// struct mixed {
6545// int i;
6546// float f;
6547// };
6548//
6549// When a struct mixed is passed by value, it only occupies 8 bytes in the
6550// parameter array, but the int is passed in an integer register, and the float
6551// is passed in a floating point register. This is represented as two arguments
6552// with the LLVM IR inreg attribute:
6553//
6554// declare void f(i32 inreg %i, float inreg %f)
6555//
6556// The code generator will only allocate 4 bytes from the parameter array for
6557// the inreg arguments. All other arguments are allocated a multiple of 8
6558// bytes.
6559//
6560namespace {
6561class SparcV9ABIInfo : public ABIInfo {
6562public:
6563 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6564
6565private:
6566 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006567 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006568 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6569 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006570
6571 // Coercion type builder for structs passed in registers. The coercion type
6572 // serves two purposes:
6573 //
6574 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6575 // in registers.
6576 // 2. Expose aligned floating point elements as first-level elements, so the
6577 // code generator knows to pass them in floating point registers.
6578 //
6579 // We also compute the InReg flag which indicates that the struct contains
6580 // aligned 32-bit floats.
6581 //
6582 struct CoerceBuilder {
6583 llvm::LLVMContext &Context;
6584 const llvm::DataLayout &DL;
6585 SmallVector<llvm::Type*, 8> Elems;
6586 uint64_t Size;
6587 bool InReg;
6588
6589 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6590 : Context(c), DL(dl), Size(0), InReg(false) {}
6591
6592 // Pad Elems with integers until Size is ToSize.
6593 void pad(uint64_t ToSize) {
6594 assert(ToSize >= Size && "Cannot remove elements");
6595 if (ToSize == Size)
6596 return;
6597
6598 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006599 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006600 if (Aligned > Size && Aligned <= ToSize) {
6601 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6602 Size = Aligned;
6603 }
6604
6605 // Add whole 64-bit words.
6606 while (Size + 64 <= ToSize) {
6607 Elems.push_back(llvm::Type::getInt64Ty(Context));
6608 Size += 64;
6609 }
6610
6611 // Final in-word padding.
6612 if (Size < ToSize) {
6613 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6614 Size = ToSize;
6615 }
6616 }
6617
6618 // Add a floating point element at Offset.
6619 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6620 // Unaligned floats are treated as integers.
6621 if (Offset % Bits)
6622 return;
6623 // The InReg flag is only required if there are any floats < 64 bits.
6624 if (Bits < 64)
6625 InReg = true;
6626 pad(Offset);
6627 Elems.push_back(Ty);
6628 Size = Offset + Bits;
6629 }
6630
6631 // Add a struct type to the coercion type, starting at Offset (in bits).
6632 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6633 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6634 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6635 llvm::Type *ElemTy = StrTy->getElementType(i);
6636 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6637 switch (ElemTy->getTypeID()) {
6638 case llvm::Type::StructTyID:
6639 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6640 break;
6641 case llvm::Type::FloatTyID:
6642 addFloat(ElemOffset, ElemTy, 32);
6643 break;
6644 case llvm::Type::DoubleTyID:
6645 addFloat(ElemOffset, ElemTy, 64);
6646 break;
6647 case llvm::Type::FP128TyID:
6648 addFloat(ElemOffset, ElemTy, 128);
6649 break;
6650 case llvm::Type::PointerTyID:
6651 if (ElemOffset % 64 == 0) {
6652 pad(ElemOffset);
6653 Elems.push_back(ElemTy);
6654 Size += 64;
6655 }
6656 break;
6657 default:
6658 break;
6659 }
6660 }
6661 }
6662
6663 // Check if Ty is a usable substitute for the coercion type.
6664 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006665 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006666 }
6667
6668 // Get the coercion type as a literal struct type.
6669 llvm::Type *getType() const {
6670 if (Elems.size() == 1)
6671 return Elems.front();
6672 else
6673 return llvm::StructType::get(Context, Elems);
6674 }
6675 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006676};
6677} // end anonymous namespace
6678
6679ABIArgInfo
6680SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6681 if (Ty->isVoidType())
6682 return ABIArgInfo::getIgnore();
6683
6684 uint64_t Size = getContext().getTypeSize(Ty);
6685
6686 // Anything too big to fit in registers is passed with an explicit indirect
6687 // pointer / sret pointer.
6688 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006689 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006690
6691 // Treat an enum type as its underlying type.
6692 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6693 Ty = EnumTy->getDecl()->getIntegerType();
6694
6695 // Integer types smaller than a register are extended.
6696 if (Size < 64 && Ty->isIntegerType())
6697 return ABIArgInfo::getExtend();
6698
6699 // Other non-aggregates go in registers.
6700 if (!isAggregateTypeForABI(Ty))
6701 return ABIArgInfo::getDirect();
6702
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006703 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6704 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6705 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006706 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006707
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006708 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006709 // Build a coercion type from the LLVM struct type.
6710 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6711 if (!StrTy)
6712 return ABIArgInfo::getDirect();
6713
6714 CoerceBuilder CB(getVMContext(), getDataLayout());
6715 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006716 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006717
6718 // Try to use the original type for coercion.
6719 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6720
6721 if (CB.InReg)
6722 return ABIArgInfo::getDirectInReg(CoerceTy);
6723 else
6724 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006725}
6726
John McCall7f416cc2015-09-08 08:05:57 +00006727Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6728 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006729 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6730 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6731 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6732 AI.setCoerceToType(ArgTy);
6733
John McCall7f416cc2015-09-08 08:05:57 +00006734 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006735
John McCall7f416cc2015-09-08 08:05:57 +00006736 CGBuilderTy &Builder = CGF.Builder;
6737 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6738 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6739
6740 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
6741
6742 Address ArgAddr = Address::invalid();
6743 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006744 switch (AI.getKind()) {
6745 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006746 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006747 llvm_unreachable("Unsupported ABI kind for va_arg");
6748
John McCall7f416cc2015-09-08 08:05:57 +00006749 case ABIArgInfo::Extend: {
6750 Stride = SlotSize;
6751 CharUnits Offset = SlotSize - TypeInfo.first;
6752 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006753 break;
John McCall7f416cc2015-09-08 08:05:57 +00006754 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006755
John McCall7f416cc2015-09-08 08:05:57 +00006756 case ABIArgInfo::Direct: {
6757 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00006758 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006759 ArgAddr = Addr;
6760 break;
John McCall7f416cc2015-09-08 08:05:57 +00006761 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006762
6763 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006764 Stride = SlotSize;
6765 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
6766 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
6767 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006768 break;
6769
6770 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006771 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006772 }
6773
6774 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006775 llvm::Value *NextPtr =
6776 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
6777 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006778
John McCall7f416cc2015-09-08 08:05:57 +00006779 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006780}
6781
6782void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6783 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006784 for (auto &I : FI.arguments())
6785 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006786}
6787
6788namespace {
6789class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6790public:
6791 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6792 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006793
Craig Topper4f12f102014-03-12 06:41:41 +00006794 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006795 return 14;
6796 }
6797
6798 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006799 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006800};
6801} // end anonymous namespace
6802
Roman Divackyf02c9942014-02-24 18:46:27 +00006803bool
6804SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6805 llvm::Value *Address) const {
6806 // This is calculated from the LLVM and GCC tables and verified
6807 // against gcc output. AFAIK all ABIs use the same encoding.
6808
6809 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6810
6811 llvm::IntegerType *i8 = CGF.Int8Ty;
6812 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6813 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6814
6815 // 0-31: the 8-byte general-purpose registers
6816 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6817
6818 // 32-63: f0-31, the 4-byte floating-point registers
6819 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6820
6821 // Y = 64
6822 // PSR = 65
6823 // WIM = 66
6824 // TBR = 67
6825 // PC = 68
6826 // NPC = 69
6827 // FSR = 70
6828 // CSR = 71
6829 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006830
Roman Divackyf02c9942014-02-24 18:46:27 +00006831 // 72-87: d0-15, the 8-byte floating-point registers
6832 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6833
6834 return false;
6835}
6836
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006837
Robert Lytton0e076492013-08-13 09:43:10 +00006838//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006839// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006840//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006841
Robert Lytton0e076492013-08-13 09:43:10 +00006842namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006843
6844/// A SmallStringEnc instance is used to build up the TypeString by passing
6845/// it by reference between functions that append to it.
6846typedef llvm::SmallString<128> SmallStringEnc;
6847
6848/// TypeStringCache caches the meta encodings of Types.
6849///
6850/// The reason for caching TypeStrings is two fold:
6851/// 1. To cache a type's encoding for later uses;
6852/// 2. As a means to break recursive member type inclusion.
6853///
6854/// A cache Entry can have a Status of:
6855/// NonRecursive: The type encoding is not recursive;
6856/// Recursive: The type encoding is recursive;
6857/// Incomplete: An incomplete TypeString;
6858/// IncompleteUsed: An incomplete TypeString that has been used in a
6859/// Recursive type encoding.
6860///
6861/// A NonRecursive entry will have all of its sub-members expanded as fully
6862/// as possible. Whilst it may contain types which are recursive, the type
6863/// itself is not recursive and thus its encoding may be safely used whenever
6864/// the type is encountered.
6865///
6866/// A Recursive entry will have all of its sub-members expanded as fully as
6867/// possible. The type itself is recursive and it may contain other types which
6868/// are recursive. The Recursive encoding must not be used during the expansion
6869/// of a recursive type's recursive branch. For simplicity the code uses
6870/// IncompleteCount to reject all usage of Recursive encodings for member types.
6871///
6872/// An Incomplete entry is always a RecordType and only encodes its
6873/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6874/// are placed into the cache during type expansion as a means to identify and
6875/// handle recursive inclusion of types as sub-members. If there is recursion
6876/// the entry becomes IncompleteUsed.
6877///
6878/// During the expansion of a RecordType's members:
6879///
6880/// If the cache contains a NonRecursive encoding for the member type, the
6881/// cached encoding is used;
6882///
6883/// If the cache contains a Recursive encoding for the member type, the
6884/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6885///
6886/// If the member is a RecordType, an Incomplete encoding is placed into the
6887/// cache to break potential recursive inclusion of itself as a sub-member;
6888///
6889/// Once a member RecordType has been expanded, its temporary incomplete
6890/// entry is removed from the cache. If a Recursive encoding was swapped out
6891/// it is swapped back in;
6892///
6893/// If an incomplete entry is used to expand a sub-member, the incomplete
6894/// entry is marked as IncompleteUsed. The cache keeps count of how many
6895/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6896///
6897/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6898/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6899/// Else the member is part of a recursive type and thus the recursion has
6900/// been exited too soon for the encoding to be correct for the member.
6901///
6902class TypeStringCache {
6903 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6904 struct Entry {
6905 std::string Str; // The encoded TypeString for the type.
6906 enum Status State; // Information about the encoding in 'Str'.
6907 std::string Swapped; // A temporary place holder for a Recursive encoding
6908 // during the expansion of RecordType's members.
6909 };
6910 std::map<const IdentifierInfo *, struct Entry> Map;
6911 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6912 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6913public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006914 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006915 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6916 bool removeIncomplete(const IdentifierInfo *ID);
6917 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6918 bool IsRecursive);
6919 StringRef lookupStr(const IdentifierInfo *ID);
6920};
6921
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006922/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006923/// FieldEncoding is a helper for this ordering process.
6924class FieldEncoding {
6925 bool HasName;
6926 std::string Enc;
6927public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006928 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6929 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006930 bool operator<(const FieldEncoding &rhs) const {
6931 if (HasName != rhs.HasName) return HasName;
6932 return Enc < rhs.Enc;
6933 }
6934};
6935
Robert Lytton7d1db152013-08-19 09:46:39 +00006936class XCoreABIInfo : public DefaultABIInfo {
6937public:
6938 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00006939 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6940 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006941};
6942
Robert Lyttond21e2d72014-03-03 13:45:29 +00006943class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006944 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006945public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006946 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006947 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006948 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6949 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006950};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006951
Robert Lytton2d196952013-10-11 10:29:34 +00006952} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006953
John McCall7f416cc2015-09-08 08:05:57 +00006954Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6955 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006956 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006957
Robert Lytton2d196952013-10-11 10:29:34 +00006958 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006959 CharUnits SlotSize = CharUnits::fromQuantity(4);
6960 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00006961
Robert Lytton2d196952013-10-11 10:29:34 +00006962 // Handle the argument.
6963 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006964 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00006965 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6966 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6967 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006968 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00006969
6970 Address Val = Address::invalid();
6971 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00006972 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006973 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006974 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006975 llvm_unreachable("Unsupported ABI kind for va_arg");
6976 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006977 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
6978 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00006979 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006980 case ABIArgInfo::Extend:
6981 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00006982 Val = Builder.CreateBitCast(AP, ArgPtrTy);
6983 ArgSize = CharUnits::fromQuantity(
6984 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00006985 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00006986 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006987 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006988 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
6989 Val = Address(Builder.CreateLoad(Val), TypeAlign);
6990 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00006991 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006992 }
Robert Lytton2d196952013-10-11 10:29:34 +00006993
6994 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006995 if (!ArgSize.isZero()) {
6996 llvm::Value *APN =
6997 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
6998 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006999 }
John McCall7f416cc2015-09-08 08:05:57 +00007000
Robert Lytton2d196952013-10-11 10:29:34 +00007001 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007002}
Robert Lytton0e076492013-08-13 09:43:10 +00007003
Robert Lytton844aeeb2014-05-02 09:33:20 +00007004/// During the expansion of a RecordType, an incomplete TypeString is placed
7005/// into the cache as a means to identify and break recursion.
7006/// If there is a Recursive encoding in the cache, it is swapped out and will
7007/// be reinserted by removeIncomplete().
7008/// All other types of encoding should have been used rather than arriving here.
7009void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7010 std::string StubEnc) {
7011 if (!ID)
7012 return;
7013 Entry &E = Map[ID];
7014 assert( (E.Str.empty() || E.State == Recursive) &&
7015 "Incorrectly use of addIncomplete");
7016 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7017 E.Swapped.swap(E.Str); // swap out the Recursive
7018 E.Str.swap(StubEnc);
7019 E.State = Incomplete;
7020 ++IncompleteCount;
7021}
7022
7023/// Once the RecordType has been expanded, the temporary incomplete TypeString
7024/// must be removed from the cache.
7025/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7026/// Returns true if the RecordType was defined recursively.
7027bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7028 if (!ID)
7029 return false;
7030 auto I = Map.find(ID);
7031 assert(I != Map.end() && "Entry not present");
7032 Entry &E = I->second;
7033 assert( (E.State == Incomplete ||
7034 E.State == IncompleteUsed) &&
7035 "Entry must be an incomplete type");
7036 bool IsRecursive = false;
7037 if (E.State == IncompleteUsed) {
7038 // We made use of our Incomplete encoding, thus we are recursive.
7039 IsRecursive = true;
7040 --IncompleteUsedCount;
7041 }
7042 if (E.Swapped.empty())
7043 Map.erase(I);
7044 else {
7045 // Swap the Recursive back.
7046 E.Swapped.swap(E.Str);
7047 E.Swapped.clear();
7048 E.State = Recursive;
7049 }
7050 --IncompleteCount;
7051 return IsRecursive;
7052}
7053
7054/// Add the encoded TypeString to the cache only if it is NonRecursive or
7055/// Recursive (viz: all sub-members were expanded as fully as possible).
7056void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7057 bool IsRecursive) {
7058 if (!ID || IncompleteUsedCount)
7059 return; // No key or it is is an incomplete sub-type so don't add.
7060 Entry &E = Map[ID];
7061 if (IsRecursive && !E.Str.empty()) {
7062 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7063 "This is not the same Recursive entry");
7064 // The parent container was not recursive after all, so we could have used
7065 // this Recursive sub-member entry after all, but we assumed the worse when
7066 // we started viz: IncompleteCount!=0.
7067 return;
7068 }
7069 assert(E.Str.empty() && "Entry already present");
7070 E.Str = Str.str();
7071 E.State = IsRecursive? Recursive : NonRecursive;
7072}
7073
7074/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7075/// are recursively expanding a type (IncompleteCount != 0) and the cached
7076/// encoding is Recursive, return an empty StringRef.
7077StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7078 if (!ID)
7079 return StringRef(); // We have no key.
7080 auto I = Map.find(ID);
7081 if (I == Map.end())
7082 return StringRef(); // We have no encoding.
7083 Entry &E = I->second;
7084 if (E.State == Recursive && IncompleteCount)
7085 return StringRef(); // We don't use Recursive encodings for member types.
7086
7087 if (E.State == Incomplete) {
7088 // The incomplete type is being used to break out of recursion.
7089 E.State = IncompleteUsed;
7090 ++IncompleteUsedCount;
7091 }
7092 return E.Str.c_str();
7093}
7094
7095/// The XCore ABI includes a type information section that communicates symbol
7096/// type information to the linker. The linker uses this information to verify
7097/// safety/correctness of things such as array bound and pointers et al.
7098/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7099/// This type information (TypeString) is emitted into meta data for all global
7100/// symbols: definitions, declarations, functions & variables.
7101///
7102/// The TypeString carries type, qualifier, name, size & value details.
7103/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007104/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007105/// The output is tested by test/CodeGen/xcore-stringtype.c.
7106///
7107static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7108 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7109
7110/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7111void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7112 CodeGen::CodeGenModule &CGM) const {
7113 SmallStringEnc Enc;
7114 if (getTypeString(Enc, D, CGM, TSC)) {
7115 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007116 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7117 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007118 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7119 llvm::NamedMDNode *MD =
7120 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7121 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7122 }
7123}
7124
7125static bool appendType(SmallStringEnc &Enc, QualType QType,
7126 const CodeGen::CodeGenModule &CGM,
7127 TypeStringCache &TSC);
7128
7129/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007130/// Builds a SmallVector containing the encoded field types in declaration
7131/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007132static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7133 const RecordDecl *RD,
7134 const CodeGen::CodeGenModule &CGM,
7135 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007136 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007137 SmallStringEnc Enc;
7138 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007139 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007140 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007141 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007142 Enc += "b(";
7143 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007144 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007145 Enc += ':';
7146 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007147 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007148 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007149 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007150 Enc += ')';
7151 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007152 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007153 }
7154 return true;
7155}
7156
7157/// Appends structure and union types to Enc and adds encoding to cache.
7158/// Recursively calls appendType (via extractFieldType) for each field.
7159/// Union types have their fields ordered according to the ABI.
7160static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7161 const CodeGen::CodeGenModule &CGM,
7162 TypeStringCache &TSC, const IdentifierInfo *ID) {
7163 // Append the cached TypeString if we have one.
7164 StringRef TypeString = TSC.lookupStr(ID);
7165 if (!TypeString.empty()) {
7166 Enc += TypeString;
7167 return true;
7168 }
7169
7170 // Start to emit an incomplete TypeString.
7171 size_t Start = Enc.size();
7172 Enc += (RT->isUnionType()? 'u' : 's');
7173 Enc += '(';
7174 if (ID)
7175 Enc += ID->getName();
7176 Enc += "){";
7177
7178 // We collect all encoded fields and order as necessary.
7179 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007180 const RecordDecl *RD = RT->getDecl()->getDefinition();
7181 if (RD && !RD->field_empty()) {
7182 // An incomplete TypeString stub is placed in the cache for this RecordType
7183 // so that recursive calls to this RecordType will use it whilst building a
7184 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007185 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007186 std::string StubEnc(Enc.substr(Start).str());
7187 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7188 TSC.addIncomplete(ID, std::move(StubEnc));
7189 if (!extractFieldType(FE, RD, CGM, TSC)) {
7190 (void) TSC.removeIncomplete(ID);
7191 return false;
7192 }
7193 IsRecursive = TSC.removeIncomplete(ID);
7194 // The ABI requires unions to be sorted but not structures.
7195 // See FieldEncoding::operator< for sort algorithm.
7196 if (RT->isUnionType())
7197 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007198 // We can now complete the TypeString.
7199 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007200 for (unsigned I = 0; I != E; ++I) {
7201 if (I)
7202 Enc += ',';
7203 Enc += FE[I].str();
7204 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007205 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007206 Enc += '}';
7207 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7208 return true;
7209}
7210
7211/// Appends enum types to Enc and adds the encoding to the cache.
7212static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7213 TypeStringCache &TSC,
7214 const IdentifierInfo *ID) {
7215 // Append the cached TypeString if we have one.
7216 StringRef TypeString = TSC.lookupStr(ID);
7217 if (!TypeString.empty()) {
7218 Enc += TypeString;
7219 return true;
7220 }
7221
7222 size_t Start = Enc.size();
7223 Enc += "e(";
7224 if (ID)
7225 Enc += ID->getName();
7226 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007227
7228 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007229 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007230 SmallVector<FieldEncoding, 16> FE;
7231 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7232 ++I) {
7233 SmallStringEnc EnumEnc;
7234 EnumEnc += "m(";
7235 EnumEnc += I->getName();
7236 EnumEnc += "){";
7237 I->getInitVal().toString(EnumEnc);
7238 EnumEnc += '}';
7239 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7240 }
7241 std::sort(FE.begin(), FE.end());
7242 unsigned E = FE.size();
7243 for (unsigned I = 0; I != E; ++I) {
7244 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007245 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007246 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007247 }
7248 }
7249 Enc += '}';
7250 TSC.addIfComplete(ID, Enc.substr(Start), false);
7251 return true;
7252}
7253
7254/// Appends type's qualifier to Enc.
7255/// This is done prior to appending the type's encoding.
7256static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7257 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007258 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007259 int Lookup = 0;
7260 if (QT.isConstQualified())
7261 Lookup += 1<<0;
7262 if (QT.isRestrictQualified())
7263 Lookup += 1<<1;
7264 if (QT.isVolatileQualified())
7265 Lookup += 1<<2;
7266 Enc += Table[Lookup];
7267}
7268
7269/// Appends built-in types to Enc.
7270static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7271 const char *EncType;
7272 switch (BT->getKind()) {
7273 case BuiltinType::Void:
7274 EncType = "0";
7275 break;
7276 case BuiltinType::Bool:
7277 EncType = "b";
7278 break;
7279 case BuiltinType::Char_U:
7280 EncType = "uc";
7281 break;
7282 case BuiltinType::UChar:
7283 EncType = "uc";
7284 break;
7285 case BuiltinType::SChar:
7286 EncType = "sc";
7287 break;
7288 case BuiltinType::UShort:
7289 EncType = "us";
7290 break;
7291 case BuiltinType::Short:
7292 EncType = "ss";
7293 break;
7294 case BuiltinType::UInt:
7295 EncType = "ui";
7296 break;
7297 case BuiltinType::Int:
7298 EncType = "si";
7299 break;
7300 case BuiltinType::ULong:
7301 EncType = "ul";
7302 break;
7303 case BuiltinType::Long:
7304 EncType = "sl";
7305 break;
7306 case BuiltinType::ULongLong:
7307 EncType = "ull";
7308 break;
7309 case BuiltinType::LongLong:
7310 EncType = "sll";
7311 break;
7312 case BuiltinType::Float:
7313 EncType = "ft";
7314 break;
7315 case BuiltinType::Double:
7316 EncType = "d";
7317 break;
7318 case BuiltinType::LongDouble:
7319 EncType = "ld";
7320 break;
7321 default:
7322 return false;
7323 }
7324 Enc += EncType;
7325 return true;
7326}
7327
7328/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7329static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7330 const CodeGen::CodeGenModule &CGM,
7331 TypeStringCache &TSC) {
7332 Enc += "p(";
7333 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7334 return false;
7335 Enc += ')';
7336 return true;
7337}
7338
7339/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007340static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7341 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007342 const CodeGen::CodeGenModule &CGM,
7343 TypeStringCache &TSC, StringRef NoSizeEnc) {
7344 if (AT->getSizeModifier() != ArrayType::Normal)
7345 return false;
7346 Enc += "a(";
7347 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7348 CAT->getSize().toStringUnsigned(Enc);
7349 else
7350 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7351 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007352 // The Qualifiers should be attached to the type rather than the array.
7353 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007354 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7355 return false;
7356 Enc += ')';
7357 return true;
7358}
7359
7360/// Appends a function encoding to Enc, calling appendType for the return type
7361/// and the arguments.
7362static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7363 const CodeGen::CodeGenModule &CGM,
7364 TypeStringCache &TSC) {
7365 Enc += "f{";
7366 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7367 return false;
7368 Enc += "}(";
7369 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7370 // N.B. we are only interested in the adjusted param types.
7371 auto I = FPT->param_type_begin();
7372 auto E = FPT->param_type_end();
7373 if (I != E) {
7374 do {
7375 if (!appendType(Enc, *I, CGM, TSC))
7376 return false;
7377 ++I;
7378 if (I != E)
7379 Enc += ',';
7380 } while (I != E);
7381 if (FPT->isVariadic())
7382 Enc += ",va";
7383 } else {
7384 if (FPT->isVariadic())
7385 Enc += "va";
7386 else
7387 Enc += '0';
7388 }
7389 }
7390 Enc += ')';
7391 return true;
7392}
7393
7394/// Handles the type's qualifier before dispatching a call to handle specific
7395/// type encodings.
7396static bool appendType(SmallStringEnc &Enc, QualType QType,
7397 const CodeGen::CodeGenModule &CGM,
7398 TypeStringCache &TSC) {
7399
7400 QualType QT = QType.getCanonicalType();
7401
Robert Lytton6adb20f2014-06-05 09:06:21 +00007402 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7403 // The Qualifiers should be attached to the type rather than the array.
7404 // Thus we don't call appendQualifier() here.
7405 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7406
Robert Lytton844aeeb2014-05-02 09:33:20 +00007407 appendQualifier(Enc, QT);
7408
7409 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7410 return appendBuiltinType(Enc, BT);
7411
Robert Lytton844aeeb2014-05-02 09:33:20 +00007412 if (const PointerType *PT = QT->getAs<PointerType>())
7413 return appendPointerType(Enc, PT, CGM, TSC);
7414
7415 if (const EnumType *ET = QT->getAs<EnumType>())
7416 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7417
7418 if (const RecordType *RT = QT->getAsStructureType())
7419 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7420
7421 if (const RecordType *RT = QT->getAsUnionType())
7422 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7423
7424 if (const FunctionType *FT = QT->getAs<FunctionType>())
7425 return appendFunctionType(Enc, FT, CGM, TSC);
7426
7427 return false;
7428}
7429
7430static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7431 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7432 if (!D)
7433 return false;
7434
7435 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7436 if (FD->getLanguageLinkage() != CLanguageLinkage)
7437 return false;
7438 return appendType(Enc, FD->getType(), CGM, TSC);
7439 }
7440
7441 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7442 if (VD->getLanguageLinkage() != CLanguageLinkage)
7443 return false;
7444 QualType QT = VD->getType().getCanonicalType();
7445 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7446 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007447 // The Qualifiers should be attached to the type rather than the array.
7448 // Thus we don't call appendQualifier() here.
7449 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007450 }
7451 return appendType(Enc, QT, CGM, TSC);
7452 }
7453 return false;
7454}
7455
7456
Robert Lytton0e076492013-08-13 09:43:10 +00007457//===----------------------------------------------------------------------===//
7458// Driver code
7459//===----------------------------------------------------------------------===//
7460
Rafael Espindola9f834732014-09-19 01:54:22 +00007461const llvm::Triple &CodeGenModule::getTriple() const {
7462 return getTarget().getTriple();
7463}
7464
7465bool CodeGenModule::supportsCOMDAT() const {
7466 return !getTriple().isOSBinFormatMachO();
7467}
7468
Chris Lattner2b037972010-07-29 02:01:43 +00007469const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007470 if (TheTargetCodeGenInfo)
7471 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007472
John McCallc8e01702013-04-16 22:48:15 +00007473 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007474 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007475 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007476 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007477
Derek Schuff09338a22012-09-06 17:37:28 +00007478 case llvm::Triple::le32:
7479 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007480 case llvm::Triple::mips:
7481 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007482 if (Triple.getOS() == llvm::Triple::NaCl)
7483 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007484 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7485
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007486 case llvm::Triple::mips64:
7487 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007488 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7489
Tim Northover25e8a672014-05-24 12:51:25 +00007490 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007491 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007492 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007493 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007494 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007495
Tim Northover573cbee2014-05-24 12:52:07 +00007496 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007497 }
7498
Dan Gohmanc2853072015-09-03 22:51:53 +00007499 case llvm::Triple::wasm32:
7500 case llvm::Triple::wasm64:
7501 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7502
Daniel Dunbard59655c2009-09-12 00:59:49 +00007503 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007504 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007505 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007506 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007507 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007508 if (Triple.getOS() == llvm::Triple::Win32) {
7509 TheTargetCodeGenInfo =
7510 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7511 return *TheTargetCodeGenInfo;
7512 }
7513
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007514 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Tim Northover5627d392015-10-30 16:30:45 +00007515 StringRef ABIStr = getTarget().getABI();
7516 if (ABIStr == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007517 Kind = ARMABIInfo::APCS;
Tim Northover5627d392015-10-30 16:30:45 +00007518 else if (ABIStr == "aapcs16")
7519 Kind = ARMABIInfo::AAPCS16_VFP;
David Tweed8f676532012-10-25 13:33:01 +00007520 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007521 (CodeGenOpts.FloatABI != "soft" &&
7522 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007523 Kind = ARMABIInfo::AAPCS_VFP;
7524
Derek Schuff71658bd2015-01-29 00:47:04 +00007525 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007526 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007527
John McCallea8d8bb2010-03-11 00:10:12 +00007528 case llvm::Triple::ppc:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00007529 return *(TheTargetCodeGenInfo =
7530 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007531 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007532 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007533 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007534 if (getTarget().getABI() == "elfv2")
7535 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007536 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007537
Ulrich Weigandb7122372014-07-21 00:48:09 +00007538 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007539 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007540 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007541 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007542 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007543 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007544 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007545 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007546 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007547 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007548
Ulrich Weigandb7122372014-07-21 00:48:09 +00007549 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007550 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007551 }
John McCallea8d8bb2010-03-11 00:10:12 +00007552
Peter Collingbournec947aae2012-05-20 23:28:41 +00007553 case llvm::Triple::nvptx:
7554 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007555 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007556
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007557 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007558 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007559
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007560 case llvm::Triple::systemz: {
7561 bool HasVector = getTarget().getABI() == "vector";
7562 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7563 HasVector));
7564 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007565
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007566 case llvm::Triple::tce:
7567 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7568
Eli Friedman33465822011-07-08 23:31:17 +00007569 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007570 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007571 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007572 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007573 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007574
John McCall1fe2a8c2013-06-18 02:46:29 +00007575 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007576 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007577 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Eric Christopher7565e0d2015-05-29 23:09:49 +00007578 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007579 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007580 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007581 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00007582 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7583 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007584 }
Eli Friedman33465822011-07-08 23:31:17 +00007585 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007586
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007587 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007588 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007589 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7590 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007591 X86AVXABILevel::None);
7592
Chris Lattner04dc9572010-08-31 16:44:54 +00007593 switch (Triple.getOS()) {
7594 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007595 return *(TheTargetCodeGenInfo =
7596 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007597 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007598 return *(TheTargetCodeGenInfo =
7599 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007600 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007601 return *(TheTargetCodeGenInfo =
7602 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007603 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007604 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007605 case llvm::Triple::hexagon:
7606 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007607 case llvm::Triple::r600:
7608 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007609 case llvm::Triple::amdgcn:
7610 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007611 case llvm::Triple::sparcv9:
7612 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007613 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007614 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007615 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007616}