blob: 8a5cc6c3df87bfd6468be8b2a30e58bc52ada485 [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 Divacky039b9702016-02-20 08:31:24 +00003508 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003509 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3510 // TODO: Implement this. For now ignore.
3511 (void)CTy;
John McCall7f416cc2015-09-08 08:05:57 +00003512 return Address::invalid();
Roman Divacky8a12d842014-11-03 18:32:54 +00003513 }
3514
John McCall7f416cc2015-09-08 08:05:57 +00003515 // struct __va_list_tag {
3516 // unsigned char gpr;
3517 // unsigned char fpr;
3518 // unsigned short reserved;
3519 // void *overflow_arg_area;
3520 // void *reg_save_area;
3521 // };
3522
Roman Divacky8a12d842014-11-03 18:32:54 +00003523 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003524 bool isInt =
3525 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003526 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003527
3528 // All aggregates are passed indirectly? That doesn't seem consistent
3529 // with the argument-lowering code.
3530 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003531
3532 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003533
3534 // The calling convention either uses 1-2 GPRs or 1 FPR.
3535 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003536 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003537 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3538 } else {
3539 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003540 }
John McCall7f416cc2015-09-08 08:05:57 +00003541
3542 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3543
3544 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003545 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003546 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3547 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3548 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003549
Eric Christopher7565e0d2015-05-29 23:09:49 +00003550 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003551 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003552
3553 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3554 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3555 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3556
3557 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3558
John McCall7f416cc2015-09-08 08:05:57 +00003559 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3560 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003561
John McCall7f416cc2015-09-08 08:05:57 +00003562 // Case 1: consume registers.
3563 Address RegAddr = Address::invalid();
3564 {
3565 CGF.EmitBlock(UsingRegs);
3566
3567 Address RegSaveAreaPtr =
3568 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3569 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3570 CharUnits::fromQuantity(8));
3571 assert(RegAddr.getElementType() == CGF.Int8Ty);
3572
3573 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003574 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003575 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3576 CharUnits::fromQuantity(32));
3577 }
3578
3579 // Get the address of the saved value by scaling the number of
3580 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003581 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003582 llvm::Value *RegOffset =
3583 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3584 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3585 RegAddr.getPointer(), RegOffset),
3586 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3587 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3588
3589 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003590 NumRegs =
3591 Builder.CreateAdd(NumRegs,
3592 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003593 Builder.CreateStore(NumRegs, NumRegsAddr);
3594
3595 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003596 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003597
John McCall7f416cc2015-09-08 08:05:57 +00003598 // Case 2: consume space in the overflow area.
3599 Address MemAddr = Address::invalid();
3600 {
3601 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003602
Roman Divacky039b9702016-02-20 08:31:24 +00003603 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3604
John McCall7f416cc2015-09-08 08:05:57 +00003605 // Everything in the overflow area is rounded up to a size of at least 4.
3606 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3607
3608 CharUnits Size;
3609 if (!isIndirect) {
3610 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003611 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003612 } else {
3613 Size = CGF.getPointerSize();
3614 }
3615
3616 Address OverflowAreaAddr =
3617 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003618 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003619 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003620 // Round up address of argument to alignment
3621 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3622 if (Align > OverflowAreaAlign) {
3623 llvm::Value *Ptr = OverflowArea.getPointer();
3624 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3625 Align);
3626 }
3627
John McCall7f416cc2015-09-08 08:05:57 +00003628 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3629
3630 // Increase the overflow area.
3631 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3632 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3633 CGF.EmitBranch(Cont);
3634 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003635
3636 CGF.EmitBlock(Cont);
3637
John McCall7f416cc2015-09-08 08:05:57 +00003638 // Merge the cases with a phi.
3639 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3640 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003641
John McCall7f416cc2015-09-08 08:05:57 +00003642 // Load the pointer if the argument was passed indirectly.
3643 if (isIndirect) {
3644 Result = Address(Builder.CreateLoad(Result, "aggr"),
3645 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003646 }
3647
3648 return Result;
3649}
3650
John McCallea8d8bb2010-03-11 00:10:12 +00003651bool
3652PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3653 llvm::Value *Address) const {
3654 // This is calculated from the LLVM and GCC tables and verified
3655 // against gcc output. AFAIK all ABIs use the same encoding.
3656
3657 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003658
Chris Lattnerece04092012-02-07 00:39:47 +00003659 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003660 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3661 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3662 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3663
3664 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003665 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003666
3667 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003668 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003669
3670 // 64-76 are various 4-byte special-purpose registers:
3671 // 64: mq
3672 // 65: lr
3673 // 66: ctr
3674 // 67: ap
3675 // 68-75 cr0-7
3676 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003677 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003678
3679 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003680 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003681
3682 // 109: vrsave
3683 // 110: vscr
3684 // 111: spe_acc
3685 // 112: spefscr
3686 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003687 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003688
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003689 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003690}
3691
Roman Divackyd966e722012-05-09 18:22:46 +00003692// PowerPC-64
3693
3694namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003695/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3696class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003697public:
3698 enum ABIKind {
3699 ELFv1 = 0,
3700 ELFv2
3701 };
3702
3703private:
3704 static const unsigned GPRBits = 64;
3705 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003706 bool HasQPX;
3707
3708 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3709 // will be passed in a QPX register.
3710 bool IsQPXVectorTy(const Type *Ty) const {
3711 if (!HasQPX)
3712 return false;
3713
3714 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3715 unsigned NumElements = VT->getNumElements();
3716 if (NumElements == 1)
3717 return false;
3718
3719 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3720 if (getContext().getTypeSize(Ty) <= 256)
3721 return true;
3722 } else if (VT->getElementType()->
3723 isSpecificBuiltinType(BuiltinType::Float)) {
3724 if (getContext().getTypeSize(Ty) <= 128)
3725 return true;
3726 }
3727 }
3728
3729 return false;
3730 }
3731
3732 bool IsQPXVectorTy(QualType Ty) const {
3733 return IsQPXVectorTy(Ty.getTypePtr());
3734 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003735
3736public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003737 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3738 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003739
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003740 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003741 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003742
3743 ABIArgInfo classifyReturnType(QualType RetTy) const;
3744 ABIArgInfo classifyArgumentType(QualType Ty) const;
3745
Reid Klecknere9f6a712014-10-31 17:10:41 +00003746 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3747 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3748 uint64_t Members) const override;
3749
Bill Schmidt84d37792012-10-12 19:26:17 +00003750 // TODO: We can add more logic to computeInfo to improve performance.
3751 // Example: For aggregate arguments that fit in a register, we could
3752 // use getDirectInReg (as is done below for structs containing a single
3753 // floating-point value) to avoid pushing them to memory on function
3754 // entry. This would require changing the logic in PPCISelLowering
3755 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003756 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003757 if (!getCXXABI().classifyReturnType(FI))
3758 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003759 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003760 // We rely on the default argument classification for the most part.
3761 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003762 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003763 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003764 if (T) {
3765 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003766 if (IsQPXVectorTy(T) ||
3767 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003768 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003769 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003770 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003771 continue;
3772 }
3773 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003774 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003775 }
3776 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003777
John McCall7f416cc2015-09-08 08:05:57 +00003778 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3779 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003780};
3781
3782class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003783
Bill Schmidt25cb3492012-10-03 19:18:57 +00003784public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003785 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003786 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003787 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003788
Craig Topper4f12f102014-03-12 06:41:41 +00003789 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003790 // This is recovered from gcc output.
3791 return 1; // r1 is the dedicated stack pointer
3792 }
3793
3794 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003795 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003796};
3797
Roman Divackyd966e722012-05-09 18:22:46 +00003798class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3799public:
3800 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3801
Craig Topper4f12f102014-03-12 06:41:41 +00003802 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003803 // This is recovered from gcc output.
3804 return 1; // r1 is the dedicated stack pointer
3805 }
3806
3807 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003808 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003809};
3810
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003811}
Roman Divackyd966e722012-05-09 18:22:46 +00003812
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003813// Return true if the ABI requires Ty to be passed sign- or zero-
3814// extended to 64 bits.
3815bool
3816PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3817 // Treat an enum type as its underlying type.
3818 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3819 Ty = EnumTy->getDecl()->getIntegerType();
3820
3821 // Promotable integer types are required to be promoted by the ABI.
3822 if (Ty->isPromotableIntegerType())
3823 return true;
3824
3825 // In addition to the usual promotable integer types, we also need to
3826 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3827 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3828 switch (BT->getKind()) {
3829 case BuiltinType::Int:
3830 case BuiltinType::UInt:
3831 return true;
3832 default:
3833 break;
3834 }
3835
3836 return false;
3837}
3838
John McCall7f416cc2015-09-08 08:05:57 +00003839/// isAlignedParamType - Determine whether a type requires 16-byte or
3840/// higher alignment in the parameter area. Always returns at least 8.
3841CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003842 // Complex types are passed just like their elements.
3843 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3844 Ty = CTy->getElementType();
3845
3846 // Only vector types of size 16 bytes need alignment (larger types are
3847 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003848 if (IsQPXVectorTy(Ty)) {
3849 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003850 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003851
John McCall7f416cc2015-09-08 08:05:57 +00003852 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003853 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00003854 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003855 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003856
3857 // For single-element float/vector structs, we consider the whole type
3858 // to have the same alignment requirements as its single element.
3859 const Type *AlignAsType = nullptr;
3860 const Type *EltType = isSingleElementStruct(Ty, getContext());
3861 if (EltType) {
3862 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003863 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003864 getContext().getTypeSize(EltType) == 128) ||
3865 (BT && BT->isFloatingPoint()))
3866 AlignAsType = EltType;
3867 }
3868
Ulrich Weigandb7122372014-07-21 00:48:09 +00003869 // Likewise for ELFv2 homogeneous aggregates.
3870 const Type *Base = nullptr;
3871 uint64_t Members = 0;
3872 if (!AlignAsType && Kind == ELFv2 &&
3873 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3874 AlignAsType = Base;
3875
Ulrich Weigand581badc2014-07-10 17:20:07 +00003876 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003877 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3878 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003879 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003880
John McCall7f416cc2015-09-08 08:05:57 +00003881 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003882 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00003883 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003884 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003885
3886 // Otherwise, we only need alignment for any aggregate type that
3887 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003888 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3889 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00003890 return CharUnits::fromQuantity(32);
3891 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003892 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003893
John McCall7f416cc2015-09-08 08:05:57 +00003894 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00003895}
3896
Ulrich Weigandb7122372014-07-21 00:48:09 +00003897/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3898/// aggregate. Base is set to the base element type, and Members is set
3899/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003900bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3901 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003902 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3903 uint64_t NElements = AT->getSize().getZExtValue();
3904 if (NElements == 0)
3905 return false;
3906 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3907 return false;
3908 Members *= NElements;
3909 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3910 const RecordDecl *RD = RT->getDecl();
3911 if (RD->hasFlexibleArrayMember())
3912 return false;
3913
3914 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003915
3916 // If this is a C++ record, check the bases first.
3917 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3918 for (const auto &I : CXXRD->bases()) {
3919 // Ignore empty records.
3920 if (isEmptyRecord(getContext(), I.getType(), true))
3921 continue;
3922
3923 uint64_t FldMembers;
3924 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3925 return false;
3926
3927 Members += FldMembers;
3928 }
3929 }
3930
Ulrich Weigandb7122372014-07-21 00:48:09 +00003931 for (const auto *FD : RD->fields()) {
3932 // Ignore (non-zero arrays of) empty records.
3933 QualType FT = FD->getType();
3934 while (const ConstantArrayType *AT =
3935 getContext().getAsConstantArrayType(FT)) {
3936 if (AT->getSize().getZExtValue() == 0)
3937 return false;
3938 FT = AT->getElementType();
3939 }
3940 if (isEmptyRecord(getContext(), FT, true))
3941 continue;
3942
3943 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3944 if (getContext().getLangOpts().CPlusPlus &&
3945 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3946 continue;
3947
3948 uint64_t FldMembers;
3949 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3950 return false;
3951
3952 Members = (RD->isUnion() ?
3953 std::max(Members, FldMembers) : Members + FldMembers);
3954 }
3955
3956 if (!Base)
3957 return false;
3958
3959 // Ensure there is no padding.
3960 if (getContext().getTypeSize(Base) * Members !=
3961 getContext().getTypeSize(Ty))
3962 return false;
3963 } else {
3964 Members = 1;
3965 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3966 Members = 2;
3967 Ty = CT->getElementType();
3968 }
3969
Reid Klecknere9f6a712014-10-31 17:10:41 +00003970 // Most ABIs only support float, double, and some vector type widths.
3971 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003972 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003973
3974 // The base type must be the same for all members. Types that
3975 // agree in both total size and mode (float vs. vector) are
3976 // treated as being equivalent here.
3977 const Type *TyPtr = Ty.getTypePtr();
3978 if (!Base)
3979 Base = TyPtr;
3980
3981 if (Base->isVectorType() != TyPtr->isVectorType() ||
3982 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3983 return false;
3984 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003985 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3986}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003987
Reid Klecknere9f6a712014-10-31 17:10:41 +00003988bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3989 // Homogeneous aggregates for ELFv2 must have base types of float,
3990 // double, long double, or 128-bit vectors.
3991 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3992 if (BT->getKind() == BuiltinType::Float ||
3993 BT->getKind() == BuiltinType::Double ||
3994 BT->getKind() == BuiltinType::LongDouble)
3995 return true;
3996 }
3997 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003998 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003999 return true;
4000 }
4001 return false;
4002}
4003
4004bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4005 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004006 // Vector types require one register, floating point types require one
4007 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004008 uint32_t NumRegs =
4009 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004010
4011 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004012 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004013}
4014
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004015ABIArgInfo
4016PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004017 Ty = useFirstFieldIfTransparentUnion(Ty);
4018
Bill Schmidt90b22c92012-11-27 02:46:43 +00004019 if (Ty->isAnyComplexType())
4020 return ABIArgInfo::getDirect();
4021
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004022 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4023 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004024 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004025 uint64_t Size = getContext().getTypeSize(Ty);
4026 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004027 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004028 else if (Size < 128) {
4029 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4030 return ABIArgInfo::getDirect(CoerceTy);
4031 }
4032 }
4033
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004034 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004035 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004036 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004037
John McCall7f416cc2015-09-08 08:05:57 +00004038 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4039 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004040
4041 // ELFv2 homogeneous aggregates are passed as array types.
4042 const Type *Base = nullptr;
4043 uint64_t Members = 0;
4044 if (Kind == ELFv2 &&
4045 isHomogeneousAggregate(Ty, Base, Members)) {
4046 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4047 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4048 return ABIArgInfo::getDirect(CoerceTy);
4049 }
4050
Ulrich Weigand601957f2014-07-21 00:56:36 +00004051 // If an aggregate may end up fully in registers, we do not
4052 // use the ByVal method, but pass the aggregate as array.
4053 // This is usually beneficial since we avoid forcing the
4054 // back-end to store the argument to memory.
4055 uint64_t Bits = getContext().getTypeSize(Ty);
4056 if (Bits > 0 && Bits <= 8 * GPRBits) {
4057 llvm::Type *CoerceTy;
4058
4059 // Types up to 8 bytes are passed as integer type (which will be
4060 // properly aligned in the argument save area doubleword).
4061 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004062 CoerceTy =
4063 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004064 // Larger types are passed as arrays, with the base type selected
4065 // according to the required alignment in the save area.
4066 else {
4067 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004068 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004069 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4070 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4071 }
4072
4073 return ABIArgInfo::getDirect(CoerceTy);
4074 }
4075
Ulrich Weigandb7122372014-07-21 00:48:09 +00004076 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004077 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4078 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004079 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004080 }
4081
4082 return (isPromotableTypeForABI(Ty) ?
4083 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4084}
4085
4086ABIArgInfo
4087PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4088 if (RetTy->isVoidType())
4089 return ABIArgInfo::getIgnore();
4090
Bill Schmidta3d121c2012-12-17 04:20:17 +00004091 if (RetTy->isAnyComplexType())
4092 return ABIArgInfo::getDirect();
4093
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004094 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4095 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004096 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004097 uint64_t Size = getContext().getTypeSize(RetTy);
4098 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004099 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004100 else if (Size < 128) {
4101 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4102 return ABIArgInfo::getDirect(CoerceTy);
4103 }
4104 }
4105
Ulrich Weigandb7122372014-07-21 00:48:09 +00004106 if (isAggregateTypeForABI(RetTy)) {
4107 // ELFv2 homogeneous aggregates are returned as array types.
4108 const Type *Base = nullptr;
4109 uint64_t Members = 0;
4110 if (Kind == ELFv2 &&
4111 isHomogeneousAggregate(RetTy, Base, Members)) {
4112 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4113 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4114 return ABIArgInfo::getDirect(CoerceTy);
4115 }
4116
4117 // ELFv2 small aggregates are returned in up to two registers.
4118 uint64_t Bits = getContext().getTypeSize(RetTy);
4119 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4120 if (Bits == 0)
4121 return ABIArgInfo::getIgnore();
4122
4123 llvm::Type *CoerceTy;
4124 if (Bits > GPRBits) {
4125 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004126 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004127 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004128 CoerceTy =
4129 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004130 return ABIArgInfo::getDirect(CoerceTy);
4131 }
4132
4133 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004134 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004135 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004136
4137 return (isPromotableTypeForABI(RetTy) ?
4138 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4139}
4140
Bill Schmidt25cb3492012-10-03 19:18:57 +00004141// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004142Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4143 QualType Ty) const {
4144 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4145 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004146
John McCall7f416cc2015-09-08 08:05:57 +00004147 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004148
Bill Schmidt924c4782013-01-14 17:45:36 +00004149 // If we have a complex type and the base type is smaller than 8 bytes,
4150 // the ABI calls for the real and imaginary parts to be right-adjusted
4151 // in separate doublewords. However, Clang expects us to produce a
4152 // pointer to a structure with the two parts packed tightly. So generate
4153 // loads of the real and imaginary parts relative to the va_list pointer,
4154 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004155 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4156 CharUnits EltSize = TypeInfo.first / 2;
4157 if (EltSize < SlotSize) {
4158 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4159 SlotSize * 2, SlotSize,
4160 SlotSize, /*AllowHigher*/ true);
4161
4162 Address RealAddr = Addr;
4163 Address ImagAddr = RealAddr;
4164 if (CGF.CGM.getDataLayout().isBigEndian()) {
4165 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4166 SlotSize - EltSize);
4167 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4168 2 * SlotSize - EltSize);
4169 } else {
4170 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4171 }
4172
4173 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4174 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4175 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4176 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4177 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4178
4179 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4180 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4181 /*init*/ true);
4182 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004183 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004184 }
4185
John McCall7f416cc2015-09-08 08:05:57 +00004186 // Otherwise, just use the general rule.
4187 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4188 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004189}
4190
4191static bool
4192PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4193 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004194 // This is calculated from the LLVM and GCC tables and verified
4195 // against gcc output. AFAIK all ABIs use the same encoding.
4196
4197 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4198
4199 llvm::IntegerType *i8 = CGF.Int8Ty;
4200 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4201 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4202 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4203
4204 // 0-31: r0-31, the 8-byte general-purpose registers
4205 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4206
4207 // 32-63: fp0-31, the 8-byte floating-point registers
4208 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4209
4210 // 64-76 are various 4-byte special-purpose registers:
4211 // 64: mq
4212 // 65: lr
4213 // 66: ctr
4214 // 67: ap
4215 // 68-75 cr0-7
4216 // 76: xer
4217 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4218
4219 // 77-108: v0-31, the 16-byte vector registers
4220 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4221
4222 // 109: vrsave
4223 // 110: vscr
4224 // 111: spe_acc
4225 // 112: spefscr
4226 // 113: sfp
4227 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4228
4229 return false;
4230}
John McCallea8d8bb2010-03-11 00:10:12 +00004231
Bill Schmidt25cb3492012-10-03 19:18:57 +00004232bool
4233PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4234 CodeGen::CodeGenFunction &CGF,
4235 llvm::Value *Address) const {
4236
4237 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4238}
4239
4240bool
4241PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4242 llvm::Value *Address) const {
4243
4244 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4245}
4246
Chris Lattner0cf24192010-06-28 20:05:43 +00004247//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004248// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004249//===----------------------------------------------------------------------===//
4250
4251namespace {
4252
Tim Northover573cbee2014-05-24 12:52:07 +00004253class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004254public:
4255 enum ABIKind {
4256 AAPCS = 0,
4257 DarwinPCS
4258 };
4259
4260private:
4261 ABIKind Kind;
4262
4263public:
Tim Northover573cbee2014-05-24 12:52:07 +00004264 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004265
4266private:
4267 ABIKind getABIKind() const { return Kind; }
4268 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4269
4270 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004271 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004272 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4273 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4274 uint64_t Members) const override;
4275
Tim Northovera2ee4332014-03-29 15:09:45 +00004276 bool isIllegalVectorType(QualType Ty) const;
4277
David Blaikie1cbb9712014-11-14 19:09:44 +00004278 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004279 if (!getCXXABI().classifyReturnType(FI))
4280 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004281
Tim Northoverb047bfa2014-11-27 21:02:49 +00004282 for (auto &it : FI.arguments())
4283 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004284 }
4285
John McCall7f416cc2015-09-08 08:05:57 +00004286 Address EmitDarwinVAArg(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 EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4290 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004291
John McCall7f416cc2015-09-08 08:05:57 +00004292 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4293 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004294 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4295 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4296 }
4297};
4298
Tim Northover573cbee2014-05-24 12:52:07 +00004299class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004300public:
Tim Northover573cbee2014-05-24 12:52:07 +00004301 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4302 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004303
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004304 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004305 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4306 }
4307
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004308 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4309 return 31;
4310 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004311
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004312 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004313};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004314}
Tim Northovera2ee4332014-03-29 15:09:45 +00004315
Tim Northoverb047bfa2014-11-27 21:02:49 +00004316ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004317 Ty = useFirstFieldIfTransparentUnion(Ty);
4318
Tim Northovera2ee4332014-03-29 15:09:45 +00004319 // Handle illegal vector types here.
4320 if (isIllegalVectorType(Ty)) {
4321 uint64_t Size = getContext().getTypeSize(Ty);
4322 if (Size <= 32) {
4323 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004324 return ABIArgInfo::getDirect(ResType);
4325 }
4326 if (Size == 64) {
4327 llvm::Type *ResType =
4328 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004329 return ABIArgInfo::getDirect(ResType);
4330 }
4331 if (Size == 128) {
4332 llvm::Type *ResType =
4333 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004334 return ABIArgInfo::getDirect(ResType);
4335 }
John McCall7f416cc2015-09-08 08:05:57 +00004336 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004337 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004338
4339 if (!isAggregateTypeForABI(Ty)) {
4340 // Treat an enum type as its underlying type.
4341 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4342 Ty = EnumTy->getDecl()->getIntegerType();
4343
Tim Northovera2ee4332014-03-29 15:09:45 +00004344 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4345 ? ABIArgInfo::getExtend()
4346 : ABIArgInfo::getDirect());
4347 }
4348
4349 // Structures with either a non-trivial destructor or a non-trivial
4350 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004351 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004352 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4353 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004354 }
4355
4356 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4357 // elsewhere for GNU compatibility.
4358 if (isEmptyRecord(getContext(), Ty, true)) {
4359 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4360 return ABIArgInfo::getIgnore();
4361
Tim Northovera2ee4332014-03-29 15:09:45 +00004362 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4363 }
4364
4365 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004366 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004367 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004368 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004369 return ABIArgInfo::getDirect(
4370 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004371 }
4372
4373 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4374 uint64_t Size = getContext().getTypeSize(Ty);
4375 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004376 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004377 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004378
Tim Northovera2ee4332014-03-29 15:09:45 +00004379 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4380 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004381 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004382 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4383 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4384 }
4385 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4386 }
4387
John McCall7f416cc2015-09-08 08:05:57 +00004388 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004389}
4390
Tim Northover573cbee2014-05-24 12:52:07 +00004391ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004392 if (RetTy->isVoidType())
4393 return ABIArgInfo::getIgnore();
4394
4395 // Large vector types should be returned via memory.
4396 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004397 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004398
4399 if (!isAggregateTypeForABI(RetTy)) {
4400 // Treat an enum type as its underlying type.
4401 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4402 RetTy = EnumTy->getDecl()->getIntegerType();
4403
Tim Northover4dab6982014-04-18 13:46:08 +00004404 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4405 ? ABIArgInfo::getExtend()
4406 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004407 }
4408
Tim Northovera2ee4332014-03-29 15:09:45 +00004409 if (isEmptyRecord(getContext(), RetTy, true))
4410 return ABIArgInfo::getIgnore();
4411
Craig Topper8a13c412014-05-21 05:09:00 +00004412 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004413 uint64_t Members = 0;
4414 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004415 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4416 return ABIArgInfo::getDirect();
4417
4418 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4419 uint64_t Size = getContext().getTypeSize(RetTy);
4420 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004421 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004422 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004423
4424 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4425 // For aggregates with 16-byte alignment, we use i128.
4426 if (Alignment < 128 && Size == 128) {
4427 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4428 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4429 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004430 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4431 }
4432
John McCall7f416cc2015-09-08 08:05:57 +00004433 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004434}
4435
Tim Northover573cbee2014-05-24 12:52:07 +00004436/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4437bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004438 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4439 // Check whether VT is legal.
4440 unsigned NumElements = VT->getNumElements();
4441 uint64_t Size = getContext().getTypeSize(VT);
4442 // NumElements should be power of 2 between 1 and 16.
4443 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4444 return true;
4445 return Size != 64 && (Size != 128 || NumElements == 1);
4446 }
4447 return false;
4448}
4449
Reid Klecknere9f6a712014-10-31 17:10:41 +00004450bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4451 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4452 // point type or a short-vector type. This is the same as the 32-bit ABI,
4453 // but with the difference that any floating-point type is allowed,
4454 // including __fp16.
4455 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4456 if (BT->isFloatingPoint())
4457 return true;
4458 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4459 unsigned VecSize = getContext().getTypeSize(VT);
4460 if (VecSize == 64 || VecSize == 128)
4461 return true;
4462 }
4463 return false;
4464}
4465
4466bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4467 uint64_t Members) const {
4468 return Members <= 4;
4469}
4470
John McCall7f416cc2015-09-08 08:05:57 +00004471Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004472 QualType Ty,
4473 CodeGenFunction &CGF) const {
4474 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004475 bool IsIndirect = AI.isIndirect();
4476
Tim Northoverb047bfa2014-11-27 21:02:49 +00004477 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4478 if (IsIndirect)
4479 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4480 else if (AI.getCoerceToType())
4481 BaseTy = AI.getCoerceToType();
4482
4483 unsigned NumRegs = 1;
4484 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4485 BaseTy = ArrTy->getElementType();
4486 NumRegs = ArrTy->getNumElements();
4487 }
4488 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4489
Tim Northovera2ee4332014-03-29 15:09:45 +00004490 // The AArch64 va_list type and handling is specified in the Procedure Call
4491 // Standard, section B.4:
4492 //
4493 // struct {
4494 // void *__stack;
4495 // void *__gr_top;
4496 // void *__vr_top;
4497 // int __gr_offs;
4498 // int __vr_offs;
4499 // };
4500
4501 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4502 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4503 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4504 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004505
John McCall7f416cc2015-09-08 08:05:57 +00004506 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4507 CharUnits TyAlign = TyInfo.second;
4508
4509 Address reg_offs_p = Address::invalid();
4510 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004511 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004512 CharUnits reg_top_offset;
4513 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004514 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004515 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004516 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004517 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4518 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004519 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4520 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004521 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004522 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004523 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004524 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004525 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004526 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4527 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004528 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4529 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004530 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004531 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004532 }
4533
4534 //=======================================
4535 // Find out where argument was passed
4536 //=======================================
4537
4538 // If reg_offs >= 0 we're already using the stack for this type of
4539 // argument. We don't want to keep updating reg_offs (in case it overflows,
4540 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4541 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004542 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004543 UsingStack = CGF.Builder.CreateICmpSGE(
4544 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4545
4546 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4547
4548 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004549 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004550 CGF.EmitBlock(MaybeRegBlock);
4551
4552 // Integer arguments may need to correct register alignment (for example a
4553 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4554 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004555 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4556 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004557
4558 reg_offs = CGF.Builder.CreateAdd(
4559 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4560 "align_regoffs");
4561 reg_offs = CGF.Builder.CreateAnd(
4562 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4563 "aligned_regoffs");
4564 }
4565
4566 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004567 // The fact that this is done unconditionally reflects the fact that
4568 // allocating an argument to the stack also uses up all the remaining
4569 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004570 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004571 NewOffset = CGF.Builder.CreateAdd(
4572 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4573 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4574
4575 // Now we're in a position to decide whether this argument really was in
4576 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004577 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004578 InRegs = CGF.Builder.CreateICmpSLE(
4579 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4580
4581 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4582
4583 //=======================================
4584 // Argument was in registers
4585 //=======================================
4586
4587 // Now we emit the code for if the argument was originally passed in
4588 // registers. First start the appropriate block:
4589 CGF.EmitBlock(InRegBlock);
4590
John McCall7f416cc2015-09-08 08:05:57 +00004591 llvm::Value *reg_top = nullptr;
4592 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4593 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004594 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004595 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4596 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4597 Address RegAddr = Address::invalid();
4598 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004599
4600 if (IsIndirect) {
4601 // If it's been passed indirectly (actually a struct), whatever we find from
4602 // stored registers or on the stack will actually be a struct **.
4603 MemTy = llvm::PointerType::getUnqual(MemTy);
4604 }
4605
Craig Topper8a13c412014-05-21 05:09:00 +00004606 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004607 uint64_t NumMembers = 0;
4608 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004609 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004610 // Homogeneous aggregates passed in registers will have their elements split
4611 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4612 // qN+1, ...). We reload and store into a temporary local variable
4613 // contiguously.
4614 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004615 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004616 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4617 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004618 Address Tmp = CGF.CreateTempAlloca(HFATy,
4619 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004620
John McCall7f416cc2015-09-08 08:05:57 +00004621 // On big-endian platforms, the value will be right-aligned in its slot.
4622 int Offset = 0;
4623 if (CGF.CGM.getDataLayout().isBigEndian() &&
4624 BaseTyInfo.first.getQuantity() < 16)
4625 Offset = 16 - BaseTyInfo.first.getQuantity();
4626
Tim Northovera2ee4332014-03-29 15:09:45 +00004627 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004628 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4629 Address LoadAddr =
4630 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4631 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4632
4633 Address StoreAddr =
4634 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004635
4636 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4637 CGF.Builder.CreateStore(Elem, StoreAddr);
4638 }
4639
John McCall7f416cc2015-09-08 08:05:57 +00004640 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004641 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004642 // Otherwise the object is contiguous in memory.
4643
4644 // It might be right-aligned in its slot.
4645 CharUnits SlotSize = BaseAddr.getAlignment();
4646 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004647 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004648 TyInfo.first < SlotSize) {
4649 CharUnits Offset = SlotSize - TyInfo.first;
4650 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004651 }
4652
John McCall7f416cc2015-09-08 08:05:57 +00004653 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004654 }
4655
4656 CGF.EmitBranch(ContBlock);
4657
4658 //=======================================
4659 // Argument was on the stack
4660 //=======================================
4661 CGF.EmitBlock(OnStackBlock);
4662
John McCall7f416cc2015-09-08 08:05:57 +00004663 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4664 CharUnits::Zero(), "stack_p");
4665 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004666
John McCall7f416cc2015-09-08 08:05:57 +00004667 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004668 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004669 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4670 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004671
John McCall7f416cc2015-09-08 08:05:57 +00004672 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004673
John McCall7f416cc2015-09-08 08:05:57 +00004674 OnStackPtr = CGF.Builder.CreateAdd(
4675 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004676 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004677 OnStackPtr = CGF.Builder.CreateAnd(
4678 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004679 "align_stack");
4680
John McCall7f416cc2015-09-08 08:05:57 +00004681 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004682 }
John McCall7f416cc2015-09-08 08:05:57 +00004683 Address OnStackAddr(OnStackPtr,
4684 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004685
John McCall7f416cc2015-09-08 08:05:57 +00004686 // All stack slots are multiples of 8 bytes.
4687 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4688 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004689 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004690 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004691 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004692 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004693
John McCall7f416cc2015-09-08 08:05:57 +00004694 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004695 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004696 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004697
4698 // Write the new value of __stack for the next call to va_arg
4699 CGF.Builder.CreateStore(NewStack, stack_p);
4700
4701 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004702 TyInfo.first < StackSlotSize) {
4703 CharUnits Offset = StackSlotSize - TyInfo.first;
4704 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004705 }
4706
John McCall7f416cc2015-09-08 08:05:57 +00004707 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004708
4709 CGF.EmitBranch(ContBlock);
4710
4711 //=======================================
4712 // Tidy up
4713 //=======================================
4714 CGF.EmitBlock(ContBlock);
4715
John McCall7f416cc2015-09-08 08:05:57 +00004716 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4717 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004718
4719 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004720 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4721 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004722
4723 return ResAddr;
4724}
4725
John McCall7f416cc2015-09-08 08:05:57 +00004726Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4727 CodeGenFunction &CGF) const {
4728 // The backend's lowering doesn't support va_arg for aggregates or
4729 // illegal vector types. Lower VAArg here for these cases and use
4730 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004731 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00004732 return Address::invalid();
Tim Northovera2ee4332014-03-29 15:09:45 +00004733
John McCall7f416cc2015-09-08 08:05:57 +00004734 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004735
John McCall7f416cc2015-09-08 08:05:57 +00004736 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004737 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004738 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4739 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4740 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004741 }
4742
John McCall7f416cc2015-09-08 08:05:57 +00004743 // The size of the actual thing passed, which might end up just
4744 // being a pointer for indirect types.
4745 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4746
4747 // Arguments bigger than 16 bytes which aren't homogeneous
4748 // aggregates should be passed indirectly.
4749 bool IsIndirect = false;
4750 if (TyInfo.first.getQuantity() > 16) {
4751 const Type *Base = nullptr;
4752 uint64_t Members = 0;
4753 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004754 }
4755
John McCall7f416cc2015-09-08 08:05:57 +00004756 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4757 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004758}
4759
4760//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004761// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004762//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004763
4764namespace {
4765
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004766class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004767public:
4768 enum ABIKind {
4769 APCS = 0,
4770 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004771 AAPCS_VFP = 2,
4772 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004773 };
4774
4775private:
4776 ABIKind Kind;
4777
4778public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004779 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004780 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004781 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004782
John McCall3480ef22011-08-30 01:42:09 +00004783 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004784 switch (getTarget().getTriple().getEnvironment()) {
4785 case llvm::Triple::Android:
4786 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004787 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004788 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004789 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004790 return true;
4791 default:
4792 return false;
4793 }
John McCall3480ef22011-08-30 01:42:09 +00004794 }
4795
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004796 bool isEABIHF() const {
4797 switch (getTarget().getTriple().getEnvironment()) {
4798 case llvm::Triple::EABIHF:
4799 case llvm::Triple::GNUEABIHF:
4800 return true;
4801 default:
4802 return false;
4803 }
4804 }
4805
Stephen Hines8267e7d2015-12-04 01:39:30 +00004806 bool isAndroid() const {
4807 return (getTarget().getTriple().getEnvironment() ==
4808 llvm::Triple::Android);
4809 }
4810
Daniel Dunbar020daa92009-09-12 01:00:39 +00004811 ABIKind getABIKind() const { return Kind; }
4812
Tim Northovera484bc02013-10-01 14:34:25 +00004813private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004814 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004815 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004816 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004817
Reid Klecknere9f6a712014-10-31 17:10:41 +00004818 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4819 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4820 uint64_t Members) const override;
4821
Craig Topper4f12f102014-03-12 06:41:41 +00004822 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004823
John McCall7f416cc2015-09-08 08:05:57 +00004824 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4825 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004826
4827 llvm::CallingConv::ID getLLVMDefaultCC() const;
4828 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004829 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004830};
4831
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004832class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4833public:
Chris Lattner2b037972010-07-29 02:01:43 +00004834 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4835 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004836
John McCall3480ef22011-08-30 01:42:09 +00004837 const ARMABIInfo &getABIInfo() const {
4838 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4839 }
4840
Craig Topper4f12f102014-03-12 06:41:41 +00004841 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004842 return 13;
4843 }
Roman Divackyc1617352011-05-18 19:36:54 +00004844
Craig Topper4f12f102014-03-12 06:41:41 +00004845 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004846 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4847 }
4848
Roman Divackyc1617352011-05-18 19:36:54 +00004849 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004850 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004851 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004852
4853 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004854 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004855 return false;
4856 }
John McCall3480ef22011-08-30 01:42:09 +00004857
Craig Topper4f12f102014-03-12 06:41:41 +00004858 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004859 if (getABIInfo().isEABI()) return 88;
4860 return TargetCodeGenInfo::getSizeOfUnwindException();
4861 }
Tim Northovera484bc02013-10-01 14:34:25 +00004862
Eric Christopher162c91c2015-06-05 22:03:00 +00004863 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004864 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00004865 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00004866 if (!FD)
4867 return;
4868
4869 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4870 if (!Attr)
4871 return;
4872
4873 const char *Kind;
4874 switch (Attr->getInterrupt()) {
4875 case ARMInterruptAttr::Generic: Kind = ""; break;
4876 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4877 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4878 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4879 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4880 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4881 }
4882
4883 llvm::Function *Fn = cast<llvm::Function>(GV);
4884
4885 Fn->addFnAttr("interrupt", Kind);
4886
Tim Northover5627d392015-10-30 16:30:45 +00004887 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
4888 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00004889 return;
4890
4891 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4892 // however this is not necessarily true on taking any interrupt. Instruct
4893 // the backend to perform a realignment as part of the function prologue.
4894 llvm::AttrBuilder B;
4895 B.addStackAlignmentAttr(8);
4896 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4897 llvm::AttributeSet::get(CGM.getLLVMContext(),
4898 llvm::AttributeSet::FunctionIndex,
4899 B));
4900 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004901};
4902
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004903class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004904public:
4905 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4906 : ARMTargetCodeGenInfo(CGT, K) {}
4907
Eric Christopher162c91c2015-06-05 22:03:00 +00004908 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004909 CodeGen::CodeGenModule &CGM) const override;
4910};
4911
Eric Christopher162c91c2015-06-05 22:03:00 +00004912void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004913 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004914 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004915 addStackProbeSizeTargetAttribute(D, GV, CGM);
4916}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004917}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004918
Chris Lattner22326a12010-07-29 02:31:05 +00004919void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004920 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004921 FI.getReturnInfo() =
4922 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004923
Tim Northoverbc784d12015-02-24 17:22:40 +00004924 for (auto &I : FI.arguments())
4925 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004926
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004927 // Always honor user-specified calling convention.
4928 if (FI.getCallingConvention() != llvm::CallingConv::C)
4929 return;
4930
John McCall882987f2013-02-28 19:01:20 +00004931 llvm::CallingConv::ID cc = getRuntimeCC();
4932 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004933 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004934}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004935
John McCall882987f2013-02-28 19:01:20 +00004936/// Return the default calling convention that LLVM will use.
4937llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4938 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00004939 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00004940 return llvm::CallingConv::ARM_AAPCS_VFP;
4941 else if (isEABI())
4942 return llvm::CallingConv::ARM_AAPCS;
4943 else
4944 return llvm::CallingConv::ARM_APCS;
4945}
4946
4947/// Return the calling convention that our ABI would like us to use
4948/// as the C calling convention.
4949llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004950 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004951 case APCS: return llvm::CallingConv::ARM_APCS;
4952 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4953 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00004954 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004955 }
John McCall882987f2013-02-28 19:01:20 +00004956 llvm_unreachable("bad ABI kind");
4957}
4958
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004959void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004960 assert(getRuntimeCC() == llvm::CallingConv::C);
4961
4962 // Don't muddy up the IR with a ton of explicit annotations if
4963 // they'd just match what LLVM will infer from the triple.
4964 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4965 if (abiCC != getLLVMDefaultCC())
4966 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004967
Tim Northover5627d392015-10-30 16:30:45 +00004968 // AAPCS apparently requires runtime support functions to be soft-float, but
4969 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
4970 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
4971 switch (getABIKind()) {
4972 case APCS:
4973 case AAPCS16_VFP:
4974 if (abiCC != getLLVMDefaultCC())
4975 BuiltinCC = abiCC;
4976 break;
4977 case AAPCS:
4978 case AAPCS_VFP:
4979 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
4980 break;
4981 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004982}
4983
Tim Northoverbc784d12015-02-24 17:22:40 +00004984ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4985 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004986 // 6.1.2.1 The following argument types are VFP CPRCs:
4987 // A single-precision floating-point type (including promoted
4988 // half-precision types); A double-precision floating-point type;
4989 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4990 // with a Base Type of a single- or double-precision floating-point type,
4991 // 64-bit containerized vectors or 128-bit containerized vectors with one
4992 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004993 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004994
Reid Klecknerb1be6832014-11-15 01:41:41 +00004995 Ty = useFirstFieldIfTransparentUnion(Ty);
4996
Manman Renfef9e312012-10-16 19:18:39 +00004997 // Handle illegal vector types here.
4998 if (isIllegalVectorType(Ty)) {
4999 uint64_t Size = getContext().getTypeSize(Ty);
5000 if (Size <= 32) {
5001 llvm::Type *ResType =
5002 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005003 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005004 }
5005 if (Size == 64) {
5006 llvm::Type *ResType = llvm::VectorType::get(
5007 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005008 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005009 }
5010 if (Size == 128) {
5011 llvm::Type *ResType = llvm::VectorType::get(
5012 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005013 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005014 }
John McCall7f416cc2015-09-08 08:05:57 +00005015 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005016 }
5017
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005018 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5019 // unspecified. This is not done for OpenCL as it handles the half type
5020 // natively, and does not need to interwork with AAPCS code.
5021 if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
5022 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5023 llvm::Type::getFloatTy(getVMContext()) :
5024 llvm::Type::getInt32Ty(getVMContext());
5025 return ABIArgInfo::getDirect(ResType);
5026 }
5027
John McCalla1dee5302010-08-22 10:59:02 +00005028 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005029 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005030 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005031 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005032 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005033
Tim Northover5a1558e2014-11-07 22:30:50 +00005034 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5035 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005036 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005037
Oliver Stannard405bded2014-02-11 09:25:50 +00005038 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005039 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005040 }
Tim Northover1060eae2013-06-21 22:49:34 +00005041
Daniel Dunbar09d33622009-09-14 21:54:03 +00005042 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005043 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005044 return ABIArgInfo::getIgnore();
5045
Tim Northover5a1558e2014-11-07 22:30:50 +00005046 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005047 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5048 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005049 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005050 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005051 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005052 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005053 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005054 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005055 }
Tim Northover5627d392015-10-30 16:30:45 +00005056 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5057 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5058 // this convention even for a variadic function: the backend will use GPRs
5059 // if needed.
5060 const Type *Base = nullptr;
5061 uint64_t Members = 0;
5062 if (isHomogeneousAggregate(Ty, Base, Members)) {
5063 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5064 llvm::Type *Ty =
5065 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5066 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5067 }
5068 }
5069
5070 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5071 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5072 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5073 // bigger than 128-bits, they get placed in space allocated by the caller,
5074 // and a pointer is passed.
5075 return ABIArgInfo::getIndirect(
5076 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005077 }
5078
Manman Ren6c30e132012-08-13 21:23:55 +00005079 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005080 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5081 // most 8-byte. We realign the indirect argument if type alignment is bigger
5082 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005083 uint64_t ABIAlign = 4;
5084 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5085 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005086 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005087 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005088
Manman Ren8cd99812012-11-06 04:58:01 +00005089 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005090 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005091 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5092 /*ByVal=*/true,
5093 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005094 }
5095
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005096 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005097 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005098 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005099 // FIXME: Try to match the types of the arguments more accurately where
5100 // we can.
5101 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005102 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5103 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005104 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005105 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5106 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005107 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005108
Tim Northover5a1558e2014-11-07 22:30:50 +00005109 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005110}
5111
Chris Lattner458b2aa2010-07-29 02:16:43 +00005112static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005113 llvm::LLVMContext &VMContext) {
5114 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5115 // is called integer-like if its size is less than or equal to one word, and
5116 // the offset of each of its addressable sub-fields is zero.
5117
5118 uint64_t Size = Context.getTypeSize(Ty);
5119
5120 // Check that the type fits in a word.
5121 if (Size > 32)
5122 return false;
5123
5124 // FIXME: Handle vector types!
5125 if (Ty->isVectorType())
5126 return false;
5127
Daniel Dunbard53bac72009-09-14 02:20:34 +00005128 // Float types are never treated as "integer like".
5129 if (Ty->isRealFloatingType())
5130 return false;
5131
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005132 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005133 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005134 return true;
5135
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005136 // Small complex integer types are "integer like".
5137 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5138 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005139
5140 // Single element and zero sized arrays should be allowed, by the definition
5141 // above, but they are not.
5142
5143 // Otherwise, it must be a record type.
5144 const RecordType *RT = Ty->getAs<RecordType>();
5145 if (!RT) return false;
5146
5147 // Ignore records with flexible arrays.
5148 const RecordDecl *RD = RT->getDecl();
5149 if (RD->hasFlexibleArrayMember())
5150 return false;
5151
5152 // Check that all sub-fields are at offset 0, and are themselves "integer
5153 // like".
5154 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5155
5156 bool HadField = false;
5157 unsigned idx = 0;
5158 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5159 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005160 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005161
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005162 // Bit-fields are not addressable, we only need to verify they are "integer
5163 // like". We still have to disallow a subsequent non-bitfield, for example:
5164 // struct { int : 0; int x }
5165 // is non-integer like according to gcc.
5166 if (FD->isBitField()) {
5167 if (!RD->isUnion())
5168 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005169
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005170 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5171 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005172
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005173 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005174 }
5175
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005176 // Check if this field is at offset 0.
5177 if (Layout.getFieldOffset(idx) != 0)
5178 return false;
5179
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005180 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5181 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005182
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005183 // Only allow at most one field in a structure. This doesn't match the
5184 // wording above, but follows gcc in situations with a field following an
5185 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005186 if (!RD->isUnion()) {
5187 if (HadField)
5188 return false;
5189
5190 HadField = true;
5191 }
5192 }
5193
5194 return true;
5195}
5196
Oliver Stannard405bded2014-02-11 09:25:50 +00005197ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5198 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005199 bool IsEffectivelyAAPCS_VFP =
5200 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005201
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005202 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005203 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005204
Daniel Dunbar19964db2010-09-23 01:54:32 +00005205 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005206 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005207 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005208 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005209
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005210 // __fp16 gets returned as if it were an int or float, but with the top 16
5211 // bits unspecified. This is not done for OpenCL as it handles the half type
5212 // natively, and does not need to interwork with AAPCS code.
5213 if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
5214 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5215 llvm::Type::getFloatTy(getVMContext()) :
5216 llvm::Type::getInt32Ty(getVMContext());
5217 return ABIArgInfo::getDirect(ResType);
5218 }
5219
John McCalla1dee5302010-08-22 10:59:02 +00005220 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005221 // Treat an enum type as its underlying type.
5222 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5223 RetTy = EnumTy->getDecl()->getIntegerType();
5224
Tim Northover5a1558e2014-11-07 22:30:50 +00005225 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5226 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005227 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005228
5229 // Are we following APCS?
5230 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005231 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005232 return ABIArgInfo::getIgnore();
5233
Daniel Dunbareedf1512010-02-01 23:31:19 +00005234 // Complex types are all returned as packed integers.
5235 //
5236 // FIXME: Consider using 2 x vector types if the back end handles them
5237 // correctly.
5238 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005239 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5240 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005241
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005242 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005243 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005244 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005245 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005246 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005247 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005248 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005249 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5250 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005251 }
5252
5253 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005254 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005255 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005256
5257 // Otherwise this is an AAPCS variant.
5258
Chris Lattner458b2aa2010-07-29 02:16:43 +00005259 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005260 return ABIArgInfo::getIgnore();
5261
Bob Wilson1d9269a2011-11-02 04:51:36 +00005262 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005263 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005264 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005265 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005266 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005267 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005268 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005269 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005270 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005271 }
5272
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005273 // Aggregates <= 4 bytes are returned in r0; other aggregates
5274 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005275 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005276 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005277 if (getDataLayout().isBigEndian())
5278 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005279 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005280
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005281 // Return in the smallest viable integer type.
5282 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005283 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005284 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005285 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5286 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005287 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5288 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5289 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005290 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005291 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005292 }
5293
John McCall7f416cc2015-09-08 08:05:57 +00005294 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005295}
5296
Manman Renfef9e312012-10-16 19:18:39 +00005297/// isIllegalVector - check whether Ty is an illegal vector type.
5298bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005299 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5300 if (isAndroid()) {
5301 // Android shipped using Clang 3.1, which supported a slightly different
5302 // vector ABI. The primary differences were that 3-element vector types
5303 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5304 // accepts that legacy behavior for Android only.
5305 // Check whether VT is legal.
5306 unsigned NumElements = VT->getNumElements();
5307 // NumElements should be power of 2 or equal to 3.
5308 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5309 return true;
5310 } else {
5311 // Check whether VT is legal.
5312 unsigned NumElements = VT->getNumElements();
5313 uint64_t Size = getContext().getTypeSize(VT);
5314 // NumElements should be power of 2.
5315 if (!llvm::isPowerOf2_32(NumElements))
5316 return true;
5317 // Size should be greater than 32 bits.
5318 return Size <= 32;
5319 }
Manman Renfef9e312012-10-16 19:18:39 +00005320 }
5321 return false;
5322}
5323
Reid Klecknere9f6a712014-10-31 17:10:41 +00005324bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5325 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5326 // double, or 64-bit or 128-bit vectors.
5327 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5328 if (BT->getKind() == BuiltinType::Float ||
5329 BT->getKind() == BuiltinType::Double ||
5330 BT->getKind() == BuiltinType::LongDouble)
5331 return true;
5332 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5333 unsigned VecSize = getContext().getTypeSize(VT);
5334 if (VecSize == 64 || VecSize == 128)
5335 return true;
5336 }
5337 return false;
5338}
5339
5340bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5341 uint64_t Members) const {
5342 return Members <= 4;
5343}
5344
John McCall7f416cc2015-09-08 08:05:57 +00005345Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5346 QualType Ty) const {
5347 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005348
John McCall7f416cc2015-09-08 08:05:57 +00005349 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005350 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005351 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5352 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5353 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005354 }
5355
John McCall7f416cc2015-09-08 08:05:57 +00005356 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5357 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005358
John McCall7f416cc2015-09-08 08:05:57 +00005359 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5360 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005361 const Type *Base = nullptr;
5362 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005363 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5364 IsIndirect = true;
5365
Tim Northover5627d392015-10-30 16:30:45 +00005366 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5367 // allocated by the caller.
5368 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5369 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5370 !isHomogeneousAggregate(Ty, Base, Members)) {
5371 IsIndirect = true;
5372
John McCall7f416cc2015-09-08 08:05:57 +00005373 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005374 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5375 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005376 // Our callers should be prepared to handle an under-aligned address.
5377 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5378 getABIKind() == ARMABIInfo::AAPCS) {
5379 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5380 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005381 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5382 // ARMv7k allows type alignment up to 16 bytes.
5383 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5384 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005385 } else {
5386 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005387 }
John McCall7f416cc2015-09-08 08:05:57 +00005388 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005389
John McCall7f416cc2015-09-08 08:05:57 +00005390 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5391 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005392}
5393
Chris Lattner0cf24192010-06-28 20:05:43 +00005394//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005395// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005396//===----------------------------------------------------------------------===//
5397
5398namespace {
5399
Justin Holewinski83e96682012-05-24 17:43:12 +00005400class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005401public:
Justin Holewinski36837432013-03-30 14:38:24 +00005402 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005403
5404 ABIArgInfo classifyReturnType(QualType RetTy) const;
5405 ABIArgInfo classifyArgumentType(QualType Ty) const;
5406
Craig Topper4f12f102014-03-12 06:41:41 +00005407 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005408 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5409 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005410};
5411
Justin Holewinski83e96682012-05-24 17:43:12 +00005412class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005413public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005414 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5415 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005416
Eric Christopher162c91c2015-06-05 22:03:00 +00005417 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005418 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005419private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005420 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5421 // resulting MDNode to the nvvm.annotations MDNode.
5422 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005423};
5424
Justin Holewinski83e96682012-05-24 17:43:12 +00005425ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005426 if (RetTy->isVoidType())
5427 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005428
5429 // note: this is different from default ABI
5430 if (!RetTy->isScalarType())
5431 return ABIArgInfo::getDirect();
5432
5433 // Treat an enum type as its underlying type.
5434 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5435 RetTy = EnumTy->getDecl()->getIntegerType();
5436
5437 return (RetTy->isPromotableIntegerType() ?
5438 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005439}
5440
Justin Holewinski83e96682012-05-24 17:43:12 +00005441ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005442 // Treat an enum type as its underlying type.
5443 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5444 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005445
Eli Bendersky95338a02014-10-29 13:43:21 +00005446 // Return aggregates type as indirect by value
5447 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005448 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005449
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005450 return (Ty->isPromotableIntegerType() ?
5451 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005452}
5453
Justin Holewinski83e96682012-05-24 17:43:12 +00005454void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005455 if (!getCXXABI().classifyReturnType(FI))
5456 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005457 for (auto &I : FI.arguments())
5458 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005459
5460 // Always honor user-specified calling convention.
5461 if (FI.getCallingConvention() != llvm::CallingConv::C)
5462 return;
5463
John McCall882987f2013-02-28 19:01:20 +00005464 FI.setEffectiveCallingConvention(getRuntimeCC());
5465}
5466
John McCall7f416cc2015-09-08 08:05:57 +00005467Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5468 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005469 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005470}
5471
Justin Holewinski83e96682012-05-24 17:43:12 +00005472void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005473setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005474 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005475 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005476 if (!FD) return;
5477
5478 llvm::Function *F = cast<llvm::Function>(GV);
5479
5480 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005481 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005482 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005483 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005484 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005485 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005486 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5487 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005488 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005489 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005490 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005491 }
Justin Holewinski38031972011-10-05 17:58:44 +00005492
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005493 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005494 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005495 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005496 // __global__ functions cannot be called from the device, we do not
5497 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005498 if (FD->hasAttr<CUDAGlobalAttr>()) {
5499 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5500 addNVVMMetadata(F, "kernel", 1);
5501 }
Artem Belevich7093e402015-04-21 22:55:54 +00005502 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005503 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005504 llvm::APSInt MaxThreads(32);
5505 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5506 if (MaxThreads > 0)
5507 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5508
5509 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5510 // not specified in __launch_bounds__ or if the user specified a 0 value,
5511 // we don't have to add a PTX directive.
5512 if (Attr->getMinBlocks()) {
5513 llvm::APSInt MinBlocks(32);
5514 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5515 if (MinBlocks > 0)
5516 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5517 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005518 }
5519 }
Justin Holewinski38031972011-10-05 17:58:44 +00005520 }
5521}
5522
Eli Benderskye06a2c42014-04-15 16:57:05 +00005523void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5524 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005525 llvm::Module *M = F->getParent();
5526 llvm::LLVMContext &Ctx = M->getContext();
5527
5528 // Get "nvvm.annotations" metadata node
5529 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5530
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005531 llvm::Metadata *MDVals[] = {
5532 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5533 llvm::ConstantAsMetadata::get(
5534 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005535 // Append metadata to nvvm.annotations
5536 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5537}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005538}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005539
5540//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005541// SystemZ ABI Implementation
5542//===----------------------------------------------------------------------===//
5543
5544namespace {
5545
5546class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005547 bool HasVector;
5548
Ulrich Weigand47445072013-05-06 16:26:41 +00005549public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005550 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5551 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005552
5553 bool isPromotableIntegerType(QualType Ty) const;
5554 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005555 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005556 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005557 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005558
5559 ABIArgInfo classifyReturnType(QualType RetTy) const;
5560 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5561
Craig Topper4f12f102014-03-12 06:41:41 +00005562 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005563 if (!getCXXABI().classifyReturnType(FI))
5564 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005565 for (auto &I : FI.arguments())
5566 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005567 }
5568
John McCall7f416cc2015-09-08 08:05:57 +00005569 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5570 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005571};
5572
5573class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5574public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005575 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5576 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005577};
5578
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005579}
Ulrich Weigand47445072013-05-06 16:26:41 +00005580
5581bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5582 // Treat an enum type as its underlying type.
5583 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5584 Ty = EnumTy->getDecl()->getIntegerType();
5585
5586 // Promotable integer types are required to be promoted by the ABI.
5587 if (Ty->isPromotableIntegerType())
5588 return true;
5589
5590 // 32-bit values must also be promoted.
5591 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5592 switch (BT->getKind()) {
5593 case BuiltinType::Int:
5594 case BuiltinType::UInt:
5595 return true;
5596 default:
5597 return false;
5598 }
5599 return false;
5600}
5601
5602bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005603 return (Ty->isAnyComplexType() ||
5604 Ty->isVectorType() ||
5605 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005606}
5607
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005608bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5609 return (HasVector &&
5610 Ty->isVectorType() &&
5611 getContext().getTypeSize(Ty) <= 128);
5612}
5613
Ulrich Weigand47445072013-05-06 16:26:41 +00005614bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5615 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5616 switch (BT->getKind()) {
5617 case BuiltinType::Float:
5618 case BuiltinType::Double:
5619 return true;
5620 default:
5621 return false;
5622 }
5623
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005624 return false;
5625}
5626
5627QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005628 if (const RecordType *RT = Ty->getAsStructureType()) {
5629 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005630 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005631
5632 // If this is a C++ record, check the bases first.
5633 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005634 for (const auto &I : CXXRD->bases()) {
5635 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005636
5637 // Empty bases don't affect things either way.
5638 if (isEmptyRecord(getContext(), Base, true))
5639 continue;
5640
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005641 if (!Found.isNull())
5642 return Ty;
5643 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005644 }
5645
5646 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005647 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005648 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005649 // Unlike isSingleElementStruct(), empty structure and array fields
5650 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005651 if (getContext().getLangOpts().CPlusPlus &&
5652 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5653 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005654
5655 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005656 // Nested structures still do though.
5657 if (!Found.isNull())
5658 return Ty;
5659 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005660 }
5661
5662 // Unlike isSingleElementStruct(), trailing padding is allowed.
5663 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005664 if (!Found.isNull())
5665 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005666 }
5667
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005668 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005669}
5670
John McCall7f416cc2015-09-08 08:05:57 +00005671Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5672 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005673 // Assume that va_list type is correct; should be pointer to LLVM type:
5674 // struct {
5675 // i64 __gpr;
5676 // i64 __fpr;
5677 // i8 *__overflow_arg_area;
5678 // i8 *__reg_save_area;
5679 // };
5680
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005681 // Every non-vector argument occupies 8 bytes and is passed by preference
5682 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5683 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005684 Ty = getContext().getCanonicalType(Ty);
5685 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005686 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005687 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005688 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005689 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005690 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005691 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005692 CharUnits UnpaddedSize;
5693 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005694 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005695 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5696 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005697 } else {
5698 if (AI.getCoerceToType())
5699 ArgTy = AI.getCoerceToType();
5700 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005701 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005702 UnpaddedSize = TyInfo.first;
5703 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005704 }
John McCall7f416cc2015-09-08 08:05:57 +00005705 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5706 if (IsVector && UnpaddedSize > PaddedSize)
5707 PaddedSize = CharUnits::fromQuantity(16);
5708 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005709
John McCall7f416cc2015-09-08 08:05:57 +00005710 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005711
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005712 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005713 llvm::Value *PaddedSizeV =
5714 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005715
5716 if (IsVector) {
5717 // Work out the address of a vector argument on the stack.
5718 // Vector arguments are always passed in the high bits of a
5719 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005720 Address OverflowArgAreaPtr =
5721 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005722 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005723 Address OverflowArgArea =
5724 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5725 TyInfo.second);
5726 Address MemAddr =
5727 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005728
5729 // Update overflow_arg_area_ptr pointer
5730 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005731 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5732 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005733 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5734
5735 return MemAddr;
5736 }
5737
John McCall7f416cc2015-09-08 08:05:57 +00005738 assert(PaddedSize.getQuantity() == 8);
5739
5740 unsigned MaxRegs, RegCountField, RegSaveIndex;
5741 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005742 if (InFPRs) {
5743 MaxRegs = 4; // Maximum of 4 FPR arguments
5744 RegCountField = 1; // __fpr
5745 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005746 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005747 } else {
5748 MaxRegs = 5; // Maximum of 5 GPR arguments
5749 RegCountField = 0; // __gpr
5750 RegSaveIndex = 2; // save offset for r2
5751 RegPadding = Padding; // values are passed in the low bits of a GPR
5752 }
5753
John McCall7f416cc2015-09-08 08:05:57 +00005754 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5755 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5756 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005757 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005758 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5759 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005760 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005761
5762 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5763 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5764 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5765 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5766
5767 // Emit code to load the value if it was passed in registers.
5768 CGF.EmitBlock(InRegBlock);
5769
5770 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005771 llvm::Value *ScaledRegCount =
5772 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5773 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005774 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5775 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005776 llvm::Value *RegOffset =
5777 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005778 Address RegSaveAreaPtr =
5779 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5780 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005781 llvm::Value *RegSaveArea =
5782 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005783 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5784 "raw_reg_addr"),
5785 PaddedSize);
5786 Address RegAddr =
5787 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005788
5789 // Update the register count
5790 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5791 llvm::Value *NewRegCount =
5792 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5793 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5794 CGF.EmitBranch(ContBlock);
5795
5796 // Emit code to load the value if it was passed in memory.
5797 CGF.EmitBlock(InMemBlock);
5798
5799 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005800 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5801 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5802 Address OverflowArgArea =
5803 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5804 PaddedSize);
5805 Address RawMemAddr =
5806 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5807 Address MemAddr =
5808 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005809
5810 // Update overflow_arg_area_ptr pointer
5811 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005812 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5813 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005814 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5815 CGF.EmitBranch(ContBlock);
5816
5817 // Return the appropriate result.
5818 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005819 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5820 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005821
5822 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005823 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5824 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005825
5826 return ResAddr;
5827}
5828
Ulrich Weigand47445072013-05-06 16:26:41 +00005829ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5830 if (RetTy->isVoidType())
5831 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005832 if (isVectorArgumentType(RetTy))
5833 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005834 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00005835 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005836 return (isPromotableIntegerType(RetTy) ?
5837 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5838}
5839
5840ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5841 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005842 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00005843 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00005844
5845 // Integers and enums are extended to full register width.
5846 if (isPromotableIntegerType(Ty))
5847 return ABIArgInfo::getExtend();
5848
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005849 // Handle vector types and vector-like structure types. Note that
5850 // as opposed to float-like structure types, we do not allow any
5851 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005852 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005853 QualType SingleElementTy = GetSingleElementType(Ty);
5854 if (isVectorArgumentType(SingleElementTy) &&
5855 getContext().getTypeSize(SingleElementTy) == Size)
5856 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5857
5858 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005859 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00005860 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005861
5862 // Handle small structures.
5863 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5864 // Structures with flexible arrays have variable length, so really
5865 // fail the size test above.
5866 const RecordDecl *RD = RT->getDecl();
5867 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00005868 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005869
5870 // The structure is passed as an unextended integer, a float, or a double.
5871 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005872 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005873 assert(Size == 32 || Size == 64);
5874 if (Size == 32)
5875 PassTy = llvm::Type::getFloatTy(getVMContext());
5876 else
5877 PassTy = llvm::Type::getDoubleTy(getVMContext());
5878 } else
5879 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5880 return ABIArgInfo::getDirect(PassTy);
5881 }
5882
5883 // Non-structure compounds are passed indirectly.
5884 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005885 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005886
Craig Topper8a13c412014-05-21 05:09:00 +00005887 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005888}
5889
5890//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005891// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005892//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005893
5894namespace {
5895
5896class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5897public:
Chris Lattner2b037972010-07-29 02:01:43 +00005898 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5899 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005900 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005901 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005902};
5903
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005904}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005905
Eric Christopher162c91c2015-06-05 22:03:00 +00005906void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005907 llvm::GlobalValue *GV,
5908 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005909 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005910 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5911 // Handle 'interrupt' attribute:
5912 llvm::Function *F = cast<llvm::Function>(GV);
5913
5914 // Step 1: Set ISR calling convention.
5915 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5916
5917 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005918 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005919
5920 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005921 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005922 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5923 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005924 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005925 }
5926}
5927
Chris Lattner0cf24192010-06-28 20:05:43 +00005928//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005929// MIPS ABI Implementation. This works for both little-endian and
5930// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005931//===----------------------------------------------------------------------===//
5932
John McCall943fae92010-05-27 06:19:26 +00005933namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005934class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005935 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005936 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5937 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005938 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005939 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005940 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005941 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005942public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005943 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005944 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005945 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005946
5947 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005948 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005949 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005950 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5951 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005952 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005953};
5954
John McCall943fae92010-05-27 06:19:26 +00005955class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005956 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005957public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005958 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5959 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005960 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005961
Craig Topper4f12f102014-03-12 06:41:41 +00005962 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005963 return 29;
5964 }
5965
Eric Christopher162c91c2015-06-05 22:03:00 +00005966 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005967 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005968 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005969 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005970 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005971 if (FD->hasAttr<Mips16Attr>()) {
5972 Fn->addFnAttr("mips16");
5973 }
5974 else if (FD->hasAttr<NoMips16Attr>()) {
5975 Fn->addFnAttr("nomips16");
5976 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005977
5978 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
5979 if (!Attr)
5980 return;
5981
5982 const char *Kind;
5983 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005984 case MipsInterruptAttr::eic: Kind = "eic"; break;
5985 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
5986 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
5987 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
5988 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
5989 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
5990 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
5991 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
5992 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
5993 }
5994
5995 Fn->addFnAttr("interrupt", Kind);
5996
Reed Kotler373feca2013-01-16 17:10:28 +00005997 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005998
John McCall943fae92010-05-27 06:19:26 +00005999 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006000 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006001
Craig Topper4f12f102014-03-12 06:41:41 +00006002 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006003 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006004 }
John McCall943fae92010-05-27 06:19:26 +00006005};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006006}
John McCall943fae92010-05-27 06:19:26 +00006007
Eric Christopher7565e0d2015-05-29 23:09:49 +00006008void MipsABIInfo::CoerceToIntArgs(
6009 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006010 llvm::IntegerType *IntTy =
6011 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006012
6013 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6014 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6015 ArgList.push_back(IntTy);
6016
6017 // If necessary, add one more integer type to ArgList.
6018 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6019
6020 if (R)
6021 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006022}
6023
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006024// In N32/64, an aligned double precision floating point field is passed in
6025// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006026llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006027 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6028
6029 if (IsO32) {
6030 CoerceToIntArgs(TySize, ArgList);
6031 return llvm::StructType::get(getVMContext(), ArgList);
6032 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006033
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006034 if (Ty->isComplexType())
6035 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006036
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006037 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006038
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006039 // Unions/vectors are passed in integer registers.
6040 if (!RT || !RT->isStructureOrClassType()) {
6041 CoerceToIntArgs(TySize, ArgList);
6042 return llvm::StructType::get(getVMContext(), ArgList);
6043 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006044
6045 const RecordDecl *RD = RT->getDecl();
6046 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006047 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006048
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006049 uint64_t LastOffset = 0;
6050 unsigned idx = 0;
6051 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6052
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006053 // Iterate over fields in the struct/class and check if there are any aligned
6054 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006055 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6056 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006057 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006058 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6059
6060 if (!BT || BT->getKind() != BuiltinType::Double)
6061 continue;
6062
6063 uint64_t Offset = Layout.getFieldOffset(idx);
6064 if (Offset % 64) // Ignore doubles that are not aligned.
6065 continue;
6066
6067 // Add ((Offset - LastOffset) / 64) args of type i64.
6068 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6069 ArgList.push_back(I64);
6070
6071 // Add double type.
6072 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6073 LastOffset = Offset + 64;
6074 }
6075
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006076 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6077 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006078
6079 return llvm::StructType::get(getVMContext(), ArgList);
6080}
6081
Akira Hatanakaddd66342013-10-29 18:41:15 +00006082llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6083 uint64_t Offset) const {
6084 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006085 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006086
Akira Hatanakaddd66342013-10-29 18:41:15 +00006087 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006088}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006089
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006090ABIArgInfo
6091MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006092 Ty = useFirstFieldIfTransparentUnion(Ty);
6093
Akira Hatanaka1632af62012-01-09 19:31:25 +00006094 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006095 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006096 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006097
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006098 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6099 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006100 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6101 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006102
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006103 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006104 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006105 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006106 return ABIArgInfo::getIgnore();
6107
Mark Lacey3825e832013-10-06 01:33:34 +00006108 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006109 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006110 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006111 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006112
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006113 // If we have reached here, aggregates are passed directly by coercing to
6114 // another structure type. Padding is inserted if the offset of the
6115 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006116 ABIArgInfo ArgInfo =
6117 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6118 getPaddingType(OrigOffset, CurrOffset));
6119 ArgInfo.setInReg(true);
6120 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006121 }
6122
6123 // Treat an enum type as its underlying type.
6124 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6125 Ty = EnumTy->getDecl()->getIntegerType();
6126
Daniel Sanders5b445b32014-10-24 14:42:42 +00006127 // All integral types are promoted to the GPR width.
6128 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006129 return ABIArgInfo::getExtend();
6130
Akira Hatanakaddd66342013-10-29 18:41:15 +00006131 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006132 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006133}
6134
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006135llvm::Type*
6136MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006137 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006138 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006139
Akira Hatanakab6f74432012-02-09 18:49:26 +00006140 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006141 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006142 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6143 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006144
Akira Hatanakab6f74432012-02-09 18:49:26 +00006145 // N32/64 returns struct/classes in floating point registers if the
6146 // following conditions are met:
6147 // 1. The size of the struct/class is no larger than 128-bit.
6148 // 2. The struct/class has one or two fields all of which are floating
6149 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006150 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006151 //
6152 // Any other composite results are returned in integer registers.
6153 //
6154 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6155 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6156 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006157 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006158
Akira Hatanakab6f74432012-02-09 18:49:26 +00006159 if (!BT || !BT->isFloatingPoint())
6160 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006161
David Blaikie2d7c57e2012-04-30 02:36:29 +00006162 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006163 }
6164
6165 if (b == e)
6166 return llvm::StructType::get(getVMContext(), RTList,
6167 RD->hasAttr<PackedAttr>());
6168
6169 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006170 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006171 }
6172
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006173 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006174 return llvm::StructType::get(getVMContext(), RTList);
6175}
6176
Akira Hatanakab579fe52011-06-02 00:09:17 +00006177ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006178 uint64_t Size = getContext().getTypeSize(RetTy);
6179
Daniel Sandersed39f582014-09-04 13:28:14 +00006180 if (RetTy->isVoidType())
6181 return ABIArgInfo::getIgnore();
6182
6183 // O32 doesn't treat zero-sized structs differently from other structs.
6184 // However, N32/N64 ignores zero sized return values.
6185 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006186 return ABIArgInfo::getIgnore();
6187
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006188 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006189 if (Size <= 128) {
6190 if (RetTy->isAnyComplexType())
6191 return ABIArgInfo::getDirect();
6192
Daniel Sanderse5018b62014-09-04 15:05:39 +00006193 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006194 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006195 if (!IsO32 ||
6196 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6197 ABIArgInfo ArgInfo =
6198 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6199 ArgInfo.setInReg(true);
6200 return ArgInfo;
6201 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006202 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006203
John McCall7f416cc2015-09-08 08:05:57 +00006204 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006205 }
6206
6207 // Treat an enum type as its underlying type.
6208 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6209 RetTy = EnumTy->getDecl()->getIntegerType();
6210
6211 return (RetTy->isPromotableIntegerType() ?
6212 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6213}
6214
6215void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006216 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006217 if (!getCXXABI().classifyReturnType(FI))
6218 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006219
Eric Christopher7565e0d2015-05-29 23:09:49 +00006220 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006221 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006222
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006223 for (auto &I : FI.arguments())
6224 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006225}
6226
John McCall7f416cc2015-09-08 08:05:57 +00006227Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6228 QualType OrigTy) const {
6229 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006230
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006231 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6232 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006233 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006234 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006235 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006236 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006237 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006238 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006239 DidPromote = true;
6240 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6241 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006242 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006243
John McCall7f416cc2015-09-08 08:05:57 +00006244 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006245
John McCall7f416cc2015-09-08 08:05:57 +00006246 // The alignment of things in the argument area is never larger than
6247 // StackAlignInBytes.
6248 TyInfo.second =
6249 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6250
6251 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6252 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6253
6254 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6255 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6256
6257
6258 // If there was a promotion, "unpromote" into a temporary.
6259 // TODO: can we just use a pointer into a subset of the original slot?
6260 if (DidPromote) {
6261 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6262 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6263
6264 // Truncate down to the right width.
6265 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6266 : CGF.IntPtrTy);
6267 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6268 if (OrigTy->isPointerType())
6269 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6270
6271 CGF.Builder.CreateStore(V, Temp);
6272 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006273 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006274
John McCall7f416cc2015-09-08 08:05:57 +00006275 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006276}
6277
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006278bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6279 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006280
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006281 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6282 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6283 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006284
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006285 return false;
6286}
6287
John McCall943fae92010-05-27 06:19:26 +00006288bool
6289MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6290 llvm::Value *Address) const {
6291 // This information comes from gcc's implementation, which seems to
6292 // as canonical as it gets.
6293
John McCall943fae92010-05-27 06:19:26 +00006294 // Everything on MIPS is 4 bytes. Double-precision FP registers
6295 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006296 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006297
6298 // 0-31 are the general purpose registers, $0 - $31.
6299 // 32-63 are the floating-point registers, $f0 - $f31.
6300 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6301 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006302 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006303
6304 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6305 // They are one bit wide and ignored here.
6306
6307 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6308 // (coprocessor 1 is the FP unit)
6309 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6310 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6311 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006312 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006313 return false;
6314}
6315
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006316//===----------------------------------------------------------------------===//
6317// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006318// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006319// handling.
6320//===----------------------------------------------------------------------===//
6321
6322namespace {
6323
6324class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6325public:
6326 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6327 : DefaultTargetCodeGenInfo(CGT) {}
6328
Eric Christopher162c91c2015-06-05 22:03:00 +00006329 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006330 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006331};
6332
Eric Christopher162c91c2015-06-05 22:03:00 +00006333void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006334 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006335 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006336 if (!FD) return;
6337
6338 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006339
David Blaikiebbafb8a2012-03-11 07:00:24 +00006340 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006341 if (FD->hasAttr<OpenCLKernelAttr>()) {
6342 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006343 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006344 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6345 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006346 // Convert the reqd_work_group_size() attributes to metadata.
6347 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006348 llvm::NamedMDNode *OpenCLMetadata =
6349 M.getModule().getOrInsertNamedMetadata(
6350 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006351
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006352 SmallVector<llvm::Metadata *, 5> Operands;
6353 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006354
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006355 Operands.push_back(
6356 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6357 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6358 Operands.push_back(
6359 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6360 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6361 Operands.push_back(
6362 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6363 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006364
Eric Christopher7565e0d2015-05-29 23:09:49 +00006365 // Add a boolean constant operand for "required" (true) or "hint"
6366 // (false) for implementing the work_group_size_hint attr later.
6367 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006368 Operands.push_back(
6369 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006370 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6371 }
6372 }
6373 }
6374}
6375
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006376}
John McCall943fae92010-05-27 06:19:26 +00006377
Tony Linthicum76329bf2011-12-12 21:14:55 +00006378//===----------------------------------------------------------------------===//
6379// Hexagon ABI Implementation
6380//===----------------------------------------------------------------------===//
6381
6382namespace {
6383
6384class HexagonABIInfo : public ABIInfo {
6385
6386
6387public:
6388 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6389
6390private:
6391
6392 ABIArgInfo classifyReturnType(QualType RetTy) const;
6393 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6394
Craig Topper4f12f102014-03-12 06:41:41 +00006395 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006396
John McCall7f416cc2015-09-08 08:05:57 +00006397 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6398 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006399};
6400
6401class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6402public:
6403 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6404 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6405
Craig Topper4f12f102014-03-12 06:41:41 +00006406 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006407 return 29;
6408 }
6409};
6410
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006411}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006412
6413void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006414 if (!getCXXABI().classifyReturnType(FI))
6415 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006416 for (auto &I : FI.arguments())
6417 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006418}
6419
6420ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6421 if (!isAggregateTypeForABI(Ty)) {
6422 // Treat an enum type as its underlying type.
6423 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6424 Ty = EnumTy->getDecl()->getIntegerType();
6425
6426 return (Ty->isPromotableIntegerType() ?
6427 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6428 }
6429
6430 // Ignore empty records.
6431 if (isEmptyRecord(getContext(), Ty, true))
6432 return ABIArgInfo::getIgnore();
6433
Mark Lacey3825e832013-10-06 01:33:34 +00006434 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006435 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006436
6437 uint64_t Size = getContext().getTypeSize(Ty);
6438 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006439 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006440 // Pass in the smallest viable integer type.
6441 else if (Size > 32)
6442 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6443 else if (Size > 16)
6444 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6445 else if (Size > 8)
6446 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6447 else
6448 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6449}
6450
6451ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6452 if (RetTy->isVoidType())
6453 return ABIArgInfo::getIgnore();
6454
6455 // Large vector types should be returned via memory.
6456 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006457 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006458
6459 if (!isAggregateTypeForABI(RetTy)) {
6460 // Treat an enum type as its underlying type.
6461 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6462 RetTy = EnumTy->getDecl()->getIntegerType();
6463
6464 return (RetTy->isPromotableIntegerType() ?
6465 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6466 }
6467
Tony Linthicum76329bf2011-12-12 21:14:55 +00006468 if (isEmptyRecord(getContext(), RetTy, true))
6469 return ABIArgInfo::getIgnore();
6470
6471 // Aggregates <= 8 bytes are returned in r0; other aggregates
6472 // are returned indirectly.
6473 uint64_t Size = getContext().getTypeSize(RetTy);
6474 if (Size <= 64) {
6475 // Return in the smallest viable integer type.
6476 if (Size <= 8)
6477 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6478 if (Size <= 16)
6479 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6480 if (Size <= 32)
6481 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6482 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6483 }
6484
John McCall7f416cc2015-09-08 08:05:57 +00006485 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006486}
6487
John McCall7f416cc2015-09-08 08:05:57 +00006488Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6489 QualType Ty) const {
6490 // FIXME: Someone needs to audit that this handle alignment correctly.
6491 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6492 getContext().getTypeInfoInChars(Ty),
6493 CharUnits::fromQuantity(4),
6494 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006495}
6496
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006497//===----------------------------------------------------------------------===//
6498// AMDGPU ABI Implementation
6499//===----------------------------------------------------------------------===//
6500
6501namespace {
6502
6503class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6504public:
6505 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6506 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006507 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006508 CodeGen::CodeGenModule &M) const override;
6509};
6510
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006511}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006512
Eric Christopher162c91c2015-06-05 22:03:00 +00006513void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006514 const Decl *D,
6515 llvm::GlobalValue *GV,
6516 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006517 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006518 if (!FD)
6519 return;
6520
6521 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6522 llvm::Function *F = cast<llvm::Function>(GV);
6523 uint32_t NumVGPR = Attr->getNumVGPR();
6524 if (NumVGPR != 0)
6525 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6526 }
6527
6528 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6529 llvm::Function *F = cast<llvm::Function>(GV);
6530 unsigned NumSGPR = Attr->getNumSGPR();
6531 if (NumSGPR != 0)
6532 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6533 }
6534}
6535
Tony Linthicum76329bf2011-12-12 21:14:55 +00006536
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006537//===----------------------------------------------------------------------===//
6538// SPARC v9 ABI Implementation.
6539// Based on the SPARC Compliance Definition version 2.4.1.
6540//
6541// Function arguments a mapped to a nominal "parameter array" and promoted to
6542// registers depending on their type. Each argument occupies 8 or 16 bytes in
6543// the array, structs larger than 16 bytes are passed indirectly.
6544//
6545// One case requires special care:
6546//
6547// struct mixed {
6548// int i;
6549// float f;
6550// };
6551//
6552// When a struct mixed is passed by value, it only occupies 8 bytes in the
6553// parameter array, but the int is passed in an integer register, and the float
6554// is passed in a floating point register. This is represented as two arguments
6555// with the LLVM IR inreg attribute:
6556//
6557// declare void f(i32 inreg %i, float inreg %f)
6558//
6559// The code generator will only allocate 4 bytes from the parameter array for
6560// the inreg arguments. All other arguments are allocated a multiple of 8
6561// bytes.
6562//
6563namespace {
6564class SparcV9ABIInfo : public ABIInfo {
6565public:
6566 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6567
6568private:
6569 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006570 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006571 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6572 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006573
6574 // Coercion type builder for structs passed in registers. The coercion type
6575 // serves two purposes:
6576 //
6577 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6578 // in registers.
6579 // 2. Expose aligned floating point elements as first-level elements, so the
6580 // code generator knows to pass them in floating point registers.
6581 //
6582 // We also compute the InReg flag which indicates that the struct contains
6583 // aligned 32-bit floats.
6584 //
6585 struct CoerceBuilder {
6586 llvm::LLVMContext &Context;
6587 const llvm::DataLayout &DL;
6588 SmallVector<llvm::Type*, 8> Elems;
6589 uint64_t Size;
6590 bool InReg;
6591
6592 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6593 : Context(c), DL(dl), Size(0), InReg(false) {}
6594
6595 // Pad Elems with integers until Size is ToSize.
6596 void pad(uint64_t ToSize) {
6597 assert(ToSize >= Size && "Cannot remove elements");
6598 if (ToSize == Size)
6599 return;
6600
6601 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006602 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006603 if (Aligned > Size && Aligned <= ToSize) {
6604 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6605 Size = Aligned;
6606 }
6607
6608 // Add whole 64-bit words.
6609 while (Size + 64 <= ToSize) {
6610 Elems.push_back(llvm::Type::getInt64Ty(Context));
6611 Size += 64;
6612 }
6613
6614 // Final in-word padding.
6615 if (Size < ToSize) {
6616 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6617 Size = ToSize;
6618 }
6619 }
6620
6621 // Add a floating point element at Offset.
6622 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6623 // Unaligned floats are treated as integers.
6624 if (Offset % Bits)
6625 return;
6626 // The InReg flag is only required if there are any floats < 64 bits.
6627 if (Bits < 64)
6628 InReg = true;
6629 pad(Offset);
6630 Elems.push_back(Ty);
6631 Size = Offset + Bits;
6632 }
6633
6634 // Add a struct type to the coercion type, starting at Offset (in bits).
6635 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6636 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6637 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6638 llvm::Type *ElemTy = StrTy->getElementType(i);
6639 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6640 switch (ElemTy->getTypeID()) {
6641 case llvm::Type::StructTyID:
6642 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6643 break;
6644 case llvm::Type::FloatTyID:
6645 addFloat(ElemOffset, ElemTy, 32);
6646 break;
6647 case llvm::Type::DoubleTyID:
6648 addFloat(ElemOffset, ElemTy, 64);
6649 break;
6650 case llvm::Type::FP128TyID:
6651 addFloat(ElemOffset, ElemTy, 128);
6652 break;
6653 case llvm::Type::PointerTyID:
6654 if (ElemOffset % 64 == 0) {
6655 pad(ElemOffset);
6656 Elems.push_back(ElemTy);
6657 Size += 64;
6658 }
6659 break;
6660 default:
6661 break;
6662 }
6663 }
6664 }
6665
6666 // Check if Ty is a usable substitute for the coercion type.
6667 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006668 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006669 }
6670
6671 // Get the coercion type as a literal struct type.
6672 llvm::Type *getType() const {
6673 if (Elems.size() == 1)
6674 return Elems.front();
6675 else
6676 return llvm::StructType::get(Context, Elems);
6677 }
6678 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006679};
6680} // end anonymous namespace
6681
6682ABIArgInfo
6683SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6684 if (Ty->isVoidType())
6685 return ABIArgInfo::getIgnore();
6686
6687 uint64_t Size = getContext().getTypeSize(Ty);
6688
6689 // Anything too big to fit in registers is passed with an explicit indirect
6690 // pointer / sret pointer.
6691 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006692 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006693
6694 // Treat an enum type as its underlying type.
6695 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6696 Ty = EnumTy->getDecl()->getIntegerType();
6697
6698 // Integer types smaller than a register are extended.
6699 if (Size < 64 && Ty->isIntegerType())
6700 return ABIArgInfo::getExtend();
6701
6702 // Other non-aggregates go in registers.
6703 if (!isAggregateTypeForABI(Ty))
6704 return ABIArgInfo::getDirect();
6705
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006706 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6707 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6708 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006709 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006710
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006711 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006712 // Build a coercion type from the LLVM struct type.
6713 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6714 if (!StrTy)
6715 return ABIArgInfo::getDirect();
6716
6717 CoerceBuilder CB(getVMContext(), getDataLayout());
6718 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006719 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006720
6721 // Try to use the original type for coercion.
6722 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6723
6724 if (CB.InReg)
6725 return ABIArgInfo::getDirectInReg(CoerceTy);
6726 else
6727 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006728}
6729
John McCall7f416cc2015-09-08 08:05:57 +00006730Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6731 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006732 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6733 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6734 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6735 AI.setCoerceToType(ArgTy);
6736
John McCall7f416cc2015-09-08 08:05:57 +00006737 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006738
John McCall7f416cc2015-09-08 08:05:57 +00006739 CGBuilderTy &Builder = CGF.Builder;
6740 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6741 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6742
6743 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
6744
6745 Address ArgAddr = Address::invalid();
6746 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006747 switch (AI.getKind()) {
6748 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006749 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006750 llvm_unreachable("Unsupported ABI kind for va_arg");
6751
John McCall7f416cc2015-09-08 08:05:57 +00006752 case ABIArgInfo::Extend: {
6753 Stride = SlotSize;
6754 CharUnits Offset = SlotSize - TypeInfo.first;
6755 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006756 break;
John McCall7f416cc2015-09-08 08:05:57 +00006757 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006758
John McCall7f416cc2015-09-08 08:05:57 +00006759 case ABIArgInfo::Direct: {
6760 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00006761 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006762 ArgAddr = Addr;
6763 break;
John McCall7f416cc2015-09-08 08:05:57 +00006764 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006765
6766 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006767 Stride = SlotSize;
6768 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
6769 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
6770 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006771 break;
6772
6773 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006774 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006775 }
6776
6777 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006778 llvm::Value *NextPtr =
6779 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
6780 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006781
John McCall7f416cc2015-09-08 08:05:57 +00006782 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006783}
6784
6785void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6786 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006787 for (auto &I : FI.arguments())
6788 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006789}
6790
6791namespace {
6792class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6793public:
6794 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6795 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006796
Craig Topper4f12f102014-03-12 06:41:41 +00006797 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006798 return 14;
6799 }
6800
6801 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006802 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006803};
6804} // end anonymous namespace
6805
Roman Divackyf02c9942014-02-24 18:46:27 +00006806bool
6807SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6808 llvm::Value *Address) const {
6809 // This is calculated from the LLVM and GCC tables and verified
6810 // against gcc output. AFAIK all ABIs use the same encoding.
6811
6812 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6813
6814 llvm::IntegerType *i8 = CGF.Int8Ty;
6815 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6816 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6817
6818 // 0-31: the 8-byte general-purpose registers
6819 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6820
6821 // 32-63: f0-31, the 4-byte floating-point registers
6822 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6823
6824 // Y = 64
6825 // PSR = 65
6826 // WIM = 66
6827 // TBR = 67
6828 // PC = 68
6829 // NPC = 69
6830 // FSR = 70
6831 // CSR = 71
6832 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006833
Roman Divackyf02c9942014-02-24 18:46:27 +00006834 // 72-87: d0-15, the 8-byte floating-point registers
6835 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6836
6837 return false;
6838}
6839
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006840
Robert Lytton0e076492013-08-13 09:43:10 +00006841//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006842// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006843//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006844
Robert Lytton0e076492013-08-13 09:43:10 +00006845namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006846
6847/// A SmallStringEnc instance is used to build up the TypeString by passing
6848/// it by reference between functions that append to it.
6849typedef llvm::SmallString<128> SmallStringEnc;
6850
6851/// TypeStringCache caches the meta encodings of Types.
6852///
6853/// The reason for caching TypeStrings is two fold:
6854/// 1. To cache a type's encoding for later uses;
6855/// 2. As a means to break recursive member type inclusion.
6856///
6857/// A cache Entry can have a Status of:
6858/// NonRecursive: The type encoding is not recursive;
6859/// Recursive: The type encoding is recursive;
6860/// Incomplete: An incomplete TypeString;
6861/// IncompleteUsed: An incomplete TypeString that has been used in a
6862/// Recursive type encoding.
6863///
6864/// A NonRecursive entry will have all of its sub-members expanded as fully
6865/// as possible. Whilst it may contain types which are recursive, the type
6866/// itself is not recursive and thus its encoding may be safely used whenever
6867/// the type is encountered.
6868///
6869/// A Recursive entry will have all of its sub-members expanded as fully as
6870/// possible. The type itself is recursive and it may contain other types which
6871/// are recursive. The Recursive encoding must not be used during the expansion
6872/// of a recursive type's recursive branch. For simplicity the code uses
6873/// IncompleteCount to reject all usage of Recursive encodings for member types.
6874///
6875/// An Incomplete entry is always a RecordType and only encodes its
6876/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6877/// are placed into the cache during type expansion as a means to identify and
6878/// handle recursive inclusion of types as sub-members. If there is recursion
6879/// the entry becomes IncompleteUsed.
6880///
6881/// During the expansion of a RecordType's members:
6882///
6883/// If the cache contains a NonRecursive encoding for the member type, the
6884/// cached encoding is used;
6885///
6886/// If the cache contains a Recursive encoding for the member type, the
6887/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6888///
6889/// If the member is a RecordType, an Incomplete encoding is placed into the
6890/// cache to break potential recursive inclusion of itself as a sub-member;
6891///
6892/// Once a member RecordType has been expanded, its temporary incomplete
6893/// entry is removed from the cache. If a Recursive encoding was swapped out
6894/// it is swapped back in;
6895///
6896/// If an incomplete entry is used to expand a sub-member, the incomplete
6897/// entry is marked as IncompleteUsed. The cache keeps count of how many
6898/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6899///
6900/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6901/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6902/// Else the member is part of a recursive type and thus the recursion has
6903/// been exited too soon for the encoding to be correct for the member.
6904///
6905class TypeStringCache {
6906 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6907 struct Entry {
6908 std::string Str; // The encoded TypeString for the type.
6909 enum Status State; // Information about the encoding in 'Str'.
6910 std::string Swapped; // A temporary place holder for a Recursive encoding
6911 // during the expansion of RecordType's members.
6912 };
6913 std::map<const IdentifierInfo *, struct Entry> Map;
6914 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6915 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6916public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006917 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006918 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6919 bool removeIncomplete(const IdentifierInfo *ID);
6920 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6921 bool IsRecursive);
6922 StringRef lookupStr(const IdentifierInfo *ID);
6923};
6924
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006925/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006926/// FieldEncoding is a helper for this ordering process.
6927class FieldEncoding {
6928 bool HasName;
6929 std::string Enc;
6930public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006931 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6932 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006933 bool operator<(const FieldEncoding &rhs) const {
6934 if (HasName != rhs.HasName) return HasName;
6935 return Enc < rhs.Enc;
6936 }
6937};
6938
Robert Lytton7d1db152013-08-19 09:46:39 +00006939class XCoreABIInfo : public DefaultABIInfo {
6940public:
6941 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00006942 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6943 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006944};
6945
Robert Lyttond21e2d72014-03-03 13:45:29 +00006946class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006947 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006948public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006949 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006950 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006951 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6952 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006953};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006954
Robert Lytton2d196952013-10-11 10:29:34 +00006955} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006956
John McCall7f416cc2015-09-08 08:05:57 +00006957Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6958 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006959 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006960
Robert Lytton2d196952013-10-11 10:29:34 +00006961 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006962 CharUnits SlotSize = CharUnits::fromQuantity(4);
6963 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00006964
Robert Lytton2d196952013-10-11 10:29:34 +00006965 // Handle the argument.
6966 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006967 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00006968 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6969 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6970 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006971 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00006972
6973 Address Val = Address::invalid();
6974 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00006975 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006976 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006977 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006978 llvm_unreachable("Unsupported ABI kind for va_arg");
6979 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006980 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
6981 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00006982 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006983 case ABIArgInfo::Extend:
6984 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00006985 Val = Builder.CreateBitCast(AP, ArgPtrTy);
6986 ArgSize = CharUnits::fromQuantity(
6987 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00006988 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00006989 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006990 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006991 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
6992 Val = Address(Builder.CreateLoad(Val), TypeAlign);
6993 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00006994 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006995 }
Robert Lytton2d196952013-10-11 10:29:34 +00006996
6997 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006998 if (!ArgSize.isZero()) {
6999 llvm::Value *APN =
7000 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7001 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007002 }
John McCall7f416cc2015-09-08 08:05:57 +00007003
Robert Lytton2d196952013-10-11 10:29:34 +00007004 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007005}
Robert Lytton0e076492013-08-13 09:43:10 +00007006
Robert Lytton844aeeb2014-05-02 09:33:20 +00007007/// During the expansion of a RecordType, an incomplete TypeString is placed
7008/// into the cache as a means to identify and break recursion.
7009/// If there is a Recursive encoding in the cache, it is swapped out and will
7010/// be reinserted by removeIncomplete().
7011/// All other types of encoding should have been used rather than arriving here.
7012void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7013 std::string StubEnc) {
7014 if (!ID)
7015 return;
7016 Entry &E = Map[ID];
7017 assert( (E.Str.empty() || E.State == Recursive) &&
7018 "Incorrectly use of addIncomplete");
7019 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7020 E.Swapped.swap(E.Str); // swap out the Recursive
7021 E.Str.swap(StubEnc);
7022 E.State = Incomplete;
7023 ++IncompleteCount;
7024}
7025
7026/// Once the RecordType has been expanded, the temporary incomplete TypeString
7027/// must be removed from the cache.
7028/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7029/// Returns true if the RecordType was defined recursively.
7030bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7031 if (!ID)
7032 return false;
7033 auto I = Map.find(ID);
7034 assert(I != Map.end() && "Entry not present");
7035 Entry &E = I->second;
7036 assert( (E.State == Incomplete ||
7037 E.State == IncompleteUsed) &&
7038 "Entry must be an incomplete type");
7039 bool IsRecursive = false;
7040 if (E.State == IncompleteUsed) {
7041 // We made use of our Incomplete encoding, thus we are recursive.
7042 IsRecursive = true;
7043 --IncompleteUsedCount;
7044 }
7045 if (E.Swapped.empty())
7046 Map.erase(I);
7047 else {
7048 // Swap the Recursive back.
7049 E.Swapped.swap(E.Str);
7050 E.Swapped.clear();
7051 E.State = Recursive;
7052 }
7053 --IncompleteCount;
7054 return IsRecursive;
7055}
7056
7057/// Add the encoded TypeString to the cache only if it is NonRecursive or
7058/// Recursive (viz: all sub-members were expanded as fully as possible).
7059void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7060 bool IsRecursive) {
7061 if (!ID || IncompleteUsedCount)
7062 return; // No key or it is is an incomplete sub-type so don't add.
7063 Entry &E = Map[ID];
7064 if (IsRecursive && !E.Str.empty()) {
7065 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7066 "This is not the same Recursive entry");
7067 // The parent container was not recursive after all, so we could have used
7068 // this Recursive sub-member entry after all, but we assumed the worse when
7069 // we started viz: IncompleteCount!=0.
7070 return;
7071 }
7072 assert(E.Str.empty() && "Entry already present");
7073 E.Str = Str.str();
7074 E.State = IsRecursive? Recursive : NonRecursive;
7075}
7076
7077/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7078/// are recursively expanding a type (IncompleteCount != 0) and the cached
7079/// encoding is Recursive, return an empty StringRef.
7080StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7081 if (!ID)
7082 return StringRef(); // We have no key.
7083 auto I = Map.find(ID);
7084 if (I == Map.end())
7085 return StringRef(); // We have no encoding.
7086 Entry &E = I->second;
7087 if (E.State == Recursive && IncompleteCount)
7088 return StringRef(); // We don't use Recursive encodings for member types.
7089
7090 if (E.State == Incomplete) {
7091 // The incomplete type is being used to break out of recursion.
7092 E.State = IncompleteUsed;
7093 ++IncompleteUsedCount;
7094 }
7095 return E.Str.c_str();
7096}
7097
7098/// The XCore ABI includes a type information section that communicates symbol
7099/// type information to the linker. The linker uses this information to verify
7100/// safety/correctness of things such as array bound and pointers et al.
7101/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7102/// This type information (TypeString) is emitted into meta data for all global
7103/// symbols: definitions, declarations, functions & variables.
7104///
7105/// The TypeString carries type, qualifier, name, size & value details.
7106/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007107/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007108/// The output is tested by test/CodeGen/xcore-stringtype.c.
7109///
7110static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7111 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7112
7113/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7114void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7115 CodeGen::CodeGenModule &CGM) const {
7116 SmallStringEnc Enc;
7117 if (getTypeString(Enc, D, CGM, TSC)) {
7118 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007119 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7120 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007121 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7122 llvm::NamedMDNode *MD =
7123 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7124 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7125 }
7126}
7127
7128static bool appendType(SmallStringEnc &Enc, QualType QType,
7129 const CodeGen::CodeGenModule &CGM,
7130 TypeStringCache &TSC);
7131
7132/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007133/// Builds a SmallVector containing the encoded field types in declaration
7134/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007135static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7136 const RecordDecl *RD,
7137 const CodeGen::CodeGenModule &CGM,
7138 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007139 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007140 SmallStringEnc Enc;
7141 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007142 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007143 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007144 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007145 Enc += "b(";
7146 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007147 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007148 Enc += ':';
7149 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007150 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007151 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007152 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007153 Enc += ')';
7154 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007155 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007156 }
7157 return true;
7158}
7159
7160/// Appends structure and union types to Enc and adds encoding to cache.
7161/// Recursively calls appendType (via extractFieldType) for each field.
7162/// Union types have their fields ordered according to the ABI.
7163static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7164 const CodeGen::CodeGenModule &CGM,
7165 TypeStringCache &TSC, const IdentifierInfo *ID) {
7166 // Append the cached TypeString if we have one.
7167 StringRef TypeString = TSC.lookupStr(ID);
7168 if (!TypeString.empty()) {
7169 Enc += TypeString;
7170 return true;
7171 }
7172
7173 // Start to emit an incomplete TypeString.
7174 size_t Start = Enc.size();
7175 Enc += (RT->isUnionType()? 'u' : 's');
7176 Enc += '(';
7177 if (ID)
7178 Enc += ID->getName();
7179 Enc += "){";
7180
7181 // We collect all encoded fields and order as necessary.
7182 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007183 const RecordDecl *RD = RT->getDecl()->getDefinition();
7184 if (RD && !RD->field_empty()) {
7185 // An incomplete TypeString stub is placed in the cache for this RecordType
7186 // so that recursive calls to this RecordType will use it whilst building a
7187 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007188 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007189 std::string StubEnc(Enc.substr(Start).str());
7190 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7191 TSC.addIncomplete(ID, std::move(StubEnc));
7192 if (!extractFieldType(FE, RD, CGM, TSC)) {
7193 (void) TSC.removeIncomplete(ID);
7194 return false;
7195 }
7196 IsRecursive = TSC.removeIncomplete(ID);
7197 // The ABI requires unions to be sorted but not structures.
7198 // See FieldEncoding::operator< for sort algorithm.
7199 if (RT->isUnionType())
7200 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007201 // We can now complete the TypeString.
7202 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007203 for (unsigned I = 0; I != E; ++I) {
7204 if (I)
7205 Enc += ',';
7206 Enc += FE[I].str();
7207 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007208 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007209 Enc += '}';
7210 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7211 return true;
7212}
7213
7214/// Appends enum types to Enc and adds the encoding to the cache.
7215static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7216 TypeStringCache &TSC,
7217 const IdentifierInfo *ID) {
7218 // Append the cached TypeString if we have one.
7219 StringRef TypeString = TSC.lookupStr(ID);
7220 if (!TypeString.empty()) {
7221 Enc += TypeString;
7222 return true;
7223 }
7224
7225 size_t Start = Enc.size();
7226 Enc += "e(";
7227 if (ID)
7228 Enc += ID->getName();
7229 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007230
7231 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007232 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007233 SmallVector<FieldEncoding, 16> FE;
7234 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7235 ++I) {
7236 SmallStringEnc EnumEnc;
7237 EnumEnc += "m(";
7238 EnumEnc += I->getName();
7239 EnumEnc += "){";
7240 I->getInitVal().toString(EnumEnc);
7241 EnumEnc += '}';
7242 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7243 }
7244 std::sort(FE.begin(), FE.end());
7245 unsigned E = FE.size();
7246 for (unsigned I = 0; I != E; ++I) {
7247 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007248 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007249 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007250 }
7251 }
7252 Enc += '}';
7253 TSC.addIfComplete(ID, Enc.substr(Start), false);
7254 return true;
7255}
7256
7257/// Appends type's qualifier to Enc.
7258/// This is done prior to appending the type's encoding.
7259static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7260 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007261 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007262 int Lookup = 0;
7263 if (QT.isConstQualified())
7264 Lookup += 1<<0;
7265 if (QT.isRestrictQualified())
7266 Lookup += 1<<1;
7267 if (QT.isVolatileQualified())
7268 Lookup += 1<<2;
7269 Enc += Table[Lookup];
7270}
7271
7272/// Appends built-in types to Enc.
7273static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7274 const char *EncType;
7275 switch (BT->getKind()) {
7276 case BuiltinType::Void:
7277 EncType = "0";
7278 break;
7279 case BuiltinType::Bool:
7280 EncType = "b";
7281 break;
7282 case BuiltinType::Char_U:
7283 EncType = "uc";
7284 break;
7285 case BuiltinType::UChar:
7286 EncType = "uc";
7287 break;
7288 case BuiltinType::SChar:
7289 EncType = "sc";
7290 break;
7291 case BuiltinType::UShort:
7292 EncType = "us";
7293 break;
7294 case BuiltinType::Short:
7295 EncType = "ss";
7296 break;
7297 case BuiltinType::UInt:
7298 EncType = "ui";
7299 break;
7300 case BuiltinType::Int:
7301 EncType = "si";
7302 break;
7303 case BuiltinType::ULong:
7304 EncType = "ul";
7305 break;
7306 case BuiltinType::Long:
7307 EncType = "sl";
7308 break;
7309 case BuiltinType::ULongLong:
7310 EncType = "ull";
7311 break;
7312 case BuiltinType::LongLong:
7313 EncType = "sll";
7314 break;
7315 case BuiltinType::Float:
7316 EncType = "ft";
7317 break;
7318 case BuiltinType::Double:
7319 EncType = "d";
7320 break;
7321 case BuiltinType::LongDouble:
7322 EncType = "ld";
7323 break;
7324 default:
7325 return false;
7326 }
7327 Enc += EncType;
7328 return true;
7329}
7330
7331/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7332static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7333 const CodeGen::CodeGenModule &CGM,
7334 TypeStringCache &TSC) {
7335 Enc += "p(";
7336 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7337 return false;
7338 Enc += ')';
7339 return true;
7340}
7341
7342/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007343static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7344 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007345 const CodeGen::CodeGenModule &CGM,
7346 TypeStringCache &TSC, StringRef NoSizeEnc) {
7347 if (AT->getSizeModifier() != ArrayType::Normal)
7348 return false;
7349 Enc += "a(";
7350 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7351 CAT->getSize().toStringUnsigned(Enc);
7352 else
7353 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7354 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007355 // The Qualifiers should be attached to the type rather than the array.
7356 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007357 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7358 return false;
7359 Enc += ')';
7360 return true;
7361}
7362
7363/// Appends a function encoding to Enc, calling appendType for the return type
7364/// and the arguments.
7365static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7366 const CodeGen::CodeGenModule &CGM,
7367 TypeStringCache &TSC) {
7368 Enc += "f{";
7369 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7370 return false;
7371 Enc += "}(";
7372 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7373 // N.B. we are only interested in the adjusted param types.
7374 auto I = FPT->param_type_begin();
7375 auto E = FPT->param_type_end();
7376 if (I != E) {
7377 do {
7378 if (!appendType(Enc, *I, CGM, TSC))
7379 return false;
7380 ++I;
7381 if (I != E)
7382 Enc += ',';
7383 } while (I != E);
7384 if (FPT->isVariadic())
7385 Enc += ",va";
7386 } else {
7387 if (FPT->isVariadic())
7388 Enc += "va";
7389 else
7390 Enc += '0';
7391 }
7392 }
7393 Enc += ')';
7394 return true;
7395}
7396
7397/// Handles the type's qualifier before dispatching a call to handle specific
7398/// type encodings.
7399static bool appendType(SmallStringEnc &Enc, QualType QType,
7400 const CodeGen::CodeGenModule &CGM,
7401 TypeStringCache &TSC) {
7402
7403 QualType QT = QType.getCanonicalType();
7404
Robert Lytton6adb20f2014-06-05 09:06:21 +00007405 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7406 // The Qualifiers should be attached to the type rather than the array.
7407 // Thus we don't call appendQualifier() here.
7408 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7409
Robert Lytton844aeeb2014-05-02 09:33:20 +00007410 appendQualifier(Enc, QT);
7411
7412 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7413 return appendBuiltinType(Enc, BT);
7414
Robert Lytton844aeeb2014-05-02 09:33:20 +00007415 if (const PointerType *PT = QT->getAs<PointerType>())
7416 return appendPointerType(Enc, PT, CGM, TSC);
7417
7418 if (const EnumType *ET = QT->getAs<EnumType>())
7419 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7420
7421 if (const RecordType *RT = QT->getAsStructureType())
7422 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7423
7424 if (const RecordType *RT = QT->getAsUnionType())
7425 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7426
7427 if (const FunctionType *FT = QT->getAs<FunctionType>())
7428 return appendFunctionType(Enc, FT, CGM, TSC);
7429
7430 return false;
7431}
7432
7433static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7434 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7435 if (!D)
7436 return false;
7437
7438 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7439 if (FD->getLanguageLinkage() != CLanguageLinkage)
7440 return false;
7441 return appendType(Enc, FD->getType(), CGM, TSC);
7442 }
7443
7444 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7445 if (VD->getLanguageLinkage() != CLanguageLinkage)
7446 return false;
7447 QualType QT = VD->getType().getCanonicalType();
7448 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7449 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007450 // The Qualifiers should be attached to the type rather than the array.
7451 // Thus we don't call appendQualifier() here.
7452 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007453 }
7454 return appendType(Enc, QT, CGM, TSC);
7455 }
7456 return false;
7457}
7458
7459
Robert Lytton0e076492013-08-13 09:43:10 +00007460//===----------------------------------------------------------------------===//
7461// Driver code
7462//===----------------------------------------------------------------------===//
7463
Rafael Espindola9f834732014-09-19 01:54:22 +00007464const llvm::Triple &CodeGenModule::getTriple() const {
7465 return getTarget().getTriple();
7466}
7467
7468bool CodeGenModule::supportsCOMDAT() const {
7469 return !getTriple().isOSBinFormatMachO();
7470}
7471
Chris Lattner2b037972010-07-29 02:01:43 +00007472const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007473 if (TheTargetCodeGenInfo)
7474 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007475
John McCallc8e01702013-04-16 22:48:15 +00007476 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007477 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007478 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007479 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007480
Derek Schuff09338a22012-09-06 17:37:28 +00007481 case llvm::Triple::le32:
7482 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007483 case llvm::Triple::mips:
7484 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007485 if (Triple.getOS() == llvm::Triple::NaCl)
7486 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007487 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7488
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007489 case llvm::Triple::mips64:
7490 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007491 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7492
Tim Northover25e8a672014-05-24 12:51:25 +00007493 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007494 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007495 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007496 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007497 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007498
Tim Northover573cbee2014-05-24 12:52:07 +00007499 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007500 }
7501
Dan Gohmanc2853072015-09-03 22:51:53 +00007502 case llvm::Triple::wasm32:
7503 case llvm::Triple::wasm64:
7504 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7505
Daniel Dunbard59655c2009-09-12 00:59:49 +00007506 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007507 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007508 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007509 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007510 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007511 if (Triple.getOS() == llvm::Triple::Win32) {
7512 TheTargetCodeGenInfo =
7513 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7514 return *TheTargetCodeGenInfo;
7515 }
7516
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007517 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Tim Northover5627d392015-10-30 16:30:45 +00007518 StringRef ABIStr = getTarget().getABI();
7519 if (ABIStr == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007520 Kind = ARMABIInfo::APCS;
Tim Northover5627d392015-10-30 16:30:45 +00007521 else if (ABIStr == "aapcs16")
7522 Kind = ARMABIInfo::AAPCS16_VFP;
David Tweed8f676532012-10-25 13:33:01 +00007523 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007524 (CodeGenOpts.FloatABI != "soft" &&
7525 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007526 Kind = ARMABIInfo::AAPCS_VFP;
7527
Derek Schuff71658bd2015-01-29 00:47:04 +00007528 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007529 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007530
John McCallea8d8bb2010-03-11 00:10:12 +00007531 case llvm::Triple::ppc:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00007532 return *(TheTargetCodeGenInfo =
7533 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007534 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007535 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007536 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007537 if (getTarget().getABI() == "elfv2")
7538 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007539 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007540
Ulrich Weigandb7122372014-07-21 00:48:09 +00007541 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007542 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007543 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007544 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007545 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007546 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007547 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007548 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007549 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007550 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007551
Ulrich Weigandb7122372014-07-21 00:48:09 +00007552 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007553 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007554 }
John McCallea8d8bb2010-03-11 00:10:12 +00007555
Peter Collingbournec947aae2012-05-20 23:28:41 +00007556 case llvm::Triple::nvptx:
7557 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007558 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007559
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007560 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007561 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007562
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007563 case llvm::Triple::systemz: {
7564 bool HasVector = getTarget().getABI() == "vector";
7565 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7566 HasVector));
7567 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007568
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007569 case llvm::Triple::tce:
7570 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7571
Eli Friedman33465822011-07-08 23:31:17 +00007572 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007573 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007574 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007575 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007576 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007577
John McCall1fe2a8c2013-06-18 02:46:29 +00007578 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007579 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007580 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Eric Christopher7565e0d2015-05-29 23:09:49 +00007581 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007582 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007583 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007584 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00007585 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7586 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007587 }
Eli Friedman33465822011-07-08 23:31:17 +00007588 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007589
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007590 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007591 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007592 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7593 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007594 X86AVXABILevel::None);
7595
Chris Lattner04dc9572010-08-31 16:44:54 +00007596 switch (Triple.getOS()) {
7597 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007598 return *(TheTargetCodeGenInfo =
7599 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007600 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007601 return *(TheTargetCodeGenInfo =
7602 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007603 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007604 return *(TheTargetCodeGenInfo =
7605 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007606 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007607 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007608 case llvm::Triple::hexagon:
7609 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007610 case llvm::Triple::r600:
7611 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007612 case llvm::Triple::amdgcn:
7613 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007614 case llvm::Triple::sparcv9:
7615 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007616 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007617 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007618 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007619}