blob: 1cfdde38a368ae086c86912be340e3259d95cb3a [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)
367 return 0;
368 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
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001122 // Small structures which are register sized are generally returned
1123 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001124 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001125 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001126
1127 // As a special-case, if the struct is a "single-element" struct, and
1128 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001129 // floating-point register. (MSVC does not apply this special case.)
1130 // We apply a similar transformation for pointer types to improve the
1131 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001132 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001133 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001134 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001135 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1136
1137 // FIXME: We should be able to narrow this integer in cases with dead
1138 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001139 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001140 }
1141
John McCall7f416cc2015-09-08 08:05:57 +00001142 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001143 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001144
Chris Lattner458b2aa2010-07-29 02:16:43 +00001145 // Treat an enum type as its underlying type.
1146 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1147 RetTy = EnumTy->getDecl()->getIntegerType();
1148
1149 return (RetTy->isPromotableIntegerType() ?
1150 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001151}
1152
Eli Friedman7919bea2012-06-05 19:40:46 +00001153static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1154 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1155}
1156
Daniel Dunbared23de32010-09-16 20:42:00 +00001157static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1158 const RecordType *RT = Ty->getAs<RecordType>();
1159 if (!RT)
1160 return 0;
1161 const RecordDecl *RD = RT->getDecl();
1162
1163 // If this is a C++ record, check the bases first.
1164 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001165 for (const auto &I : CXXRD->bases())
1166 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001167 return false;
1168
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001169 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001170 QualType FT = i->getType();
1171
Eli Friedman7919bea2012-06-05 19:40:46 +00001172 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001173 return true;
1174
1175 if (isRecordWithSSEVectorType(Context, FT))
1176 return true;
1177 }
1178
1179 return false;
1180}
1181
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001182unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1183 unsigned Align) const {
1184 // Otherwise, if the alignment is less than or equal to the minimum ABI
1185 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001186 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001187 return 0; // Use default alignment.
1188
1189 // On non-Darwin, the stack type alignment is always 4.
1190 if (!IsDarwinVectorABI) {
1191 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001192 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001193 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001194
Daniel Dunbared23de32010-09-16 20:42:00 +00001195 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001196 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1197 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001198 return 16;
1199
1200 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001201}
1202
Rafael Espindola703c47f2012-10-19 05:04:37 +00001203ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001204 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001205 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001206 if (State.FreeRegs) {
1207 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001208 if (!IsMCUABI)
1209 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001210 }
John McCall7f416cc2015-09-08 08:05:57 +00001211 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001212 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001213
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001214 // Compute the byval alignment.
1215 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1216 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1217 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001218 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001219
1220 // If the stack alignment is less than the type alignment, realign the
1221 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001222 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001223 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1224 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001225}
1226
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001227X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1228 const Type *T = isSingleElementStruct(Ty, getContext());
1229 if (!T)
1230 T = Ty.getTypePtr();
1231
1232 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1233 BuiltinType::Kind K = BT->getKind();
1234 if (K == BuiltinType::Float || K == BuiltinType::Double)
1235 return Float;
1236 }
1237 return Integer;
1238}
1239
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001240bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001241 if (!IsSoftFloatABI) {
1242 Class C = classify(Ty);
1243 if (C == Float)
1244 return false;
1245 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001246
Rafael Espindola077dd592012-10-24 01:58:58 +00001247 unsigned Size = getContext().getTypeSize(Ty);
1248 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001249
1250 if (SizeInRegs == 0)
1251 return false;
1252
Michael Kuperstein68901882015-10-25 08:18:20 +00001253 if (!IsMCUABI) {
1254 if (SizeInRegs > State.FreeRegs) {
1255 State.FreeRegs = 0;
1256 return false;
1257 }
1258 } else {
1259 // The MCU psABI allows passing parameters in-reg even if there are
1260 // earlier parameters that are passed on the stack. Also,
1261 // it does not allow passing >8-byte structs in-register,
1262 // even if there are 3 free registers available.
1263 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1264 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001265 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001266
Reid Kleckner661f35b2014-01-18 01:12:41 +00001267 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001268 return true;
1269}
1270
1271bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1272 bool &InReg,
1273 bool &NeedsPadding) const {
1274 NeedsPadding = false;
1275 InReg = !IsMCUABI;
1276
1277 if (!updateFreeRegs(Ty, State))
1278 return false;
1279
1280 if (IsMCUABI)
1281 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001282
Reid Kleckner80944df2014-10-31 22:00:51 +00001283 if (State.CC == llvm::CallingConv::X86_FastCall ||
1284 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001285 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001286 NeedsPadding = true;
1287
Rafael Espindola077dd592012-10-24 01:58:58 +00001288 return false;
1289 }
1290
Rafael Espindola703c47f2012-10-19 05:04:37 +00001291 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001292}
1293
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001294bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1295 if (!updateFreeRegs(Ty, State))
1296 return false;
1297
1298 if (IsMCUABI)
1299 return false;
1300
1301 if (State.CC == llvm::CallingConv::X86_FastCall ||
1302 State.CC == llvm::CallingConv::X86_VectorCall) {
1303 if (getContext().getTypeSize(Ty) > 32)
1304 return false;
1305
1306 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1307 Ty->isReferenceType());
1308 }
1309
1310 return true;
1311}
1312
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001313ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1314 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001315 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001316
Reid Klecknerb1be6832014-11-15 01:41:41 +00001317 Ty = useFirstFieldIfTransparentUnion(Ty);
1318
Reid Kleckner80944df2014-10-31 22:00:51 +00001319 // Check with the C++ ABI first.
1320 const RecordType *RT = Ty->getAs<RecordType>();
1321 if (RT) {
1322 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1323 if (RAA == CGCXXABI::RAA_Indirect) {
1324 return getIndirectResult(Ty, false, State);
1325 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1326 // The field index doesn't matter, we'll fix it up later.
1327 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1328 }
1329 }
1330
1331 // vectorcall adds the concept of a homogenous vector aggregate, similar
1332 // to other targets.
1333 const Type *Base = nullptr;
1334 uint64_t NumElts = 0;
1335 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1336 isHomogeneousAggregate(Ty, Base, NumElts)) {
1337 if (State.FreeSSERegs >= NumElts) {
1338 State.FreeSSERegs -= NumElts;
1339 if (Ty->isBuiltinType() || Ty->isVectorType())
1340 return ABIArgInfo::getDirect();
1341 return ABIArgInfo::getExpand();
1342 }
1343 return getIndirectResult(Ty, /*ByVal=*/false, State);
1344 }
1345
1346 if (isAggregateTypeForABI(Ty)) {
1347 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001348 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001349 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001350 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001351
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001352 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001353 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001354 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001355 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001356
Eli Friedman9f061a32011-11-18 00:28:11 +00001357 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001358 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001359 return ABIArgInfo::getIgnore();
1360
Rafael Espindolafad28de2012-10-24 01:59:00 +00001361 llvm::LLVMContext &LLVMContext = getVMContext();
1362 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001363 bool NeedsPadding, InReg;
1364 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001365 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001366 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001367 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001368 if (InReg)
1369 return ABIArgInfo::getDirectInReg(Result);
1370 else
1371 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001372 }
Craig Topper8a13c412014-05-21 05:09:00 +00001373 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001374
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001375 // Expand small (<= 128-bit) record types when we know that the stack layout
1376 // of those arguments will match the struct. This is important because the
1377 // LLVM backend isn't smart enough to remove byval, which inhibits many
1378 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001379 // Don't do this for the MCU if there are still free integer registers
1380 // (see X86_64 ABI for full explanation).
Chris Lattner458b2aa2010-07-29 02:16:43 +00001381 if (getContext().getTypeSize(Ty) <= 4*32 &&
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001382 canExpandIndirectArgument(Ty, getContext()) &&
1383 (!IsMCUABI || State.FreeRegs == 0))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001384 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001385 State.CC == llvm::CallingConv::X86_FastCall ||
1386 State.CC == llvm::CallingConv::X86_VectorCall,
1387 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001388
Reid Kleckner661f35b2014-01-18 01:12:41 +00001389 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001390 }
1391
Chris Lattnerd774ae92010-08-26 20:05:13 +00001392 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001393 // On Darwin, some vectors are passed in memory, we handle this by passing
1394 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001395 if (IsDarwinVectorABI) {
1396 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001397 if ((Size == 8 || Size == 16 || Size == 32) ||
1398 (Size == 64 && VT->getNumElements() == 1))
1399 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1400 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001401 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001402
Chad Rosier651c1832013-03-25 21:00:27 +00001403 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1404 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001405
Chris Lattnerd774ae92010-08-26 20:05:13 +00001406 return ABIArgInfo::getDirect();
1407 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001408
1409
Chris Lattner458b2aa2010-07-29 02:16:43 +00001410 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1411 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001412
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001413 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001414
1415 if (Ty->isPromotableIntegerType()) {
1416 if (InReg)
1417 return ABIArgInfo::getExtendInReg();
1418 return ABIArgInfo::getExtend();
1419 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001420
Rafael Espindola703c47f2012-10-19 05:04:37 +00001421 if (InReg)
1422 return ABIArgInfo::getDirectInReg();
1423 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001424}
1425
Rafael Espindolaa6472962012-07-24 00:01:07 +00001426void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001427 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001428 if (IsMCUABI)
1429 State.FreeRegs = 3;
1430 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001431 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001432 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1433 State.FreeRegs = 2;
1434 State.FreeSSERegs = 6;
1435 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001436 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001437 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001438 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001439
Reid Kleckner677539d2014-07-10 01:58:55 +00001440 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001441 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001442 } else if (FI.getReturnInfo().isIndirect()) {
1443 // The C++ ABI is not aware of register usage, so we have to check if the
1444 // return value was sret and put it in a register ourselves if appropriate.
1445 if (State.FreeRegs) {
1446 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001447 if (!IsMCUABI)
1448 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001449 }
1450 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001451
Peter Collingbournef7706832014-12-12 23:41:25 +00001452 // The chain argument effectively gives us another free register.
1453 if (FI.isChainCall())
1454 ++State.FreeRegs;
1455
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001456 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001457 for (auto &I : FI.arguments()) {
1458 I.info = classifyArgumentType(I.type, State);
1459 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001460 }
1461
1462 // If we needed to use inalloca for any argument, do a second pass and rewrite
1463 // all the memory arguments to use inalloca.
1464 if (UsedInAlloca)
1465 rewriteWithInAlloca(FI);
1466}
1467
1468void
1469X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001470 CharUnits &StackOffset, ABIArgInfo &Info,
1471 QualType Type) const {
1472 // Arguments are always 4-byte-aligned.
1473 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1474
1475 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001476 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1477 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001478 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001479
John McCall7f416cc2015-09-08 08:05:57 +00001480 // Insert padding bytes to respect alignment.
1481 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001482 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001483 if (StackOffset != FieldEnd) {
1484 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001485 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001486 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001487 FrameFields.push_back(Ty);
1488 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001489}
1490
Reid Kleckner852361d2014-07-26 00:12:26 +00001491static bool isArgInAlloca(const ABIArgInfo &Info) {
1492 // Leave ignored and inreg arguments alone.
1493 switch (Info.getKind()) {
1494 case ABIArgInfo::InAlloca:
1495 return true;
1496 case ABIArgInfo::Indirect:
1497 assert(Info.getIndirectByVal());
1498 return true;
1499 case ABIArgInfo::Ignore:
1500 return false;
1501 case ABIArgInfo::Direct:
1502 case ABIArgInfo::Extend:
1503 case ABIArgInfo::Expand:
1504 if (Info.getInReg())
1505 return false;
1506 return true;
1507 }
1508 llvm_unreachable("invalid enum");
1509}
1510
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001511void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1512 assert(IsWin32StructABI && "inalloca only supported on win32");
1513
1514 // Build a packed struct type for all of the arguments in memory.
1515 SmallVector<llvm::Type *, 6> FrameFields;
1516
John McCall7f416cc2015-09-08 08:05:57 +00001517 // The stack alignment is always 4.
1518 CharUnits StackAlign = CharUnits::fromQuantity(4);
1519
1520 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001521 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1522
1523 // Put 'this' into the struct before 'sret', if necessary.
1524 bool IsThisCall =
1525 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1526 ABIArgInfo &Ret = FI.getReturnInfo();
1527 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1528 isArgInAlloca(I->info)) {
1529 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1530 ++I;
1531 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001532
1533 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001534 if (Ret.isIndirect() && !Ret.getInReg()) {
1535 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1536 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001537 // On Windows, the hidden sret parameter is always returned in eax.
1538 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001539 }
1540
1541 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001542 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001543 ++I;
1544
1545 // Put arguments passed in memory into the struct.
1546 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001547 if (isArgInAlloca(I->info))
1548 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001549 }
1550
1551 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001552 /*isPacked=*/true),
1553 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001554}
1555
John McCall7f416cc2015-09-08 08:05:57 +00001556Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1557 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001558
John McCall7f416cc2015-09-08 08:05:57 +00001559 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001560
John McCall7f416cc2015-09-08 08:05:57 +00001561 // x86-32 changes the alignment of certain arguments on the stack.
1562 //
1563 // Just messing with TypeInfo like this works because we never pass
1564 // anything indirectly.
1565 TypeInfo.second = CharUnits::fromQuantity(
1566 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001567
John McCall7f416cc2015-09-08 08:05:57 +00001568 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1569 TypeInfo, CharUnits::fromQuantity(4),
1570 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001571}
1572
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001573bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1574 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1575 assert(Triple.getArch() == llvm::Triple::x86);
1576
1577 switch (Opts.getStructReturnConvention()) {
1578 case CodeGenOptions::SRCK_Default:
1579 break;
1580 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1581 return false;
1582 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1583 return true;
1584 }
1585
Michael Kupersteind749f232015-10-27 07:46:22 +00001586 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001587 return true;
1588
1589 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001590 case llvm::Triple::DragonFly:
1591 case llvm::Triple::FreeBSD:
1592 case llvm::Triple::OpenBSD:
1593 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001594 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001595 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001596 default:
1597 return false;
1598 }
1599}
1600
Eric Christopher162c91c2015-06-05 22:03:00 +00001601void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001602 llvm::GlobalValue *GV,
1603 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001604 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001605 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1606 // Get the LLVM function.
1607 llvm::Function *Fn = cast<llvm::Function>(GV);
1608
1609 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001610 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001611 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001612 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1613 llvm::AttributeSet::get(CGM.getLLVMContext(),
1614 llvm::AttributeSet::FunctionIndex,
1615 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001616 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001617 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1618 llvm::Function *Fn = cast<llvm::Function>(GV);
1619 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1620 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001621 }
1622}
1623
John McCallbeec5a02010-03-06 00:35:14 +00001624bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1625 CodeGen::CodeGenFunction &CGF,
1626 llvm::Value *Address) const {
1627 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001628
Chris Lattnerece04092012-02-07 00:39:47 +00001629 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001630
John McCallbeec5a02010-03-06 00:35:14 +00001631 // 0-7 are the eight integer registers; the order is different
1632 // on Darwin (for EH), but the range is the same.
1633 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001634 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001635
John McCallc8e01702013-04-16 22:48:15 +00001636 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001637 // 12-16 are st(0..4). Not sure why we stop at 4.
1638 // These have size 16, which is sizeof(long double) on
1639 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001640 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001641 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001642
John McCallbeec5a02010-03-06 00:35:14 +00001643 } else {
1644 // 9 is %eflags, which doesn't get a size on Darwin for some
1645 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001646 Builder.CreateAlignedStore(
1647 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1648 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001649
1650 // 11-16 are st(0..5). Not sure why we stop at 5.
1651 // These have size 12, which is sizeof(long double) on
1652 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001653 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001654 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1655 }
John McCallbeec5a02010-03-06 00:35:14 +00001656
1657 return false;
1658}
1659
Chris Lattner0cf24192010-06-28 20:05:43 +00001660//===----------------------------------------------------------------------===//
1661// X86-64 ABI Implementation
1662//===----------------------------------------------------------------------===//
1663
1664
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001665namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001666/// The AVX ABI level for X86 targets.
1667enum class X86AVXABILevel {
1668 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001669 AVX,
1670 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001671};
1672
1673/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1674static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1675 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001676 case X86AVXABILevel::AVX512:
1677 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001678 case X86AVXABILevel::AVX:
1679 return 256;
1680 case X86AVXABILevel::None:
1681 return 128;
1682 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001683 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001684}
1685
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001686/// X86_64ABIInfo - The X86_64 ABI information.
1687class X86_64ABIInfo : public ABIInfo {
1688 enum Class {
1689 Integer = 0,
1690 SSE,
1691 SSEUp,
1692 X87,
1693 X87Up,
1694 ComplexX87,
1695 NoClass,
1696 Memory
1697 };
1698
1699 /// merge - Implement the X86_64 ABI merging algorithm.
1700 ///
1701 /// Merge an accumulating classification \arg Accum with a field
1702 /// classification \arg Field.
1703 ///
1704 /// \param Accum - The accumulating classification. This should
1705 /// always be either NoClass or the result of a previous merge
1706 /// call. In addition, this should never be Memory (the caller
1707 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001708 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001709
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001710 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1711 ///
1712 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1713 /// final MEMORY or SSE classes when necessary.
1714 ///
1715 /// \param AggregateSize - The size of the current aggregate in
1716 /// the classification process.
1717 ///
1718 /// \param Lo - The classification for the parts of the type
1719 /// residing in the low word of the containing object.
1720 ///
1721 /// \param Hi - The classification for the parts of the type
1722 /// residing in the higher words of the containing object.
1723 ///
1724 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1725
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001726 /// classify - Determine the x86_64 register classes in which the
1727 /// given type T should be passed.
1728 ///
1729 /// \param Lo - The classification for the parts of the type
1730 /// residing in the low word of the containing object.
1731 ///
1732 /// \param Hi - The classification for the parts of the type
1733 /// residing in the high word of the containing object.
1734 ///
1735 /// \param OffsetBase - The bit offset of this type in the
1736 /// containing object. Some parameters are classified different
1737 /// depending on whether they straddle an eightbyte boundary.
1738 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001739 /// \param isNamedArg - Whether the argument in question is a "named"
1740 /// argument, as used in AMD64-ABI 3.5.7.
1741 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001742 /// If a word is unused its result will be NoClass; if a type should
1743 /// be passed in Memory then at least the classification of \arg Lo
1744 /// will be Memory.
1745 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001746 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001747 ///
1748 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1749 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001750 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1751 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001752
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001753 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001754 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1755 unsigned IROffset, QualType SourceTy,
1756 unsigned SourceOffset) const;
1757 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1758 unsigned IROffset, QualType SourceTy,
1759 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001760
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001761 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001762 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001763 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001764
1765 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001766 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001767 ///
1768 /// \param freeIntRegs - The number of free integer registers remaining
1769 /// available.
1770 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001771
Chris Lattner458b2aa2010-07-29 02:16:43 +00001772 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001773
Bill Wendling5cd41c42010-10-18 03:41:31 +00001774 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001775 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001776 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001777 unsigned &neededSSE,
1778 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001779
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001780 bool IsIllegalVectorType(QualType Ty) const;
1781
John McCalle0fda732011-04-21 01:20:55 +00001782 /// The 0.98 ABI revision clarified a lot of ambiguities,
1783 /// unfortunately in ways that were not always consistent with
1784 /// certain previous compilers. In particular, platforms which
1785 /// required strict binary compatibility with older versions of GCC
1786 /// may need to exempt themselves.
1787 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001788 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001789 }
1790
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001791 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001792 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1793 // 64-bit hardware.
1794 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001795
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001796public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001797 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1798 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001799 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001800 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001801
John McCalla729c622012-02-17 03:33:10 +00001802 bool isPassedUsingAVXType(QualType type) const {
1803 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001804 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001805 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1806 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001807 if (info.isDirect()) {
1808 llvm::Type *ty = info.getCoerceToType();
1809 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1810 return (vectorTy->getBitWidth() > 128);
1811 }
1812 return false;
1813 }
1814
Craig Topper4f12f102014-03-12 06:41:41 +00001815 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001816
John McCall7f416cc2015-09-08 08:05:57 +00001817 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1818 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001819 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1820 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001821
1822 bool has64BitPointers() const {
1823 return Has64BitPointers;
1824 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001825};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001826
Chris Lattner04dc9572010-08-31 16:44:54 +00001827/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001828class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001829public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001830 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1831 : ABIInfo(CGT),
1832 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001833
Craig Topper4f12f102014-03-12 06:41:41 +00001834 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001835
John McCall7f416cc2015-09-08 08:05:57 +00001836 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1837 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001838
1839 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1840 // FIXME: Assumes vectorcall is in use.
1841 return isX86VectorTypeForVectorCall(getContext(), Ty);
1842 }
1843
1844 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1845 uint64_t NumMembers) const override {
1846 // FIXME: Assumes vectorcall is in use.
1847 return isX86VectorCallAggregateSmallEnough(NumMembers);
1848 }
Reid Kleckner11a17192015-10-28 22:29:52 +00001849
1850private:
1851 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1852 bool IsReturnType) const;
1853
1854 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00001855};
1856
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001857class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1858public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001859 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001860 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001861
John McCalla729c622012-02-17 03:33:10 +00001862 const X86_64ABIInfo &getABIInfo() const {
1863 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1864 }
1865
Craig Topper4f12f102014-03-12 06:41:41 +00001866 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001867 return 7;
1868 }
1869
1870 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001871 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001872 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001873
John McCall943fae92010-05-27 06:19:26 +00001874 // 0-15 are the 16 integer registers.
1875 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001876 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001877 return false;
1878 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001879
Jay Foad7c57be32011-07-11 09:56:20 +00001880 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001881 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001882 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001883 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1884 }
1885
John McCalla729c622012-02-17 03:33:10 +00001886 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001887 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001888 // The default CC on x86-64 sets %al to the number of SSA
1889 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001890 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001891 // that when AVX types are involved: the ABI explicitly states it is
1892 // undefined, and it doesn't work in practice because of how the ABI
1893 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001894 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001895 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001896 for (CallArgList::const_iterator
1897 it = args.begin(), ie = args.end(); it != ie; ++it) {
1898 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1899 HasAVXType = true;
1900 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001901 }
1902 }
John McCalla729c622012-02-17 03:33:10 +00001903
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001904 if (!HasAVXType)
1905 return true;
1906 }
John McCallcbc038a2011-09-21 08:08:30 +00001907
John McCalla729c622012-02-17 03:33:10 +00001908 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001909 }
1910
Craig Topper4f12f102014-03-12 06:41:41 +00001911 llvm::Constant *
1912 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001913 unsigned Sig;
1914 if (getABIInfo().has64BitPointers())
1915 Sig = (0xeb << 0) | // jmp rel8
1916 (0x0a << 8) | // .+0x0c
1917 ('F' << 16) |
1918 ('T' << 24);
1919 else
1920 Sig = (0xeb << 0) | // jmp rel8
1921 (0x06 << 8) | // .+0x08
1922 ('F' << 16) |
1923 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001924 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1925 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001926
1927 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1928 CodeGen::CodeGenModule &CGM) const override {
1929 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1930 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1931 llvm::Function *Fn = cast<llvm::Function>(GV);
1932 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1933 }
1934 }
1935 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001936};
1937
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001938class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1939public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001940 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1941 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001942
1943 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001944 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001945 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00001946 // If the argument contains a space, enclose it in quotes.
1947 if (Lib.find(" ") != StringRef::npos)
1948 Opt += "\"" + Lib.str() + "\"";
1949 else
1950 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001951 }
1952};
1953
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001954static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001955 // If the argument does not end in .lib, automatically add the suffix.
1956 // If the argument contains a space, enclose it in quotes.
1957 // This matches the behavior of MSVC.
1958 bool Quote = (Lib.find(" ") != StringRef::npos);
1959 std::string ArgStr = Quote ? "\"" : "";
1960 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001961 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001962 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001963 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001964 return ArgStr;
1965}
1966
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001967class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1968public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001969 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00001970 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
1971 unsigned NumRegisterParameters)
1972 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001973 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001974
Eric Christopher162c91c2015-06-05 22:03:00 +00001975 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001976 CodeGen::CodeGenModule &CGM) const override;
1977
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001978 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001979 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001980 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001981 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001982 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001983
1984 void getDetectMismatchOption(llvm::StringRef Name,
1985 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001986 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001987 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001988 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001989};
1990
Hans Wennborg77dc2362015-01-20 19:45:50 +00001991static void addStackProbeSizeTargetAttribute(const Decl *D,
1992 llvm::GlobalValue *GV,
1993 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001994 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00001995 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1996 llvm::Function *Fn = cast<llvm::Function>(GV);
1997
Eric Christopher7565e0d2015-05-29 23:09:49 +00001998 Fn->addFnAttr("stack-probe-size",
1999 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002000 }
2001 }
2002}
2003
Eric Christopher162c91c2015-06-05 22:03:00 +00002004void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002005 llvm::GlobalValue *GV,
2006 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002007 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002008
2009 addStackProbeSizeTargetAttribute(D, GV, CGM);
2010}
2011
Chris Lattner04dc9572010-08-31 16:44:54 +00002012class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2013public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002014 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2015 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002016 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002017
Eric Christopher162c91c2015-06-05 22:03:00 +00002018 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002019 CodeGen::CodeGenModule &CGM) const override;
2020
Craig Topper4f12f102014-03-12 06:41:41 +00002021 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002022 return 7;
2023 }
2024
2025 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002026 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002027 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002028
Chris Lattner04dc9572010-08-31 16:44:54 +00002029 // 0-15 are the 16 integer registers.
2030 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002031 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002032 return false;
2033 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002034
2035 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002036 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002037 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002038 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002039 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002040
2041 void getDetectMismatchOption(llvm::StringRef Name,
2042 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002043 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002044 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002045 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002046};
2047
Eric Christopher162c91c2015-06-05 22:03:00 +00002048void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002049 llvm::GlobalValue *GV,
2050 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002051 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002052
Alexey Bataevd51e9932016-01-15 04:06:31 +00002053 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2054 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2055 llvm::Function *Fn = cast<llvm::Function>(GV);
2056 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2057 }
2058 }
2059
Hans Wennborg77dc2362015-01-20 19:45:50 +00002060 addStackProbeSizeTargetAttribute(D, GV, CGM);
2061}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002062}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002063
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002064void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2065 Class &Hi) const {
2066 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2067 //
2068 // (a) If one of the classes is Memory, the whole argument is passed in
2069 // memory.
2070 //
2071 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2072 // memory.
2073 //
2074 // (c) If the size of the aggregate exceeds two eightbytes and the first
2075 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2076 // argument is passed in memory. NOTE: This is necessary to keep the
2077 // ABI working for processors that don't support the __m256 type.
2078 //
2079 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2080 //
2081 // Some of these are enforced by the merging logic. Others can arise
2082 // only with unions; for example:
2083 // union { _Complex double; unsigned; }
2084 //
2085 // Note that clauses (b) and (c) were added in 0.98.
2086 //
2087 if (Hi == Memory)
2088 Lo = Memory;
2089 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2090 Lo = Memory;
2091 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2092 Lo = Memory;
2093 if (Hi == SSEUp && Lo != SSE)
2094 Hi = SSE;
2095}
2096
Chris Lattnerd776fb12010-06-28 21:43:59 +00002097X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002098 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2099 // classified recursively so that always two fields are
2100 // considered. The resulting class is calculated according to
2101 // the classes of the fields in the eightbyte:
2102 //
2103 // (a) If both classes are equal, this is the resulting class.
2104 //
2105 // (b) If one of the classes is NO_CLASS, the resulting class is
2106 // the other class.
2107 //
2108 // (c) If one of the classes is MEMORY, the result is the MEMORY
2109 // class.
2110 //
2111 // (d) If one of the classes is INTEGER, the result is the
2112 // INTEGER.
2113 //
2114 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2115 // MEMORY is used as class.
2116 //
2117 // (f) Otherwise class SSE is used.
2118
2119 // Accum should never be memory (we should have returned) or
2120 // ComplexX87 (because this cannot be passed in a structure).
2121 assert((Accum != Memory && Accum != ComplexX87) &&
2122 "Invalid accumulated classification during merge.");
2123 if (Accum == Field || Field == NoClass)
2124 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002125 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002126 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002127 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002128 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002129 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002130 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002131 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2132 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002133 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002134 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002135}
2136
Chris Lattner5c740f12010-06-30 19:14:05 +00002137void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002138 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002139 // FIXME: This code can be simplified by introducing a simple value class for
2140 // Class pairs with appropriate constructor methods for the various
2141 // situations.
2142
2143 // FIXME: Some of the split computations are wrong; unaligned vectors
2144 // shouldn't be passed in registers for example, so there is no chance they
2145 // can straddle an eightbyte. Verify & simplify.
2146
2147 Lo = Hi = NoClass;
2148
2149 Class &Current = OffsetBase < 64 ? Lo : Hi;
2150 Current = Memory;
2151
John McCall9dd450b2009-09-21 23:43:11 +00002152 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002153 BuiltinType::Kind k = BT->getKind();
2154
2155 if (k == BuiltinType::Void) {
2156 Current = NoClass;
2157 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2158 Lo = Integer;
2159 Hi = Integer;
2160 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2161 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002162 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002163 Current = SSE;
2164 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002165 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2166 if (LDF == &llvm::APFloat::IEEEquad) {
2167 Lo = SSE;
2168 Hi = SSEUp;
2169 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2170 Lo = X87;
2171 Hi = X87Up;
2172 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2173 Current = SSE;
2174 } else
2175 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002176 }
2177 // FIXME: _Decimal32 and _Decimal64 are SSE.
2178 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002179 return;
2180 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002181
Chris Lattnerd776fb12010-06-28 21:43:59 +00002182 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002183 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002184 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002185 return;
2186 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002187
Chris Lattnerd776fb12010-06-28 21:43:59 +00002188 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002189 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002190 return;
2191 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002192
Chris Lattnerd776fb12010-06-28 21:43:59 +00002193 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002194 if (Ty->isMemberFunctionPointerType()) {
2195 if (Has64BitPointers) {
2196 // If Has64BitPointers, this is an {i64, i64}, so classify both
2197 // Lo and Hi now.
2198 Lo = Hi = Integer;
2199 } else {
2200 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2201 // straddles an eightbyte boundary, Hi should be classified as well.
2202 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2203 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2204 if (EB_FuncPtr != EB_ThisAdj) {
2205 Lo = Hi = Integer;
2206 } else {
2207 Current = Integer;
2208 }
2209 }
2210 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002211 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002212 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002213 return;
2214 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002215
Chris Lattnerd776fb12010-06-28 21:43:59 +00002216 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002217 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002218 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2219 // gcc passes the following as integer:
2220 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2221 // 2 bytes - <2 x char>, <1 x short>
2222 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002223 Current = Integer;
2224
2225 // If this type crosses an eightbyte boundary, it should be
2226 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002227 uint64_t EB_Lo = (OffsetBase) / 64;
2228 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2229 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002230 Hi = Lo;
2231 } else if (Size == 64) {
2232 // gcc passes <1 x double> in memory. :(
2233 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
2234 return;
2235
2236 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00002237 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00002238 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2239 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
2240 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002241 Current = Integer;
2242 else
2243 Current = SSE;
2244
2245 // If this type crosses an eightbyte boundary, it should be
2246 // split.
2247 if (OffsetBase && OffsetBase != 64)
2248 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002249 } else if (Size == 128 ||
2250 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002251 // Arguments of 256-bits are split into four eightbyte chunks. The
2252 // least significant one belongs to class SSE and all the others to class
2253 // SSEUP. The original Lo and Hi design considers that types can't be
2254 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2255 // This design isn't correct for 256-bits, but since there're no cases
2256 // where the upper parts would need to be inspected, avoid adding
2257 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002258 //
2259 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2260 // registers if they are "named", i.e. not part of the "..." of a
2261 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002262 //
2263 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2264 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002265 Lo = SSE;
2266 Hi = SSEUp;
2267 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002268 return;
2269 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002270
Chris Lattnerd776fb12010-06-28 21:43:59 +00002271 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002272 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002273
Chris Lattner2b037972010-07-29 02:01:43 +00002274 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002275 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002276 if (Size <= 64)
2277 Current = Integer;
2278 else if (Size <= 128)
2279 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002280 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002281 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002282 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002283 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002284 } else if (ET == getContext().LongDoubleTy) {
2285 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2286 if (LDF == &llvm::APFloat::IEEEquad)
2287 Current = Memory;
2288 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2289 Current = ComplexX87;
2290 else if (LDF == &llvm::APFloat::IEEEdouble)
2291 Lo = Hi = SSE;
2292 else
2293 llvm_unreachable("unexpected long double representation!");
2294 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002295
2296 // If this complex type crosses an eightbyte boundary then it
2297 // should be split.
2298 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002299 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002300 if (Hi == NoClass && EB_Real != EB_Imag)
2301 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002302
Chris Lattnerd776fb12010-06-28 21:43:59 +00002303 return;
2304 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002305
Chris Lattner2b037972010-07-29 02:01:43 +00002306 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002307 // Arrays are treated like structures.
2308
Chris Lattner2b037972010-07-29 02:01:43 +00002309 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002310
2311 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002312 // than four eightbytes, ..., it has class MEMORY.
2313 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002314 return;
2315
2316 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2317 // fields, it has class MEMORY.
2318 //
2319 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002320 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002321 return;
2322
2323 // Otherwise implement simplified merge. We could be smarter about
2324 // this, but it isn't worth it and would be harder to verify.
2325 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002326 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002327 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002328
2329 // The only case a 256-bit wide vector could be used is when the array
2330 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2331 // to work for sizes wider than 128, early check and fallback to memory.
2332 if (Size > 128 && EltSize != 256)
2333 return;
2334
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002335 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2336 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002337 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002338 Lo = merge(Lo, FieldLo);
2339 Hi = merge(Hi, FieldHi);
2340 if (Lo == Memory || Hi == Memory)
2341 break;
2342 }
2343
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002344 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002345 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002346 return;
2347 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002348
Chris Lattnerd776fb12010-06-28 21:43:59 +00002349 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002350 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002351
2352 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002353 // than four eightbytes, ..., it has class MEMORY.
2354 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002355 return;
2356
Anders Carlsson20759ad2009-09-16 15:53:40 +00002357 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2358 // copy constructor or a non-trivial destructor, it is passed by invisible
2359 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002360 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002361 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002362
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002363 const RecordDecl *RD = RT->getDecl();
2364
2365 // Assume variable sized types are passed in memory.
2366 if (RD->hasFlexibleArrayMember())
2367 return;
2368
Chris Lattner2b037972010-07-29 02:01:43 +00002369 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002370
2371 // Reset Lo class, this will be recomputed.
2372 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002373
2374 // If this is a C++ record, classify the bases first.
2375 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002376 for (const auto &I : CXXRD->bases()) {
2377 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002378 "Unexpected base class!");
2379 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002380 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002381
2382 // Classify this field.
2383 //
2384 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2385 // single eightbyte, each is classified separately. Each eightbyte gets
2386 // initialized to class NO_CLASS.
2387 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002388 uint64_t Offset =
2389 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002390 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002391 Lo = merge(Lo, FieldLo);
2392 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002393 if (Lo == Memory || Hi == Memory) {
2394 postMerge(Size, Lo, Hi);
2395 return;
2396 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002397 }
2398 }
2399
2400 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002401 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002402 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002403 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002404 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2405 bool BitField = i->isBitField();
2406
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002407 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2408 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002409 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002410 // The only case a 256-bit wide vector could be used is when the struct
2411 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2412 // to work for sizes wider than 128, early check and fallback to memory.
2413 //
2414 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2415 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002416 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002417 return;
2418 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002419 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002420 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002421 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002422 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002423 return;
2424 }
2425
2426 // Classify this field.
2427 //
2428 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2429 // exceeds a single eightbyte, each is classified
2430 // separately. Each eightbyte gets initialized to class
2431 // NO_CLASS.
2432 Class FieldLo, FieldHi;
2433
2434 // Bit-fields require special handling, they do not force the
2435 // structure to be passed in memory even if unaligned, and
2436 // therefore they can straddle an eightbyte.
2437 if (BitField) {
2438 // Ignore padding bit-fields.
2439 if (i->isUnnamedBitfield())
2440 continue;
2441
2442 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002443 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002444
2445 uint64_t EB_Lo = Offset / 64;
2446 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002447
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002448 if (EB_Lo) {
2449 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2450 FieldLo = NoClass;
2451 FieldHi = Integer;
2452 } else {
2453 FieldLo = Integer;
2454 FieldHi = EB_Hi ? Integer : NoClass;
2455 }
2456 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002457 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002458 Lo = merge(Lo, FieldLo);
2459 Hi = merge(Hi, FieldHi);
2460 if (Lo == Memory || Hi == Memory)
2461 break;
2462 }
2463
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002464 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002465 }
2466}
2467
Chris Lattner22a931e2010-06-29 06:01:59 +00002468ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002469 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2470 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002471 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002472 // Treat an enum type as its underlying type.
2473 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2474 Ty = EnumTy->getDecl()->getIntegerType();
2475
2476 return (Ty->isPromotableIntegerType() ?
2477 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2478 }
2479
John McCall7f416cc2015-09-08 08:05:57 +00002480 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002481}
2482
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002483bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2484 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2485 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002486 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002487 if (Size <= 64 || Size > LargestVector)
2488 return true;
2489 }
2490
2491 return false;
2492}
2493
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002494ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2495 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002496 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2497 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002498 //
2499 // This assumption is optimistic, as there could be free registers available
2500 // when we need to pass this argument in memory, and LLVM could try to pass
2501 // the argument in the free register. This does not seem to happen currently,
2502 // but this code would be much safer if we could mark the argument with
2503 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002504 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002505 // Treat an enum type as its underlying type.
2506 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2507 Ty = EnumTy->getDecl()->getIntegerType();
2508
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002509 return (Ty->isPromotableIntegerType() ?
2510 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002511 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002512
Mark Lacey3825e832013-10-06 01:33:34 +00002513 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002514 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002515
Chris Lattner44c2b902011-05-22 23:21:23 +00002516 // Compute the byval alignment. We specify the alignment of the byval in all
2517 // cases so that the mid-level optimizer knows the alignment of the byval.
2518 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002519
2520 // Attempt to avoid passing indirect results using byval when possible. This
2521 // is important for good codegen.
2522 //
2523 // We do this by coercing the value into a scalar type which the backend can
2524 // handle naturally (i.e., without using byval).
2525 //
2526 // For simplicity, we currently only do this when we have exhausted all of the
2527 // free integer registers. Doing this when there are free integer registers
2528 // would require more care, as we would have to ensure that the coerced value
2529 // did not claim the unused register. That would require either reording the
2530 // arguments to the function (so that any subsequent inreg values came first),
2531 // or only doing this optimization when there were no following arguments that
2532 // might be inreg.
2533 //
2534 // We currently expect it to be rare (particularly in well written code) for
2535 // arguments to be passed on the stack when there are still free integer
2536 // registers available (this would typically imply large structs being passed
2537 // by value), so this seems like a fair tradeoff for now.
2538 //
2539 // We can revisit this if the backend grows support for 'onstack' parameter
2540 // attributes. See PR12193.
2541 if (freeIntRegs == 0) {
2542 uint64_t Size = getContext().getTypeSize(Ty);
2543
2544 // If this type fits in an eightbyte, coerce it into the matching integral
2545 // type, which will end up on the stack (with alignment 8).
2546 if (Align == 8 && Size <= 64)
2547 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2548 Size));
2549 }
2550
John McCall7f416cc2015-09-08 08:05:57 +00002551 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002552}
2553
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002554/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2555/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002556llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002557 // Wrapper structs/arrays that only contain vectors are passed just like
2558 // vectors; strip them off if present.
2559 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2560 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002561
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002562 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002563 if (isa<llvm::VectorType>(IRType) ||
2564 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002565 return IRType;
2566
2567 // We couldn't find the preferred IR vector type for 'Ty'.
2568 uint64_t Size = getContext().getTypeSize(Ty);
2569 assert((Size == 128 || Size == 256) && "Invalid type found!");
2570
2571 // Return a LLVM IR vector type based on the size of 'Ty'.
2572 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2573 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002574}
2575
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002576/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2577/// is known to either be off the end of the specified type or being in
2578/// alignment padding. The user type specified is known to be at most 128 bits
2579/// in size, and have passed through X86_64ABIInfo::classify with a successful
2580/// classification that put one of the two halves in the INTEGER class.
2581///
2582/// It is conservatively correct to return false.
2583static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2584 unsigned EndBit, ASTContext &Context) {
2585 // If the bytes being queried are off the end of the type, there is no user
2586 // data hiding here. This handles analysis of builtins, vectors and other
2587 // types that don't contain interesting padding.
2588 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2589 if (TySize <= StartBit)
2590 return true;
2591
Chris Lattner98076a22010-07-29 07:43:55 +00002592 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2593 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2594 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2595
2596 // Check each element to see if the element overlaps with the queried range.
2597 for (unsigned i = 0; i != NumElts; ++i) {
2598 // If the element is after the span we care about, then we're done..
2599 unsigned EltOffset = i*EltSize;
2600 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002601
Chris Lattner98076a22010-07-29 07:43:55 +00002602 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2603 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2604 EndBit-EltOffset, Context))
2605 return false;
2606 }
2607 // If it overlaps no elements, then it is safe to process as padding.
2608 return true;
2609 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002610
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002611 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2612 const RecordDecl *RD = RT->getDecl();
2613 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002614
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002615 // If this is a C++ record, check the bases first.
2616 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002617 for (const auto &I : CXXRD->bases()) {
2618 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002619 "Unexpected base class!");
2620 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002621 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002622
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002623 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002624 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002625 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002626
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002627 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002628 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002629 EndBit-BaseOffset, Context))
2630 return false;
2631 }
2632 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002633
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002634 // Verify that no field has data that overlaps the region of interest. Yes
2635 // this could be sped up a lot by being smarter about queried fields,
2636 // however we're only looking at structs up to 16 bytes, so we don't care
2637 // much.
2638 unsigned idx = 0;
2639 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2640 i != e; ++i, ++idx) {
2641 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002642
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002643 // If we found a field after the region we care about, then we're done.
2644 if (FieldOffset >= EndBit) break;
2645
2646 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2647 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2648 Context))
2649 return false;
2650 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002651
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002652 // If nothing in this record overlapped the area of interest, then we're
2653 // clean.
2654 return true;
2655 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002656
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002657 return false;
2658}
2659
Chris Lattnere556a712010-07-29 18:39:32 +00002660/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2661/// float member at the specified offset. For example, {int,{float}} has a
2662/// float at offset 4. It is conservatively correct for this routine to return
2663/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002664static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002665 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002666 // Base case if we find a float.
2667 if (IROffset == 0 && IRType->isFloatTy())
2668 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002669
Chris Lattnere556a712010-07-29 18:39:32 +00002670 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002671 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002672 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2673 unsigned Elt = SL->getElementContainingOffset(IROffset);
2674 IROffset -= SL->getElementOffset(Elt);
2675 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2676 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002677
Chris Lattnere556a712010-07-29 18:39:32 +00002678 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002679 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2680 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002681 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2682 IROffset -= IROffset/EltSize*EltSize;
2683 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2684 }
2685
2686 return false;
2687}
2688
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002689
2690/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2691/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002692llvm::Type *X86_64ABIInfo::
2693GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002694 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002695 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002696 // pass as float if the last 4 bytes is just padding. This happens for
2697 // structs that contain 3 floats.
2698 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2699 SourceOffset*8+64, getContext()))
2700 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002701
Chris Lattnere556a712010-07-29 18:39:32 +00002702 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2703 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2704 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002705 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2706 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002707 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002708
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002709 return llvm::Type::getDoubleTy(getVMContext());
2710}
2711
2712
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002713/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2714/// an 8-byte GPR. This means that we either have a scalar or we are talking
2715/// about the high or low part of an up-to-16-byte struct. This routine picks
2716/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002717/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2718/// etc).
2719///
2720/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2721/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2722/// the 8-byte value references. PrefType may be null.
2723///
Alp Toker9907f082014-07-09 14:06:35 +00002724/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002725/// an offset into this that we're processing (which is always either 0 or 8).
2726///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002727llvm::Type *X86_64ABIInfo::
2728GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002729 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002730 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2731 // returning an 8-byte unit starting with it. See if we can safely use it.
2732 if (IROffset == 0) {
2733 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002734 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2735 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002736 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002737
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002738 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2739 // goodness in the source type is just tail padding. This is allowed to
2740 // kick in for struct {double,int} on the int, but not on
2741 // struct{double,int,int} because we wouldn't return the second int. We
2742 // have to do this analysis on the source type because we can't depend on
2743 // unions being lowered a specific way etc.
2744 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002745 IRType->isIntegerTy(32) ||
2746 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2747 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2748 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002749
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002750 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2751 SourceOffset*8+64, getContext()))
2752 return IRType;
2753 }
2754 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002755
Chris Lattner2192fe52011-07-18 04:24:23 +00002756 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002757 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002758 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002759 if (IROffset < SL->getSizeInBytes()) {
2760 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2761 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002762
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002763 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2764 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002765 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002766 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002767
Chris Lattner2192fe52011-07-18 04:24:23 +00002768 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002769 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002770 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002771 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002772 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2773 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002774 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002775
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002776 // Okay, we don't have any better idea of what to pass, so we pass this in an
2777 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002778 unsigned TySizeInBytes =
2779 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002780
Chris Lattner3f763422010-07-29 17:34:39 +00002781 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002782
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002783 // It is always safe to classify this as an integer type up to i64 that
2784 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002785 return llvm::IntegerType::get(getVMContext(),
2786 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002787}
2788
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002789
2790/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2791/// be used as elements of a two register pair to pass or return, return a
2792/// first class aggregate to represent them. For example, if the low part of
2793/// a by-value argument should be passed as i32* and the high part as float,
2794/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002795static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002796GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002797 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002798 // In order to correctly satisfy the ABI, we need to the high part to start
2799 // at offset 8. If the high and low parts we inferred are both 4-byte types
2800 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2801 // the second element at offset 8. Check for this:
2802 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2803 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002804 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002805 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002806
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002807 // To handle this, we have to increase the size of the low part so that the
2808 // second element will start at an 8 byte offset. We can't increase the size
2809 // of the second element because it might make us access off the end of the
2810 // struct.
2811 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002812 // There are usually two sorts of types the ABI generation code can produce
2813 // for the low part of a pair that aren't 8 bytes in size: float or
2814 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2815 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002816 // Promote these to a larger type.
2817 if (Lo->isFloatTy())
2818 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2819 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002820 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2821 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002822 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2823 }
2824 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002825
Reid Kleckneree7cf842014-12-01 22:02:27 +00002826 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002827
2828
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002829 // Verify that the second element is at an 8-byte offset.
2830 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2831 "Invalid x86-64 argument pair!");
2832 return Result;
2833}
2834
Chris Lattner31faff52010-07-28 23:06:14 +00002835ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002836classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002837 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2838 // classification algorithm.
2839 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002840 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002841
2842 // Check some invariants.
2843 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002844 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2845
Craig Topper8a13c412014-05-21 05:09:00 +00002846 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002847 switch (Lo) {
2848 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002849 if (Hi == NoClass)
2850 return ABIArgInfo::getIgnore();
2851 // If the low part is just padding, it takes no register, leave ResType
2852 // null.
2853 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2854 "Unknown missing lo part");
2855 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002856
2857 case SSEUp:
2858 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002859 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002860
2861 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2862 // hidden argument.
2863 case Memory:
2864 return getIndirectReturnResult(RetTy);
2865
2866 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2867 // available register of the sequence %rax, %rdx is used.
2868 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002869 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002870
Chris Lattner1f3a0632010-07-29 21:42:50 +00002871 // If we have a sign or zero extended integer, make sure to return Extend
2872 // so that the parameter gets the right LLVM IR attributes.
2873 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2874 // Treat an enum type as its underlying type.
2875 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2876 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002877
Chris Lattner1f3a0632010-07-29 21:42:50 +00002878 if (RetTy->isIntegralOrEnumerationType() &&
2879 RetTy->isPromotableIntegerType())
2880 return ABIArgInfo::getExtend();
2881 }
Chris Lattner31faff52010-07-28 23:06:14 +00002882 break;
2883
2884 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2885 // available SSE register of the sequence %xmm0, %xmm1 is used.
2886 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002887 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002888 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002889
2890 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2891 // returned on the X87 stack in %st0 as 80-bit x87 number.
2892 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002893 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002894 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002895
2896 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2897 // part of the value is returned in %st0 and the imaginary part in
2898 // %st1.
2899 case ComplexX87:
2900 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002901 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002902 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002903 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002904 break;
2905 }
2906
Craig Topper8a13c412014-05-21 05:09:00 +00002907 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002908 switch (Hi) {
2909 // Memory was handled previously and X87 should
2910 // never occur as a hi class.
2911 case Memory:
2912 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002913 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002914
2915 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002916 case NoClass:
2917 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002918
Chris Lattner52b3c132010-09-01 00:20:33 +00002919 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002920 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002921 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2922 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002923 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002924 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002925 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002926 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2927 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002928 break;
2929
2930 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002931 // is passed in the next available eightbyte chunk if the last used
2932 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002933 //
Chris Lattner57540c52011-04-15 05:22:18 +00002934 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002935 case SSEUp:
2936 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002937 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002938 break;
2939
2940 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2941 // returned together with the previous X87 value in %st0.
2942 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002943 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002944 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002945 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002946 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002947 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002948 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002949 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2950 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002951 }
Chris Lattner31faff52010-07-28 23:06:14 +00002952 break;
2953 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002954
Chris Lattner52b3c132010-09-01 00:20:33 +00002955 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002956 // known to pass in the high eightbyte of the result. We do this by forming a
2957 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002958 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002959 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002960
Chris Lattner1f3a0632010-07-29 21:42:50 +00002961 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002962}
2963
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002964ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002965 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2966 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002967 const
2968{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002969 Ty = useFirstFieldIfTransparentUnion(Ty);
2970
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002971 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002972 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002973
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002974 // Check some invariants.
2975 // FIXME: Enforce these by construction.
2976 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002977 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2978
2979 neededInt = 0;
2980 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002981 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002982 switch (Lo) {
2983 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002984 if (Hi == NoClass)
2985 return ABIArgInfo::getIgnore();
2986 // If the low part is just padding, it takes no register, leave ResType
2987 // null.
2988 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2989 "Unknown missing lo part");
2990 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002991
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002992 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2993 // on the stack.
2994 case Memory:
2995
2996 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2997 // COMPLEX_X87, it is passed in memory.
2998 case X87:
2999 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003000 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003001 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003002 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003003
3004 case SSEUp:
3005 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003006 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003007
3008 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3009 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3010 // and %r9 is used.
3011 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003012 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003013
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003014 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003015 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003016
3017 // If we have a sign or zero extended integer, make sure to return Extend
3018 // so that the parameter gets the right LLVM IR attributes.
3019 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3020 // Treat an enum type as its underlying type.
3021 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3022 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003023
Chris Lattner1f3a0632010-07-29 21:42:50 +00003024 if (Ty->isIntegralOrEnumerationType() &&
3025 Ty->isPromotableIntegerType())
3026 return ABIArgInfo::getExtend();
3027 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003028
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003029 break;
3030
3031 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3032 // available SSE register is used, the registers are taken in the
3033 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003034 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003035 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003036 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003037 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003038 break;
3039 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003040 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003041
Craig Topper8a13c412014-05-21 05:09:00 +00003042 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003043 switch (Hi) {
3044 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003045 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003046 // which is passed in memory.
3047 case Memory:
3048 case X87:
3049 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003050 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003051
3052 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003053
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003054 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003055 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003056 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003057 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003058
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003059 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3060 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003061 break;
3062
3063 // X87Up generally doesn't occur here (long double is passed in
3064 // memory), except in situations involving unions.
3065 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003066 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003067 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003068
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003069 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3070 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003071
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003072 ++neededSSE;
3073 break;
3074
3075 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3076 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003077 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003078 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003079 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003080 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003081 break;
3082 }
3083
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003084 // If a high part was specified, merge it together with the low part. It is
3085 // known to pass in the high eightbyte of the result. We do this by forming a
3086 // first class struct aggregate with the high and low part: {low, high}
3087 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003088 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003089
Chris Lattner1f3a0632010-07-29 21:42:50 +00003090 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003091}
3092
Chris Lattner22326a12010-07-29 02:31:05 +00003093void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003094
Reid Kleckner40ca9132014-05-13 22:05:45 +00003095 if (!getCXXABI().classifyReturnType(FI))
3096 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003097
3098 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003099 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003100
3101 // If the return value is indirect, then the hidden argument is consuming one
3102 // integer register.
3103 if (FI.getReturnInfo().isIndirect())
3104 --freeIntRegs;
3105
Peter Collingbournef7706832014-12-12 23:41:25 +00003106 // The chain argument effectively gives us another free register.
3107 if (FI.isChainCall())
3108 ++freeIntRegs;
3109
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003110 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003111 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3112 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003113 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003114 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003115 it != ie; ++it, ++ArgNo) {
3116 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003117
Bill Wendling9987c0e2010-10-18 23:51:38 +00003118 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003119 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003120 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003121
3122 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3123 // eightbyte of an argument, the whole argument is passed on the
3124 // stack. If registers have already been assigned for some
3125 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003126 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003127 freeIntRegs -= neededInt;
3128 freeSSERegs -= neededSSE;
3129 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003130 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003131 }
3132 }
3133}
3134
John McCall7f416cc2015-09-08 08:05:57 +00003135static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3136 Address VAListAddr, QualType Ty) {
3137 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3138 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003139 llvm::Value *overflow_arg_area =
3140 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3141
3142 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3143 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003144 // It isn't stated explicitly in the standard, but in practice we use
3145 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003146 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3147 if (Align > CharUnits::fromQuantity(8)) {
3148 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3149 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003150 }
3151
3152 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003153 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003154 llvm::Value *Res =
3155 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003156 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003157
3158 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3159 // l->overflow_arg_area + sizeof(type).
3160 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3161 // an 8 byte boundary.
3162
3163 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003164 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003165 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003166 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3167 "overflow_arg_area.next");
3168 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3169
3170 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003171 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003172}
3173
John McCall7f416cc2015-09-08 08:05:57 +00003174Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3175 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003176 // Assume that va_list type is correct; should be pointer to LLVM type:
3177 // struct {
3178 // i32 gp_offset;
3179 // i32 fp_offset;
3180 // i8* overflow_arg_area;
3181 // i8* reg_save_area;
3182 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003183 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003184
John McCall7f416cc2015-09-08 08:05:57 +00003185 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003186 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003187 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003188
3189 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3190 // in the registers. If not go to step 7.
3191 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003192 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003193
3194 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3195 // general purpose registers needed to pass type and num_fp to hold
3196 // the number of floating point registers needed.
3197
3198 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3199 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3200 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3201 //
3202 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3203 // register save space).
3204
Craig Topper8a13c412014-05-21 05:09:00 +00003205 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003206 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3207 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003208 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003209 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003210 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3211 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003212 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003213 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3214 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003215 }
3216
3217 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003218 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003219 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3220 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003221 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3222 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003223 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3224 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003225 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3226 }
3227
3228 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3229 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3230 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3231 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3232
3233 // Emit code to load the value if it was passed in registers.
3234
3235 CGF.EmitBlock(InRegBlock);
3236
3237 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3238 // an offset of l->gp_offset and/or l->fp_offset. This may require
3239 // copying to a temporary location in case the parameter is passed
3240 // in different register classes or requires an alignment greater
3241 // than 8 for general purpose registers and 16 for XMM registers.
3242 //
3243 // FIXME: This really results in shameful code when we end up needing to
3244 // collect arguments from different places; often what should result in a
3245 // simple assembling of a structure from scattered addresses has many more
3246 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003247 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003248 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3249 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3250 "reg_save_area");
3251
3252 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003253 if (neededInt && neededSSE) {
3254 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003255 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003256 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003257 Address Tmp = CGF.CreateMemTemp(Ty);
3258 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003259 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003260 llvm::Type *TyLo = ST->getElementType(0);
3261 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003262 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003263 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003264 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3265 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003266 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3267 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003268 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3269 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003270
John McCall7f416cc2015-09-08 08:05:57 +00003271 // Copy the first element.
3272 llvm::Value *V =
3273 CGF.Builder.CreateDefaultAlignedLoad(
3274 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3275 CGF.Builder.CreateStore(V,
3276 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3277
3278 // Copy the second element.
3279 V = CGF.Builder.CreateDefaultAlignedLoad(
3280 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3281 CharUnits Offset = CharUnits::fromQuantity(
3282 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3283 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3284
3285 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003286 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003287 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3288 CharUnits::fromQuantity(8));
3289 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003290
3291 // Copy to a temporary if necessary to ensure the appropriate alignment.
3292 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003293 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003294 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003295 CharUnits TyAlign = SizeAlign.second;
3296
3297 // Copy into a temporary if the type is more aligned than the
3298 // register save area.
3299 if (TyAlign.getQuantity() > 8) {
3300 Address Tmp = CGF.CreateMemTemp(Ty);
3301 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003302 RegAddr = Tmp;
3303 }
John McCall7f416cc2015-09-08 08:05:57 +00003304
Chris Lattner0cf24192010-06-28 20:05:43 +00003305 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003306 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3307 CharUnits::fromQuantity(16));
3308 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003309 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003310 assert(neededSSE == 2 && "Invalid number of needed registers!");
3311 // SSE registers are spaced 16 bytes apart in the register save
3312 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003313 // The ABI isn't explicit about this, but it seems reasonable
3314 // to assume that the slots are 16-byte aligned, since the stack is
3315 // naturally 16-byte aligned and the prologue is expected to store
3316 // all the SSE registers to the RSA.
3317 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3318 CharUnits::fromQuantity(16));
3319 Address RegAddrHi =
3320 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3321 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003322 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003323 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003324 llvm::Value *V;
3325 Address Tmp = CGF.CreateMemTemp(Ty);
3326 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3327 V = CGF.Builder.CreateLoad(
3328 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3329 CGF.Builder.CreateStore(V,
3330 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3331 V = CGF.Builder.CreateLoad(
3332 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3333 CGF.Builder.CreateStore(V,
3334 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3335
3336 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003337 }
3338
3339 // AMD64-ABI 3.5.7p5: Step 5. Set:
3340 // l->gp_offset = l->gp_offset + num_gp * 8
3341 // l->fp_offset = l->fp_offset + num_fp * 16.
3342 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003343 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003344 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3345 gp_offset_p);
3346 }
3347 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003348 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003349 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3350 fp_offset_p);
3351 }
3352 CGF.EmitBranch(ContBlock);
3353
3354 // Emit code to load the value if it was passed in memory.
3355
3356 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003357 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003358
3359 // Return the appropriate result.
3360
3361 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003362 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3363 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003364 return ResAddr;
3365}
3366
Charles Davisc7d5c942015-09-17 20:55:33 +00003367Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3368 QualType Ty) const {
3369 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3370 CGF.getContext().getTypeInfoInChars(Ty),
3371 CharUnits::fromQuantity(8),
3372 /*allowHigherAlign*/ false);
3373}
3374
Reid Kleckner80944df2014-10-31 22:00:51 +00003375ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3376 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003377
3378 if (Ty->isVoidType())
3379 return ABIArgInfo::getIgnore();
3380
3381 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3382 Ty = EnumTy->getDecl()->getIntegerType();
3383
Reid Kleckner80944df2014-10-31 22:00:51 +00003384 TypeInfo Info = getContext().getTypeInfo(Ty);
3385 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003386 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003387
Reid Kleckner9005f412014-05-02 00:51:20 +00003388 const RecordType *RT = Ty->getAs<RecordType>();
3389 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003390 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003391 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003392 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003393 }
3394
3395 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003396 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003397
Reid Kleckner9005f412014-05-02 00:51:20 +00003398 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003399
Reid Kleckner80944df2014-10-31 22:00:51 +00003400 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3401 // other targets.
3402 const Type *Base = nullptr;
3403 uint64_t NumElts = 0;
3404 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3405 if (FreeSSERegs >= NumElts) {
3406 FreeSSERegs -= NumElts;
3407 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3408 return ABIArgInfo::getDirect();
3409 return ABIArgInfo::getExpand();
3410 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003411 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003412 }
3413
3414
Reid Klecknerec87fec2014-05-02 01:17:12 +00003415 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003416 // If the member pointer is represented by an LLVM int or ptr, pass it
3417 // directly.
3418 llvm::Type *LLTy = CGT.ConvertType(Ty);
3419 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3420 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003421 }
3422
Michael Kuperstein4f818702015-02-24 09:35:58 +00003423 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003424 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3425 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003426 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003427 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003428
Reid Kleckner9005f412014-05-02 00:51:20 +00003429 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003430 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003431 }
3432
Julien Lerouge10dcff82014-08-27 00:36:55 +00003433 // Bool type is always extended to the ABI, other builtin types are not
3434 // extended.
3435 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3436 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003437 return ABIArgInfo::getExtend();
3438
Reid Kleckner11a17192015-10-28 22:29:52 +00003439 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3440 // passes them indirectly through memory.
3441 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3442 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3443 if (LDF == &llvm::APFloat::x87DoubleExtended)
3444 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3445 }
3446
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003447 return ABIArgInfo::getDirect();
3448}
3449
3450void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003451 bool IsVectorCall =
3452 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003453
Reid Kleckner80944df2014-10-31 22:00:51 +00003454 // We can use up to 4 SSE return registers with vectorcall.
3455 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3456 if (!getCXXABI().classifyReturnType(FI))
3457 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3458
3459 // We can use up to 6 SSE register parameters with vectorcall.
3460 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003461 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003462 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003463}
3464
John McCall7f416cc2015-09-08 08:05:57 +00003465Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3466 QualType Ty) const {
3467 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3468 CGF.getContext().getTypeInfoInChars(Ty),
3469 CharUnits::fromQuantity(8),
3470 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003471}
Chris Lattner0cf24192010-06-28 20:05:43 +00003472
John McCallea8d8bb2010-03-11 00:10:12 +00003473// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003474namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003475/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3476class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003477bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003478public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003479 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3480 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003481
John McCall7f416cc2015-09-08 08:05:57 +00003482 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3483 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003484};
3485
3486class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3487public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003488 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3489 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003490
Craig Topper4f12f102014-03-12 06:41:41 +00003491 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003492 // This is recovered from gcc output.
3493 return 1; // r1 is the dedicated stack pointer
3494 }
3495
3496 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003497 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003498};
3499
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003500}
John McCallea8d8bb2010-03-11 00:10:12 +00003501
John McCall7f416cc2015-09-08 08:05:57 +00003502Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3503 QualType Ty) const {
Roman Divacky8a12d842014-11-03 18:32:54 +00003504 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3505 // TODO: Implement this. For now ignore.
3506 (void)CTy;
John McCall7f416cc2015-09-08 08:05:57 +00003507 return Address::invalid();
Roman Divacky8a12d842014-11-03 18:32:54 +00003508 }
3509
John McCall7f416cc2015-09-08 08:05:57 +00003510 // struct __va_list_tag {
3511 // unsigned char gpr;
3512 // unsigned char fpr;
3513 // unsigned short reserved;
3514 // void *overflow_arg_area;
3515 // void *reg_save_area;
3516 // };
3517
Roman Divacky8a12d842014-11-03 18:32:54 +00003518 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003519 bool isInt =
3520 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003521 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003522
3523 // All aggregates are passed indirectly? That doesn't seem consistent
3524 // with the argument-lowering code.
3525 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003526
3527 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003528
3529 // The calling convention either uses 1-2 GPRs or 1 FPR.
3530 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003531 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003532 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3533 } else {
3534 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003535 }
John McCall7f416cc2015-09-08 08:05:57 +00003536
3537 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3538
3539 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003540 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003541 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3542 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3543 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003544
Eric Christopher7565e0d2015-05-29 23:09:49 +00003545 llvm::Value *CC =
John McCall7f416cc2015-09-08 08:05:57 +00003546 Builder.CreateICmpULT(NumRegs, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003547
3548 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3549 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3550 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3551
3552 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3553
John McCall7f416cc2015-09-08 08:05:57 +00003554 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3555 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003556
John McCall7f416cc2015-09-08 08:05:57 +00003557 // Case 1: consume registers.
3558 Address RegAddr = Address::invalid();
3559 {
3560 CGF.EmitBlock(UsingRegs);
3561
3562 Address RegSaveAreaPtr =
3563 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3564 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3565 CharUnits::fromQuantity(8));
3566 assert(RegAddr.getElementType() == CGF.Int8Ty);
3567
3568 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003569 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003570 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3571 CharUnits::fromQuantity(32));
3572 }
3573
3574 // Get the address of the saved value by scaling the number of
3575 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003576 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003577 llvm::Value *RegOffset =
3578 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3579 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3580 RegAddr.getPointer(), RegOffset),
3581 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3582 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3583
3584 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003585 NumRegs =
3586 Builder.CreateAdd(NumRegs,
3587 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003588 Builder.CreateStore(NumRegs, NumRegsAddr);
3589
3590 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003591 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003592
John McCall7f416cc2015-09-08 08:05:57 +00003593 // Case 2: consume space in the overflow area.
3594 Address MemAddr = Address::invalid();
3595 {
3596 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003597
John McCall7f416cc2015-09-08 08:05:57 +00003598 // Everything in the overflow area is rounded up to a size of at least 4.
3599 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3600
3601 CharUnits Size;
3602 if (!isIndirect) {
3603 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003604 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003605 } else {
3606 Size = CGF.getPointerSize();
3607 }
3608
3609 Address OverflowAreaAddr =
3610 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003611 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003612 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003613 // Round up address of argument to alignment
3614 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3615 if (Align > OverflowAreaAlign) {
3616 llvm::Value *Ptr = OverflowArea.getPointer();
3617 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3618 Align);
3619 }
3620
John McCall7f416cc2015-09-08 08:05:57 +00003621 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3622
3623 // Increase the overflow area.
3624 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3625 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3626 CGF.EmitBranch(Cont);
3627 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003628
3629 CGF.EmitBlock(Cont);
3630
John McCall7f416cc2015-09-08 08:05:57 +00003631 // Merge the cases with a phi.
3632 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3633 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003634
John McCall7f416cc2015-09-08 08:05:57 +00003635 // Load the pointer if the argument was passed indirectly.
3636 if (isIndirect) {
3637 Result = Address(Builder.CreateLoad(Result, "aggr"),
3638 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003639 }
3640
3641 return Result;
3642}
3643
John McCallea8d8bb2010-03-11 00:10:12 +00003644bool
3645PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3646 llvm::Value *Address) const {
3647 // This is calculated from the LLVM and GCC tables and verified
3648 // against gcc output. AFAIK all ABIs use the same encoding.
3649
3650 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003651
Chris Lattnerece04092012-02-07 00:39:47 +00003652 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003653 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3654 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3655 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3656
3657 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003658 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003659
3660 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003661 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003662
3663 // 64-76 are various 4-byte special-purpose registers:
3664 // 64: mq
3665 // 65: lr
3666 // 66: ctr
3667 // 67: ap
3668 // 68-75 cr0-7
3669 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003670 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003671
3672 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003673 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003674
3675 // 109: vrsave
3676 // 110: vscr
3677 // 111: spe_acc
3678 // 112: spefscr
3679 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003680 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003681
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003682 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003683}
3684
Roman Divackyd966e722012-05-09 18:22:46 +00003685// PowerPC-64
3686
3687namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003688/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3689class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003690public:
3691 enum ABIKind {
3692 ELFv1 = 0,
3693 ELFv2
3694 };
3695
3696private:
3697 static const unsigned GPRBits = 64;
3698 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003699 bool HasQPX;
3700
3701 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3702 // will be passed in a QPX register.
3703 bool IsQPXVectorTy(const Type *Ty) const {
3704 if (!HasQPX)
3705 return false;
3706
3707 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3708 unsigned NumElements = VT->getNumElements();
3709 if (NumElements == 1)
3710 return false;
3711
3712 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3713 if (getContext().getTypeSize(Ty) <= 256)
3714 return true;
3715 } else if (VT->getElementType()->
3716 isSpecificBuiltinType(BuiltinType::Float)) {
3717 if (getContext().getTypeSize(Ty) <= 128)
3718 return true;
3719 }
3720 }
3721
3722 return false;
3723 }
3724
3725 bool IsQPXVectorTy(QualType Ty) const {
3726 return IsQPXVectorTy(Ty.getTypePtr());
3727 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003728
3729public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003730 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3731 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003732
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003733 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003734 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003735
3736 ABIArgInfo classifyReturnType(QualType RetTy) const;
3737 ABIArgInfo classifyArgumentType(QualType Ty) const;
3738
Reid Klecknere9f6a712014-10-31 17:10:41 +00003739 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3740 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3741 uint64_t Members) const override;
3742
Bill Schmidt84d37792012-10-12 19:26:17 +00003743 // TODO: We can add more logic to computeInfo to improve performance.
3744 // Example: For aggregate arguments that fit in a register, we could
3745 // use getDirectInReg (as is done below for structs containing a single
3746 // floating-point value) to avoid pushing them to memory on function
3747 // entry. This would require changing the logic in PPCISelLowering
3748 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003749 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003750 if (!getCXXABI().classifyReturnType(FI))
3751 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003752 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003753 // We rely on the default argument classification for the most part.
3754 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003755 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003756 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003757 if (T) {
3758 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003759 if (IsQPXVectorTy(T) ||
3760 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003761 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003762 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003763 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003764 continue;
3765 }
3766 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003767 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003768 }
3769 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003770
John McCall7f416cc2015-09-08 08:05:57 +00003771 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3772 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003773};
3774
3775class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003776
Bill Schmidt25cb3492012-10-03 19:18:57 +00003777public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003778 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003779 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003780 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003781
Craig Topper4f12f102014-03-12 06:41:41 +00003782 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003783 // This is recovered from gcc output.
3784 return 1; // r1 is the dedicated stack pointer
3785 }
3786
3787 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003788 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003789};
3790
Roman Divackyd966e722012-05-09 18:22:46 +00003791class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3792public:
3793 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3794
Craig Topper4f12f102014-03-12 06:41:41 +00003795 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003796 // This is recovered from gcc output.
3797 return 1; // r1 is the dedicated stack pointer
3798 }
3799
3800 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003801 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003802};
3803
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003804}
Roman Divackyd966e722012-05-09 18:22:46 +00003805
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003806// Return true if the ABI requires Ty to be passed sign- or zero-
3807// extended to 64 bits.
3808bool
3809PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3810 // Treat an enum type as its underlying type.
3811 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3812 Ty = EnumTy->getDecl()->getIntegerType();
3813
3814 // Promotable integer types are required to be promoted by the ABI.
3815 if (Ty->isPromotableIntegerType())
3816 return true;
3817
3818 // In addition to the usual promotable integer types, we also need to
3819 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3820 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3821 switch (BT->getKind()) {
3822 case BuiltinType::Int:
3823 case BuiltinType::UInt:
3824 return true;
3825 default:
3826 break;
3827 }
3828
3829 return false;
3830}
3831
John McCall7f416cc2015-09-08 08:05:57 +00003832/// isAlignedParamType - Determine whether a type requires 16-byte or
3833/// higher alignment in the parameter area. Always returns at least 8.
3834CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003835 // Complex types are passed just like their elements.
3836 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3837 Ty = CTy->getElementType();
3838
3839 // Only vector types of size 16 bytes need alignment (larger types are
3840 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003841 if (IsQPXVectorTy(Ty)) {
3842 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003843 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003844
John McCall7f416cc2015-09-08 08:05:57 +00003845 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003846 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00003847 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003848 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003849
3850 // For single-element float/vector structs, we consider the whole type
3851 // to have the same alignment requirements as its single element.
3852 const Type *AlignAsType = nullptr;
3853 const Type *EltType = isSingleElementStruct(Ty, getContext());
3854 if (EltType) {
3855 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003856 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003857 getContext().getTypeSize(EltType) == 128) ||
3858 (BT && BT->isFloatingPoint()))
3859 AlignAsType = EltType;
3860 }
3861
Ulrich Weigandb7122372014-07-21 00:48:09 +00003862 // Likewise for ELFv2 homogeneous aggregates.
3863 const Type *Base = nullptr;
3864 uint64_t Members = 0;
3865 if (!AlignAsType && Kind == ELFv2 &&
3866 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3867 AlignAsType = Base;
3868
Ulrich Weigand581badc2014-07-10 17:20:07 +00003869 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003870 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3871 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003872 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003873
John McCall7f416cc2015-09-08 08:05:57 +00003874 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003875 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00003876 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003877 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003878
3879 // Otherwise, we only need alignment for any aggregate type that
3880 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003881 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3882 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00003883 return CharUnits::fromQuantity(32);
3884 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003885 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003886
John McCall7f416cc2015-09-08 08:05:57 +00003887 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00003888}
3889
Ulrich Weigandb7122372014-07-21 00:48:09 +00003890/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3891/// aggregate. Base is set to the base element type, and Members is set
3892/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003893bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3894 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003895 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3896 uint64_t NElements = AT->getSize().getZExtValue();
3897 if (NElements == 0)
3898 return false;
3899 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3900 return false;
3901 Members *= NElements;
3902 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3903 const RecordDecl *RD = RT->getDecl();
3904 if (RD->hasFlexibleArrayMember())
3905 return false;
3906
3907 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003908
3909 // If this is a C++ record, check the bases first.
3910 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3911 for (const auto &I : CXXRD->bases()) {
3912 // Ignore empty records.
3913 if (isEmptyRecord(getContext(), I.getType(), true))
3914 continue;
3915
3916 uint64_t FldMembers;
3917 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3918 return false;
3919
3920 Members += FldMembers;
3921 }
3922 }
3923
Ulrich Weigandb7122372014-07-21 00:48:09 +00003924 for (const auto *FD : RD->fields()) {
3925 // Ignore (non-zero arrays of) empty records.
3926 QualType FT = FD->getType();
3927 while (const ConstantArrayType *AT =
3928 getContext().getAsConstantArrayType(FT)) {
3929 if (AT->getSize().getZExtValue() == 0)
3930 return false;
3931 FT = AT->getElementType();
3932 }
3933 if (isEmptyRecord(getContext(), FT, true))
3934 continue;
3935
3936 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3937 if (getContext().getLangOpts().CPlusPlus &&
3938 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3939 continue;
3940
3941 uint64_t FldMembers;
3942 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3943 return false;
3944
3945 Members = (RD->isUnion() ?
3946 std::max(Members, FldMembers) : Members + FldMembers);
3947 }
3948
3949 if (!Base)
3950 return false;
3951
3952 // Ensure there is no padding.
3953 if (getContext().getTypeSize(Base) * Members !=
3954 getContext().getTypeSize(Ty))
3955 return false;
3956 } else {
3957 Members = 1;
3958 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3959 Members = 2;
3960 Ty = CT->getElementType();
3961 }
3962
Reid Klecknere9f6a712014-10-31 17:10:41 +00003963 // Most ABIs only support float, double, and some vector type widths.
3964 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003965 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003966
3967 // The base type must be the same for all members. Types that
3968 // agree in both total size and mode (float vs. vector) are
3969 // treated as being equivalent here.
3970 const Type *TyPtr = Ty.getTypePtr();
3971 if (!Base)
3972 Base = TyPtr;
3973
3974 if (Base->isVectorType() != TyPtr->isVectorType() ||
3975 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3976 return false;
3977 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003978 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3979}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003980
Reid Klecknere9f6a712014-10-31 17:10:41 +00003981bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3982 // Homogeneous aggregates for ELFv2 must have base types of float,
3983 // double, long double, or 128-bit vectors.
3984 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3985 if (BT->getKind() == BuiltinType::Float ||
3986 BT->getKind() == BuiltinType::Double ||
3987 BT->getKind() == BuiltinType::LongDouble)
3988 return true;
3989 }
3990 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003991 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003992 return true;
3993 }
3994 return false;
3995}
3996
3997bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3998 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003999 // Vector types require one register, floating point types require one
4000 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004001 uint32_t NumRegs =
4002 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004003
4004 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004005 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004006}
4007
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004008ABIArgInfo
4009PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004010 Ty = useFirstFieldIfTransparentUnion(Ty);
4011
Bill Schmidt90b22c92012-11-27 02:46:43 +00004012 if (Ty->isAnyComplexType())
4013 return ABIArgInfo::getDirect();
4014
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004015 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4016 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004017 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004018 uint64_t Size = getContext().getTypeSize(Ty);
4019 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004020 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004021 else if (Size < 128) {
4022 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4023 return ABIArgInfo::getDirect(CoerceTy);
4024 }
4025 }
4026
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004027 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004028 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004029 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004030
John McCall7f416cc2015-09-08 08:05:57 +00004031 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4032 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004033
4034 // ELFv2 homogeneous aggregates are passed as array types.
4035 const Type *Base = nullptr;
4036 uint64_t Members = 0;
4037 if (Kind == ELFv2 &&
4038 isHomogeneousAggregate(Ty, Base, Members)) {
4039 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4040 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4041 return ABIArgInfo::getDirect(CoerceTy);
4042 }
4043
Ulrich Weigand601957f2014-07-21 00:56:36 +00004044 // If an aggregate may end up fully in registers, we do not
4045 // use the ByVal method, but pass the aggregate as array.
4046 // This is usually beneficial since we avoid forcing the
4047 // back-end to store the argument to memory.
4048 uint64_t Bits = getContext().getTypeSize(Ty);
4049 if (Bits > 0 && Bits <= 8 * GPRBits) {
4050 llvm::Type *CoerceTy;
4051
4052 // Types up to 8 bytes are passed as integer type (which will be
4053 // properly aligned in the argument save area doubleword).
4054 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004055 CoerceTy =
4056 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004057 // Larger types are passed as arrays, with the base type selected
4058 // according to the required alignment in the save area.
4059 else {
4060 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004061 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004062 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4063 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4064 }
4065
4066 return ABIArgInfo::getDirect(CoerceTy);
4067 }
4068
Ulrich Weigandb7122372014-07-21 00:48:09 +00004069 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004070 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4071 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004072 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004073 }
4074
4075 return (isPromotableTypeForABI(Ty) ?
4076 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4077}
4078
4079ABIArgInfo
4080PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4081 if (RetTy->isVoidType())
4082 return ABIArgInfo::getIgnore();
4083
Bill Schmidta3d121c2012-12-17 04:20:17 +00004084 if (RetTy->isAnyComplexType())
4085 return ABIArgInfo::getDirect();
4086
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004087 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4088 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004089 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004090 uint64_t Size = getContext().getTypeSize(RetTy);
4091 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004092 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004093 else if (Size < 128) {
4094 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4095 return ABIArgInfo::getDirect(CoerceTy);
4096 }
4097 }
4098
Ulrich Weigandb7122372014-07-21 00:48:09 +00004099 if (isAggregateTypeForABI(RetTy)) {
4100 // ELFv2 homogeneous aggregates are returned as array types.
4101 const Type *Base = nullptr;
4102 uint64_t Members = 0;
4103 if (Kind == ELFv2 &&
4104 isHomogeneousAggregate(RetTy, Base, Members)) {
4105 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4106 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4107 return ABIArgInfo::getDirect(CoerceTy);
4108 }
4109
4110 // ELFv2 small aggregates are returned in up to two registers.
4111 uint64_t Bits = getContext().getTypeSize(RetTy);
4112 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4113 if (Bits == 0)
4114 return ABIArgInfo::getIgnore();
4115
4116 llvm::Type *CoerceTy;
4117 if (Bits > GPRBits) {
4118 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004119 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004120 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004121 CoerceTy =
4122 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004123 return ABIArgInfo::getDirect(CoerceTy);
4124 }
4125
4126 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004127 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004128 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004129
4130 return (isPromotableTypeForABI(RetTy) ?
4131 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4132}
4133
Bill Schmidt25cb3492012-10-03 19:18:57 +00004134// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004135Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4136 QualType Ty) const {
4137 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4138 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004139
John McCall7f416cc2015-09-08 08:05:57 +00004140 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004141
Bill Schmidt924c4782013-01-14 17:45:36 +00004142 // If we have a complex type and the base type is smaller than 8 bytes,
4143 // the ABI calls for the real and imaginary parts to be right-adjusted
4144 // in separate doublewords. However, Clang expects us to produce a
4145 // pointer to a structure with the two parts packed tightly. So generate
4146 // loads of the real and imaginary parts relative to the va_list pointer,
4147 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004148 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4149 CharUnits EltSize = TypeInfo.first / 2;
4150 if (EltSize < SlotSize) {
4151 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4152 SlotSize * 2, SlotSize,
4153 SlotSize, /*AllowHigher*/ true);
4154
4155 Address RealAddr = Addr;
4156 Address ImagAddr = RealAddr;
4157 if (CGF.CGM.getDataLayout().isBigEndian()) {
4158 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4159 SlotSize - EltSize);
4160 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4161 2 * SlotSize - EltSize);
4162 } else {
4163 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4164 }
4165
4166 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4167 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4168 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4169 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4170 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4171
4172 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4173 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4174 /*init*/ true);
4175 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004176 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004177 }
4178
John McCall7f416cc2015-09-08 08:05:57 +00004179 // Otherwise, just use the general rule.
4180 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4181 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004182}
4183
4184static bool
4185PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4186 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004187 // This is calculated from the LLVM and GCC tables and verified
4188 // against gcc output. AFAIK all ABIs use the same encoding.
4189
4190 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4191
4192 llvm::IntegerType *i8 = CGF.Int8Ty;
4193 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4194 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4195 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4196
4197 // 0-31: r0-31, the 8-byte general-purpose registers
4198 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4199
4200 // 32-63: fp0-31, the 8-byte floating-point registers
4201 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4202
4203 // 64-76 are various 4-byte special-purpose registers:
4204 // 64: mq
4205 // 65: lr
4206 // 66: ctr
4207 // 67: ap
4208 // 68-75 cr0-7
4209 // 76: xer
4210 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4211
4212 // 77-108: v0-31, the 16-byte vector registers
4213 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4214
4215 // 109: vrsave
4216 // 110: vscr
4217 // 111: spe_acc
4218 // 112: spefscr
4219 // 113: sfp
4220 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4221
4222 return false;
4223}
John McCallea8d8bb2010-03-11 00:10:12 +00004224
Bill Schmidt25cb3492012-10-03 19:18:57 +00004225bool
4226PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4227 CodeGen::CodeGenFunction &CGF,
4228 llvm::Value *Address) const {
4229
4230 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4231}
4232
4233bool
4234PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4235 llvm::Value *Address) const {
4236
4237 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4238}
4239
Chris Lattner0cf24192010-06-28 20:05:43 +00004240//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004241// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004242//===----------------------------------------------------------------------===//
4243
4244namespace {
4245
Tim Northover573cbee2014-05-24 12:52:07 +00004246class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004247public:
4248 enum ABIKind {
4249 AAPCS = 0,
4250 DarwinPCS
4251 };
4252
4253private:
4254 ABIKind Kind;
4255
4256public:
Tim Northover573cbee2014-05-24 12:52:07 +00004257 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004258
4259private:
4260 ABIKind getABIKind() const { return Kind; }
4261 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4262
4263 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004264 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004265 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4266 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4267 uint64_t Members) const override;
4268
Tim Northovera2ee4332014-03-29 15:09:45 +00004269 bool isIllegalVectorType(QualType Ty) const;
4270
David Blaikie1cbb9712014-11-14 19:09:44 +00004271 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004272 if (!getCXXABI().classifyReturnType(FI))
4273 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004274
Tim Northoverb047bfa2014-11-27 21:02:49 +00004275 for (auto &it : FI.arguments())
4276 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004277 }
4278
John McCall7f416cc2015-09-08 08:05:57 +00004279 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4280 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004281
John McCall7f416cc2015-09-08 08:05:57 +00004282 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4283 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004284
John McCall7f416cc2015-09-08 08:05:57 +00004285 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4286 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004287 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4288 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4289 }
4290};
4291
Tim Northover573cbee2014-05-24 12:52:07 +00004292class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004293public:
Tim Northover573cbee2014-05-24 12:52:07 +00004294 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4295 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004296
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004297 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004298 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4299 }
4300
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004301 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4302 return 31;
4303 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004304
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004305 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004306};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004307}
Tim Northovera2ee4332014-03-29 15:09:45 +00004308
Tim Northoverb047bfa2014-11-27 21:02:49 +00004309ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004310 Ty = useFirstFieldIfTransparentUnion(Ty);
4311
Tim Northovera2ee4332014-03-29 15:09:45 +00004312 // Handle illegal vector types here.
4313 if (isIllegalVectorType(Ty)) {
4314 uint64_t Size = getContext().getTypeSize(Ty);
4315 if (Size <= 32) {
4316 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004317 return ABIArgInfo::getDirect(ResType);
4318 }
4319 if (Size == 64) {
4320 llvm::Type *ResType =
4321 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004322 return ABIArgInfo::getDirect(ResType);
4323 }
4324 if (Size == 128) {
4325 llvm::Type *ResType =
4326 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004327 return ABIArgInfo::getDirect(ResType);
4328 }
John McCall7f416cc2015-09-08 08:05:57 +00004329 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004330 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004331
4332 if (!isAggregateTypeForABI(Ty)) {
4333 // Treat an enum type as its underlying type.
4334 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4335 Ty = EnumTy->getDecl()->getIntegerType();
4336
Tim Northovera2ee4332014-03-29 15:09:45 +00004337 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4338 ? ABIArgInfo::getExtend()
4339 : ABIArgInfo::getDirect());
4340 }
4341
4342 // Structures with either a non-trivial destructor or a non-trivial
4343 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004344 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004345 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4346 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004347 }
4348
4349 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4350 // elsewhere for GNU compatibility.
4351 if (isEmptyRecord(getContext(), Ty, true)) {
4352 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4353 return ABIArgInfo::getIgnore();
4354
Tim Northovera2ee4332014-03-29 15:09:45 +00004355 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4356 }
4357
4358 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004359 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004360 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004361 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004362 return ABIArgInfo::getDirect(
4363 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004364 }
4365
4366 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4367 uint64_t Size = getContext().getTypeSize(Ty);
4368 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004369 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004370 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004371
Tim Northovera2ee4332014-03-29 15:09:45 +00004372 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4373 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004374 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004375 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4376 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4377 }
4378 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4379 }
4380
John McCall7f416cc2015-09-08 08:05:57 +00004381 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004382}
4383
Tim Northover573cbee2014-05-24 12:52:07 +00004384ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004385 if (RetTy->isVoidType())
4386 return ABIArgInfo::getIgnore();
4387
4388 // Large vector types should be returned via memory.
4389 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004390 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004391
4392 if (!isAggregateTypeForABI(RetTy)) {
4393 // Treat an enum type as its underlying type.
4394 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4395 RetTy = EnumTy->getDecl()->getIntegerType();
4396
Tim Northover4dab6982014-04-18 13:46:08 +00004397 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4398 ? ABIArgInfo::getExtend()
4399 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004400 }
4401
Tim Northovera2ee4332014-03-29 15:09:45 +00004402 if (isEmptyRecord(getContext(), RetTy, true))
4403 return ABIArgInfo::getIgnore();
4404
Craig Topper8a13c412014-05-21 05:09:00 +00004405 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004406 uint64_t Members = 0;
4407 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004408 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4409 return ABIArgInfo::getDirect();
4410
4411 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4412 uint64_t Size = getContext().getTypeSize(RetTy);
4413 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004414 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004415 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004416
4417 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4418 // For aggregates with 16-byte alignment, we use i128.
4419 if (Alignment < 128 && Size == 128) {
4420 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4421 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4422 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004423 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4424 }
4425
John McCall7f416cc2015-09-08 08:05:57 +00004426 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004427}
4428
Tim Northover573cbee2014-05-24 12:52:07 +00004429/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4430bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004431 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4432 // Check whether VT is legal.
4433 unsigned NumElements = VT->getNumElements();
4434 uint64_t Size = getContext().getTypeSize(VT);
4435 // NumElements should be power of 2 between 1 and 16.
4436 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4437 return true;
4438 return Size != 64 && (Size != 128 || NumElements == 1);
4439 }
4440 return false;
4441}
4442
Reid Klecknere9f6a712014-10-31 17:10:41 +00004443bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4444 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4445 // point type or a short-vector type. This is the same as the 32-bit ABI,
4446 // but with the difference that any floating-point type is allowed,
4447 // including __fp16.
4448 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4449 if (BT->isFloatingPoint())
4450 return true;
4451 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4452 unsigned VecSize = getContext().getTypeSize(VT);
4453 if (VecSize == 64 || VecSize == 128)
4454 return true;
4455 }
4456 return false;
4457}
4458
4459bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4460 uint64_t Members) const {
4461 return Members <= 4;
4462}
4463
John McCall7f416cc2015-09-08 08:05:57 +00004464Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004465 QualType Ty,
4466 CodeGenFunction &CGF) const {
4467 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004468 bool IsIndirect = AI.isIndirect();
4469
Tim Northoverb047bfa2014-11-27 21:02:49 +00004470 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4471 if (IsIndirect)
4472 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4473 else if (AI.getCoerceToType())
4474 BaseTy = AI.getCoerceToType();
4475
4476 unsigned NumRegs = 1;
4477 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4478 BaseTy = ArrTy->getElementType();
4479 NumRegs = ArrTy->getNumElements();
4480 }
4481 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4482
Tim Northovera2ee4332014-03-29 15:09:45 +00004483 // The AArch64 va_list type and handling is specified in the Procedure Call
4484 // Standard, section B.4:
4485 //
4486 // struct {
4487 // void *__stack;
4488 // void *__gr_top;
4489 // void *__vr_top;
4490 // int __gr_offs;
4491 // int __vr_offs;
4492 // };
4493
4494 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4495 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4496 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4497 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004498
John McCall7f416cc2015-09-08 08:05:57 +00004499 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4500 CharUnits TyAlign = TyInfo.second;
4501
4502 Address reg_offs_p = Address::invalid();
4503 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004504 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004505 CharUnits reg_top_offset;
4506 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004507 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004508 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004509 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004510 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4511 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004512 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4513 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004514 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004515 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004516 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004517 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004518 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004519 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4520 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004521 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4522 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004523 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004524 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004525 }
4526
4527 //=======================================
4528 // Find out where argument was passed
4529 //=======================================
4530
4531 // If reg_offs >= 0 we're already using the stack for this type of
4532 // argument. We don't want to keep updating reg_offs (in case it overflows,
4533 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4534 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004535 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004536 UsingStack = CGF.Builder.CreateICmpSGE(
4537 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4538
4539 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4540
4541 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004542 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004543 CGF.EmitBlock(MaybeRegBlock);
4544
4545 // Integer arguments may need to correct register alignment (for example a
4546 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4547 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004548 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4549 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004550
4551 reg_offs = CGF.Builder.CreateAdd(
4552 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4553 "align_regoffs");
4554 reg_offs = CGF.Builder.CreateAnd(
4555 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4556 "aligned_regoffs");
4557 }
4558
4559 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004560 // The fact that this is done unconditionally reflects the fact that
4561 // allocating an argument to the stack also uses up all the remaining
4562 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004563 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004564 NewOffset = CGF.Builder.CreateAdd(
4565 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4566 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4567
4568 // Now we're in a position to decide whether this argument really was in
4569 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004570 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004571 InRegs = CGF.Builder.CreateICmpSLE(
4572 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4573
4574 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4575
4576 //=======================================
4577 // Argument was in registers
4578 //=======================================
4579
4580 // Now we emit the code for if the argument was originally passed in
4581 // registers. First start the appropriate block:
4582 CGF.EmitBlock(InRegBlock);
4583
John McCall7f416cc2015-09-08 08:05:57 +00004584 llvm::Value *reg_top = nullptr;
4585 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4586 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004587 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004588 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4589 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4590 Address RegAddr = Address::invalid();
4591 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004592
4593 if (IsIndirect) {
4594 // If it's been passed indirectly (actually a struct), whatever we find from
4595 // stored registers or on the stack will actually be a struct **.
4596 MemTy = llvm::PointerType::getUnqual(MemTy);
4597 }
4598
Craig Topper8a13c412014-05-21 05:09:00 +00004599 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004600 uint64_t NumMembers = 0;
4601 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004602 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004603 // Homogeneous aggregates passed in registers will have their elements split
4604 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4605 // qN+1, ...). We reload and store into a temporary local variable
4606 // contiguously.
4607 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004608 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004609 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4610 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004611 Address Tmp = CGF.CreateTempAlloca(HFATy,
4612 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004613
John McCall7f416cc2015-09-08 08:05:57 +00004614 // On big-endian platforms, the value will be right-aligned in its slot.
4615 int Offset = 0;
4616 if (CGF.CGM.getDataLayout().isBigEndian() &&
4617 BaseTyInfo.first.getQuantity() < 16)
4618 Offset = 16 - BaseTyInfo.first.getQuantity();
4619
Tim Northovera2ee4332014-03-29 15:09:45 +00004620 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004621 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4622 Address LoadAddr =
4623 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4624 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4625
4626 Address StoreAddr =
4627 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004628
4629 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4630 CGF.Builder.CreateStore(Elem, StoreAddr);
4631 }
4632
John McCall7f416cc2015-09-08 08:05:57 +00004633 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004634 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004635 // Otherwise the object is contiguous in memory.
4636
4637 // It might be right-aligned in its slot.
4638 CharUnits SlotSize = BaseAddr.getAlignment();
4639 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004640 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004641 TyInfo.first < SlotSize) {
4642 CharUnits Offset = SlotSize - TyInfo.first;
4643 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004644 }
4645
John McCall7f416cc2015-09-08 08:05:57 +00004646 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004647 }
4648
4649 CGF.EmitBranch(ContBlock);
4650
4651 //=======================================
4652 // Argument was on the stack
4653 //=======================================
4654 CGF.EmitBlock(OnStackBlock);
4655
John McCall7f416cc2015-09-08 08:05:57 +00004656 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4657 CharUnits::Zero(), "stack_p");
4658 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004659
John McCall7f416cc2015-09-08 08:05:57 +00004660 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004661 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004662 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4663 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004664
John McCall7f416cc2015-09-08 08:05:57 +00004665 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004666
John McCall7f416cc2015-09-08 08:05:57 +00004667 OnStackPtr = CGF.Builder.CreateAdd(
4668 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004669 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004670 OnStackPtr = CGF.Builder.CreateAnd(
4671 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004672 "align_stack");
4673
John McCall7f416cc2015-09-08 08:05:57 +00004674 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004675 }
John McCall7f416cc2015-09-08 08:05:57 +00004676 Address OnStackAddr(OnStackPtr,
4677 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004678
John McCall7f416cc2015-09-08 08:05:57 +00004679 // All stack slots are multiples of 8 bytes.
4680 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4681 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004682 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004683 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004684 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004685 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004686
John McCall7f416cc2015-09-08 08:05:57 +00004687 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004688 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004689 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004690
4691 // Write the new value of __stack for the next call to va_arg
4692 CGF.Builder.CreateStore(NewStack, stack_p);
4693
4694 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004695 TyInfo.first < StackSlotSize) {
4696 CharUnits Offset = StackSlotSize - TyInfo.first;
4697 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004698 }
4699
John McCall7f416cc2015-09-08 08:05:57 +00004700 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004701
4702 CGF.EmitBranch(ContBlock);
4703
4704 //=======================================
4705 // Tidy up
4706 //=======================================
4707 CGF.EmitBlock(ContBlock);
4708
John McCall7f416cc2015-09-08 08:05:57 +00004709 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4710 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004711
4712 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004713 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4714 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004715
4716 return ResAddr;
4717}
4718
John McCall7f416cc2015-09-08 08:05:57 +00004719Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4720 CodeGenFunction &CGF) const {
4721 // The backend's lowering doesn't support va_arg for aggregates or
4722 // illegal vector types. Lower VAArg here for these cases and use
4723 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004724 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00004725 return Address::invalid();
Tim Northovera2ee4332014-03-29 15:09:45 +00004726
John McCall7f416cc2015-09-08 08:05:57 +00004727 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004728
John McCall7f416cc2015-09-08 08:05:57 +00004729 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004730 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004731 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4732 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4733 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004734 }
4735
John McCall7f416cc2015-09-08 08:05:57 +00004736 // The size of the actual thing passed, which might end up just
4737 // being a pointer for indirect types.
4738 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4739
4740 // Arguments bigger than 16 bytes which aren't homogeneous
4741 // aggregates should be passed indirectly.
4742 bool IsIndirect = false;
4743 if (TyInfo.first.getQuantity() > 16) {
4744 const Type *Base = nullptr;
4745 uint64_t Members = 0;
4746 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004747 }
4748
John McCall7f416cc2015-09-08 08:05:57 +00004749 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4750 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004751}
4752
4753//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004754// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004755//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004756
4757namespace {
4758
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004759class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004760public:
4761 enum ABIKind {
4762 APCS = 0,
4763 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004764 AAPCS_VFP = 2,
4765 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004766 };
4767
4768private:
4769 ABIKind Kind;
4770
4771public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004772 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004773 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004774 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004775
John McCall3480ef22011-08-30 01:42:09 +00004776 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004777 switch (getTarget().getTriple().getEnvironment()) {
4778 case llvm::Triple::Android:
4779 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004780 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004781 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004782 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004783 return true;
4784 default:
4785 return false;
4786 }
John McCall3480ef22011-08-30 01:42:09 +00004787 }
4788
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004789 bool isEABIHF() const {
4790 switch (getTarget().getTriple().getEnvironment()) {
4791 case llvm::Triple::EABIHF:
4792 case llvm::Triple::GNUEABIHF:
4793 return true;
4794 default:
4795 return false;
4796 }
4797 }
4798
Stephen Hines8267e7d2015-12-04 01:39:30 +00004799 bool isAndroid() const {
4800 return (getTarget().getTriple().getEnvironment() ==
4801 llvm::Triple::Android);
4802 }
4803
Daniel Dunbar020daa92009-09-12 01:00:39 +00004804 ABIKind getABIKind() const { return Kind; }
4805
Tim Northovera484bc02013-10-01 14:34:25 +00004806private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004807 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004808 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004809 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004810
Reid Klecknere9f6a712014-10-31 17:10:41 +00004811 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4812 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4813 uint64_t Members) const override;
4814
Craig Topper4f12f102014-03-12 06:41:41 +00004815 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004816
John McCall7f416cc2015-09-08 08:05:57 +00004817 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4818 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004819
4820 llvm::CallingConv::ID getLLVMDefaultCC() const;
4821 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004822 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004823};
4824
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004825class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4826public:
Chris Lattner2b037972010-07-29 02:01:43 +00004827 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4828 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004829
John McCall3480ef22011-08-30 01:42:09 +00004830 const ARMABIInfo &getABIInfo() const {
4831 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4832 }
4833
Craig Topper4f12f102014-03-12 06:41:41 +00004834 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004835 return 13;
4836 }
Roman Divackyc1617352011-05-18 19:36:54 +00004837
Craig Topper4f12f102014-03-12 06:41:41 +00004838 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004839 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4840 }
4841
Roman Divackyc1617352011-05-18 19:36:54 +00004842 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004843 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004844 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004845
4846 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004847 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004848 return false;
4849 }
John McCall3480ef22011-08-30 01:42:09 +00004850
Craig Topper4f12f102014-03-12 06:41:41 +00004851 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004852 if (getABIInfo().isEABI()) return 88;
4853 return TargetCodeGenInfo::getSizeOfUnwindException();
4854 }
Tim Northovera484bc02013-10-01 14:34:25 +00004855
Eric Christopher162c91c2015-06-05 22:03:00 +00004856 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004857 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00004858 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00004859 if (!FD)
4860 return;
4861
4862 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4863 if (!Attr)
4864 return;
4865
4866 const char *Kind;
4867 switch (Attr->getInterrupt()) {
4868 case ARMInterruptAttr::Generic: Kind = ""; break;
4869 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4870 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4871 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4872 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4873 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4874 }
4875
4876 llvm::Function *Fn = cast<llvm::Function>(GV);
4877
4878 Fn->addFnAttr("interrupt", Kind);
4879
Tim Northover5627d392015-10-30 16:30:45 +00004880 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
4881 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00004882 return;
4883
4884 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4885 // however this is not necessarily true on taking any interrupt. Instruct
4886 // the backend to perform a realignment as part of the function prologue.
4887 llvm::AttrBuilder B;
4888 B.addStackAlignmentAttr(8);
4889 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4890 llvm::AttributeSet::get(CGM.getLLVMContext(),
4891 llvm::AttributeSet::FunctionIndex,
4892 B));
4893 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004894};
4895
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004896class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004897public:
4898 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4899 : ARMTargetCodeGenInfo(CGT, K) {}
4900
Eric Christopher162c91c2015-06-05 22:03:00 +00004901 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004902 CodeGen::CodeGenModule &CGM) const override;
4903};
4904
Eric Christopher162c91c2015-06-05 22:03:00 +00004905void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004906 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004907 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004908 addStackProbeSizeTargetAttribute(D, GV, CGM);
4909}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004910}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004911
Chris Lattner22326a12010-07-29 02:31:05 +00004912void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004913 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004914 FI.getReturnInfo() =
4915 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004916
Tim Northoverbc784d12015-02-24 17:22:40 +00004917 for (auto &I : FI.arguments())
4918 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004919
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004920 // Always honor user-specified calling convention.
4921 if (FI.getCallingConvention() != llvm::CallingConv::C)
4922 return;
4923
John McCall882987f2013-02-28 19:01:20 +00004924 llvm::CallingConv::ID cc = getRuntimeCC();
4925 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004926 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004927}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004928
John McCall882987f2013-02-28 19:01:20 +00004929/// Return the default calling convention that LLVM will use.
4930llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4931 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00004932 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00004933 return llvm::CallingConv::ARM_AAPCS_VFP;
4934 else if (isEABI())
4935 return llvm::CallingConv::ARM_AAPCS;
4936 else
4937 return llvm::CallingConv::ARM_APCS;
4938}
4939
4940/// Return the calling convention that our ABI would like us to use
4941/// as the C calling convention.
4942llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004943 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004944 case APCS: return llvm::CallingConv::ARM_APCS;
4945 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4946 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00004947 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004948 }
John McCall882987f2013-02-28 19:01:20 +00004949 llvm_unreachable("bad ABI kind");
4950}
4951
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004952void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004953 assert(getRuntimeCC() == llvm::CallingConv::C);
4954
4955 // Don't muddy up the IR with a ton of explicit annotations if
4956 // they'd just match what LLVM will infer from the triple.
4957 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4958 if (abiCC != getLLVMDefaultCC())
4959 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004960
Tim Northover5627d392015-10-30 16:30:45 +00004961 // AAPCS apparently requires runtime support functions to be soft-float, but
4962 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
4963 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
4964 switch (getABIKind()) {
4965 case APCS:
4966 case AAPCS16_VFP:
4967 if (abiCC != getLLVMDefaultCC())
4968 BuiltinCC = abiCC;
4969 break;
4970 case AAPCS:
4971 case AAPCS_VFP:
4972 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
4973 break;
4974 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004975}
4976
Tim Northoverbc784d12015-02-24 17:22:40 +00004977ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4978 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004979 // 6.1.2.1 The following argument types are VFP CPRCs:
4980 // A single-precision floating-point type (including promoted
4981 // half-precision types); A double-precision floating-point type;
4982 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4983 // with a Base Type of a single- or double-precision floating-point type,
4984 // 64-bit containerized vectors or 128-bit containerized vectors with one
4985 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004986 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004987
Reid Klecknerb1be6832014-11-15 01:41:41 +00004988 Ty = useFirstFieldIfTransparentUnion(Ty);
4989
Manman Renfef9e312012-10-16 19:18:39 +00004990 // Handle illegal vector types here.
4991 if (isIllegalVectorType(Ty)) {
4992 uint64_t Size = getContext().getTypeSize(Ty);
4993 if (Size <= 32) {
4994 llvm::Type *ResType =
4995 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004996 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004997 }
4998 if (Size == 64) {
4999 llvm::Type *ResType = llvm::VectorType::get(
5000 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005001 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005002 }
5003 if (Size == 128) {
5004 llvm::Type *ResType = llvm::VectorType::get(
5005 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005006 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005007 }
John McCall7f416cc2015-09-08 08:05:57 +00005008 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005009 }
5010
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005011 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5012 // unspecified. This is not done for OpenCL as it handles the half type
5013 // natively, and does not need to interwork with AAPCS code.
5014 if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
5015 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5016 llvm::Type::getFloatTy(getVMContext()) :
5017 llvm::Type::getInt32Ty(getVMContext());
5018 return ABIArgInfo::getDirect(ResType);
5019 }
5020
John McCalla1dee5302010-08-22 10:59:02 +00005021 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005022 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005023 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005024 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005025 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005026
Tim Northover5a1558e2014-11-07 22:30:50 +00005027 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5028 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005029 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005030
Oliver Stannard405bded2014-02-11 09:25:50 +00005031 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005032 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005033 }
Tim Northover1060eae2013-06-21 22:49:34 +00005034
Daniel Dunbar09d33622009-09-14 21:54:03 +00005035 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005036 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005037 return ABIArgInfo::getIgnore();
5038
Tim Northover5a1558e2014-11-07 22:30:50 +00005039 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005040 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5041 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005042 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005043 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005044 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005045 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005046 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005047 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005048 }
Tim Northover5627d392015-10-30 16:30:45 +00005049 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5050 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5051 // this convention even for a variadic function: the backend will use GPRs
5052 // if needed.
5053 const Type *Base = nullptr;
5054 uint64_t Members = 0;
5055 if (isHomogeneousAggregate(Ty, Base, Members)) {
5056 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5057 llvm::Type *Ty =
5058 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5059 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5060 }
5061 }
5062
5063 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5064 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5065 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5066 // bigger than 128-bits, they get placed in space allocated by the caller,
5067 // and a pointer is passed.
5068 return ABIArgInfo::getIndirect(
5069 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005070 }
5071
Manman Ren6c30e132012-08-13 21:23:55 +00005072 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005073 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5074 // most 8-byte. We realign the indirect argument if type alignment is bigger
5075 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005076 uint64_t ABIAlign = 4;
5077 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5078 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005079 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005080 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005081
Manman Ren8cd99812012-11-06 04:58:01 +00005082 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005083 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005084 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5085 /*ByVal=*/true,
5086 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005087 }
5088
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005089 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005090 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005091 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005092 // FIXME: Try to match the types of the arguments more accurately where
5093 // we can.
5094 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005095 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5096 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005097 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005098 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5099 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005100 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005101
Tim Northover5a1558e2014-11-07 22:30:50 +00005102 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005103}
5104
Chris Lattner458b2aa2010-07-29 02:16:43 +00005105static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005106 llvm::LLVMContext &VMContext) {
5107 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5108 // is called integer-like if its size is less than or equal to one word, and
5109 // the offset of each of its addressable sub-fields is zero.
5110
5111 uint64_t Size = Context.getTypeSize(Ty);
5112
5113 // Check that the type fits in a word.
5114 if (Size > 32)
5115 return false;
5116
5117 // FIXME: Handle vector types!
5118 if (Ty->isVectorType())
5119 return false;
5120
Daniel Dunbard53bac72009-09-14 02:20:34 +00005121 // Float types are never treated as "integer like".
5122 if (Ty->isRealFloatingType())
5123 return false;
5124
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005125 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005126 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005127 return true;
5128
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005129 // Small complex integer types are "integer like".
5130 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5131 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005132
5133 // Single element and zero sized arrays should be allowed, by the definition
5134 // above, but they are not.
5135
5136 // Otherwise, it must be a record type.
5137 const RecordType *RT = Ty->getAs<RecordType>();
5138 if (!RT) return false;
5139
5140 // Ignore records with flexible arrays.
5141 const RecordDecl *RD = RT->getDecl();
5142 if (RD->hasFlexibleArrayMember())
5143 return false;
5144
5145 // Check that all sub-fields are at offset 0, and are themselves "integer
5146 // like".
5147 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5148
5149 bool HadField = false;
5150 unsigned idx = 0;
5151 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5152 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005153 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005154
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005155 // Bit-fields are not addressable, we only need to verify they are "integer
5156 // like". We still have to disallow a subsequent non-bitfield, for example:
5157 // struct { int : 0; int x }
5158 // is non-integer like according to gcc.
5159 if (FD->isBitField()) {
5160 if (!RD->isUnion())
5161 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005162
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005163 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5164 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005165
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005166 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005167 }
5168
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005169 // Check if this field is at offset 0.
5170 if (Layout.getFieldOffset(idx) != 0)
5171 return false;
5172
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005173 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5174 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005175
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005176 // Only allow at most one field in a structure. This doesn't match the
5177 // wording above, but follows gcc in situations with a field following an
5178 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005179 if (!RD->isUnion()) {
5180 if (HadField)
5181 return false;
5182
5183 HadField = true;
5184 }
5185 }
5186
5187 return true;
5188}
5189
Oliver Stannard405bded2014-02-11 09:25:50 +00005190ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5191 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005192 bool IsEffectivelyAAPCS_VFP =
5193 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005194
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005195 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005196 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005197
Daniel Dunbar19964db2010-09-23 01:54:32 +00005198 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005199 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005200 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005201 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005202
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005203 // __fp16 gets returned as if it were an int or float, but with the top 16
5204 // bits unspecified. This is not done for OpenCL as it handles the half type
5205 // natively, and does not need to interwork with AAPCS code.
5206 if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
5207 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5208 llvm::Type::getFloatTy(getVMContext()) :
5209 llvm::Type::getInt32Ty(getVMContext());
5210 return ABIArgInfo::getDirect(ResType);
5211 }
5212
John McCalla1dee5302010-08-22 10:59:02 +00005213 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005214 // Treat an enum type as its underlying type.
5215 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5216 RetTy = EnumTy->getDecl()->getIntegerType();
5217
Tim Northover5a1558e2014-11-07 22:30:50 +00005218 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5219 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005220 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005221
5222 // Are we following APCS?
5223 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005224 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005225 return ABIArgInfo::getIgnore();
5226
Daniel Dunbareedf1512010-02-01 23:31:19 +00005227 // Complex types are all returned as packed integers.
5228 //
5229 // FIXME: Consider using 2 x vector types if the back end handles them
5230 // correctly.
5231 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005232 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5233 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005234
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005235 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005236 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005237 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005238 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005239 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005240 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005241 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005242 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5243 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005244 }
5245
5246 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005247 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005248 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005249
5250 // Otherwise this is an AAPCS variant.
5251
Chris Lattner458b2aa2010-07-29 02:16:43 +00005252 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005253 return ABIArgInfo::getIgnore();
5254
Bob Wilson1d9269a2011-11-02 04:51:36 +00005255 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005256 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005257 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005258 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005259 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005260 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005261 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005262 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005263 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005264 }
5265
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005266 // Aggregates <= 4 bytes are returned in r0; other aggregates
5267 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005268 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005269 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005270 if (getDataLayout().isBigEndian())
5271 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005272 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005273
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005274 // Return in the smallest viable integer type.
5275 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005276 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005277 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005278 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5279 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005280 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5281 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5282 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005283 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005284 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005285 }
5286
John McCall7f416cc2015-09-08 08:05:57 +00005287 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005288}
5289
Manman Renfef9e312012-10-16 19:18:39 +00005290/// isIllegalVector - check whether Ty is an illegal vector type.
5291bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005292 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5293 if (isAndroid()) {
5294 // Android shipped using Clang 3.1, which supported a slightly different
5295 // vector ABI. The primary differences were that 3-element vector types
5296 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5297 // accepts that legacy behavior for Android only.
5298 // Check whether VT is legal.
5299 unsigned NumElements = VT->getNumElements();
5300 // NumElements should be power of 2 or equal to 3.
5301 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5302 return true;
5303 } else {
5304 // Check whether VT is legal.
5305 unsigned NumElements = VT->getNumElements();
5306 uint64_t Size = getContext().getTypeSize(VT);
5307 // NumElements should be power of 2.
5308 if (!llvm::isPowerOf2_32(NumElements))
5309 return true;
5310 // Size should be greater than 32 bits.
5311 return Size <= 32;
5312 }
Manman Renfef9e312012-10-16 19:18:39 +00005313 }
5314 return false;
5315}
5316
Reid Klecknere9f6a712014-10-31 17:10:41 +00005317bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5318 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5319 // double, or 64-bit or 128-bit vectors.
5320 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5321 if (BT->getKind() == BuiltinType::Float ||
5322 BT->getKind() == BuiltinType::Double ||
5323 BT->getKind() == BuiltinType::LongDouble)
5324 return true;
5325 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5326 unsigned VecSize = getContext().getTypeSize(VT);
5327 if (VecSize == 64 || VecSize == 128)
5328 return true;
5329 }
5330 return false;
5331}
5332
5333bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5334 uint64_t Members) const {
5335 return Members <= 4;
5336}
5337
John McCall7f416cc2015-09-08 08:05:57 +00005338Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5339 QualType Ty) const {
5340 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005341
John McCall7f416cc2015-09-08 08:05:57 +00005342 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005343 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005344 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5345 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5346 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005347 }
5348
John McCall7f416cc2015-09-08 08:05:57 +00005349 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5350 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005351
John McCall7f416cc2015-09-08 08:05:57 +00005352 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5353 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005354 const Type *Base = nullptr;
5355 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005356 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5357 IsIndirect = true;
5358
Tim Northover5627d392015-10-30 16:30:45 +00005359 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5360 // allocated by the caller.
5361 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5362 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5363 !isHomogeneousAggregate(Ty, Base, Members)) {
5364 IsIndirect = true;
5365
John McCall7f416cc2015-09-08 08:05:57 +00005366 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005367 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5368 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005369 // Our callers should be prepared to handle an under-aligned address.
5370 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5371 getABIKind() == ARMABIInfo::AAPCS) {
5372 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5373 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005374 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5375 // ARMv7k allows type alignment up to 16 bytes.
5376 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5377 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005378 } else {
5379 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005380 }
John McCall7f416cc2015-09-08 08:05:57 +00005381 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005382
John McCall7f416cc2015-09-08 08:05:57 +00005383 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5384 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005385}
5386
Chris Lattner0cf24192010-06-28 20:05:43 +00005387//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005388// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005389//===----------------------------------------------------------------------===//
5390
5391namespace {
5392
Justin Holewinski83e96682012-05-24 17:43:12 +00005393class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005394public:
Justin Holewinski36837432013-03-30 14:38:24 +00005395 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005396
5397 ABIArgInfo classifyReturnType(QualType RetTy) const;
5398 ABIArgInfo classifyArgumentType(QualType Ty) const;
5399
Craig Topper4f12f102014-03-12 06:41:41 +00005400 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005401 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5402 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005403};
5404
Justin Holewinski83e96682012-05-24 17:43:12 +00005405class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005406public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005407 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5408 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005409
Eric Christopher162c91c2015-06-05 22:03:00 +00005410 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005411 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005412private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005413 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5414 // resulting MDNode to the nvvm.annotations MDNode.
5415 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005416};
5417
Justin Holewinski83e96682012-05-24 17:43:12 +00005418ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005419 if (RetTy->isVoidType())
5420 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005421
5422 // note: this is different from default ABI
5423 if (!RetTy->isScalarType())
5424 return ABIArgInfo::getDirect();
5425
5426 // Treat an enum type as its underlying type.
5427 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5428 RetTy = EnumTy->getDecl()->getIntegerType();
5429
5430 return (RetTy->isPromotableIntegerType() ?
5431 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005432}
5433
Justin Holewinski83e96682012-05-24 17:43:12 +00005434ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005435 // Treat an enum type as its underlying type.
5436 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5437 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005438
Eli Bendersky95338a02014-10-29 13:43:21 +00005439 // Return aggregates type as indirect by value
5440 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005441 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005442
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005443 return (Ty->isPromotableIntegerType() ?
5444 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005445}
5446
Justin Holewinski83e96682012-05-24 17:43:12 +00005447void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005448 if (!getCXXABI().classifyReturnType(FI))
5449 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005450 for (auto &I : FI.arguments())
5451 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005452
5453 // Always honor user-specified calling convention.
5454 if (FI.getCallingConvention() != llvm::CallingConv::C)
5455 return;
5456
John McCall882987f2013-02-28 19:01:20 +00005457 FI.setEffectiveCallingConvention(getRuntimeCC());
5458}
5459
John McCall7f416cc2015-09-08 08:05:57 +00005460Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5461 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005462 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005463}
5464
Justin Holewinski83e96682012-05-24 17:43:12 +00005465void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005466setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005467 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005468 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005469 if (!FD) return;
5470
5471 llvm::Function *F = cast<llvm::Function>(GV);
5472
5473 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005474 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005475 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005476 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005477 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005478 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005479 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5480 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005481 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005482 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005483 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005484 }
Justin Holewinski38031972011-10-05 17:58:44 +00005485
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005486 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005487 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005488 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005489 // __global__ functions cannot be called from the device, we do not
5490 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005491 if (FD->hasAttr<CUDAGlobalAttr>()) {
5492 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5493 addNVVMMetadata(F, "kernel", 1);
5494 }
Artem Belevich7093e402015-04-21 22:55:54 +00005495 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005496 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005497 llvm::APSInt MaxThreads(32);
5498 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5499 if (MaxThreads > 0)
5500 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5501
5502 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5503 // not specified in __launch_bounds__ or if the user specified a 0 value,
5504 // we don't have to add a PTX directive.
5505 if (Attr->getMinBlocks()) {
5506 llvm::APSInt MinBlocks(32);
5507 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5508 if (MinBlocks > 0)
5509 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5510 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005511 }
5512 }
Justin Holewinski38031972011-10-05 17:58:44 +00005513 }
5514}
5515
Eli Benderskye06a2c42014-04-15 16:57:05 +00005516void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5517 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005518 llvm::Module *M = F->getParent();
5519 llvm::LLVMContext &Ctx = M->getContext();
5520
5521 // Get "nvvm.annotations" metadata node
5522 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5523
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005524 llvm::Metadata *MDVals[] = {
5525 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5526 llvm::ConstantAsMetadata::get(
5527 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005528 // Append metadata to nvvm.annotations
5529 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5530}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005531}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005532
5533//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005534// SystemZ ABI Implementation
5535//===----------------------------------------------------------------------===//
5536
5537namespace {
5538
5539class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005540 bool HasVector;
5541
Ulrich Weigand47445072013-05-06 16:26:41 +00005542public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005543 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5544 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005545
5546 bool isPromotableIntegerType(QualType Ty) const;
5547 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005548 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005549 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005550 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005551
5552 ABIArgInfo classifyReturnType(QualType RetTy) const;
5553 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5554
Craig Topper4f12f102014-03-12 06:41:41 +00005555 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005556 if (!getCXXABI().classifyReturnType(FI))
5557 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005558 for (auto &I : FI.arguments())
5559 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005560 }
5561
John McCall7f416cc2015-09-08 08:05:57 +00005562 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5563 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005564};
5565
5566class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5567public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005568 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5569 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005570};
5571
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005572}
Ulrich Weigand47445072013-05-06 16:26:41 +00005573
5574bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5575 // Treat an enum type as its underlying type.
5576 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5577 Ty = EnumTy->getDecl()->getIntegerType();
5578
5579 // Promotable integer types are required to be promoted by the ABI.
5580 if (Ty->isPromotableIntegerType())
5581 return true;
5582
5583 // 32-bit values must also be promoted.
5584 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5585 switch (BT->getKind()) {
5586 case BuiltinType::Int:
5587 case BuiltinType::UInt:
5588 return true;
5589 default:
5590 return false;
5591 }
5592 return false;
5593}
5594
5595bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005596 return (Ty->isAnyComplexType() ||
5597 Ty->isVectorType() ||
5598 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005599}
5600
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005601bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5602 return (HasVector &&
5603 Ty->isVectorType() &&
5604 getContext().getTypeSize(Ty) <= 128);
5605}
5606
Ulrich Weigand47445072013-05-06 16:26:41 +00005607bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5608 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5609 switch (BT->getKind()) {
5610 case BuiltinType::Float:
5611 case BuiltinType::Double:
5612 return true;
5613 default:
5614 return false;
5615 }
5616
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005617 return false;
5618}
5619
5620QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005621 if (const RecordType *RT = Ty->getAsStructureType()) {
5622 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005623 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005624
5625 // If this is a C++ record, check the bases first.
5626 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005627 for (const auto &I : CXXRD->bases()) {
5628 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005629
5630 // Empty bases don't affect things either way.
5631 if (isEmptyRecord(getContext(), Base, true))
5632 continue;
5633
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005634 if (!Found.isNull())
5635 return Ty;
5636 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005637 }
5638
5639 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005640 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005641 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005642 // Unlike isSingleElementStruct(), empty structure and array fields
5643 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005644 if (getContext().getLangOpts().CPlusPlus &&
5645 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5646 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005647
5648 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005649 // Nested structures still do though.
5650 if (!Found.isNull())
5651 return Ty;
5652 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005653 }
5654
5655 // Unlike isSingleElementStruct(), trailing padding is allowed.
5656 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005657 if (!Found.isNull())
5658 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005659 }
5660
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005661 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005662}
5663
John McCall7f416cc2015-09-08 08:05:57 +00005664Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5665 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005666 // Assume that va_list type is correct; should be pointer to LLVM type:
5667 // struct {
5668 // i64 __gpr;
5669 // i64 __fpr;
5670 // i8 *__overflow_arg_area;
5671 // i8 *__reg_save_area;
5672 // };
5673
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005674 // Every non-vector argument occupies 8 bytes and is passed by preference
5675 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5676 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005677 Ty = getContext().getCanonicalType(Ty);
5678 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005679 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005680 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005681 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005682 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005683 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005684 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005685 CharUnits UnpaddedSize;
5686 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005687 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005688 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5689 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005690 } else {
5691 if (AI.getCoerceToType())
5692 ArgTy = AI.getCoerceToType();
5693 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005694 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005695 UnpaddedSize = TyInfo.first;
5696 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005697 }
John McCall7f416cc2015-09-08 08:05:57 +00005698 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5699 if (IsVector && UnpaddedSize > PaddedSize)
5700 PaddedSize = CharUnits::fromQuantity(16);
5701 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005702
John McCall7f416cc2015-09-08 08:05:57 +00005703 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005704
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005705 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005706 llvm::Value *PaddedSizeV =
5707 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005708
5709 if (IsVector) {
5710 // Work out the address of a vector argument on the stack.
5711 // Vector arguments are always passed in the high bits of a
5712 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005713 Address OverflowArgAreaPtr =
5714 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005715 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005716 Address OverflowArgArea =
5717 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5718 TyInfo.second);
5719 Address MemAddr =
5720 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005721
5722 // Update overflow_arg_area_ptr pointer
5723 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005724 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5725 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005726 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5727
5728 return MemAddr;
5729 }
5730
John McCall7f416cc2015-09-08 08:05:57 +00005731 assert(PaddedSize.getQuantity() == 8);
5732
5733 unsigned MaxRegs, RegCountField, RegSaveIndex;
5734 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005735 if (InFPRs) {
5736 MaxRegs = 4; // Maximum of 4 FPR arguments
5737 RegCountField = 1; // __fpr
5738 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005739 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005740 } else {
5741 MaxRegs = 5; // Maximum of 5 GPR arguments
5742 RegCountField = 0; // __gpr
5743 RegSaveIndex = 2; // save offset for r2
5744 RegPadding = Padding; // values are passed in the low bits of a GPR
5745 }
5746
John McCall7f416cc2015-09-08 08:05:57 +00005747 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5748 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5749 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005750 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005751 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5752 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005753 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005754
5755 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5756 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5757 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5758 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5759
5760 // Emit code to load the value if it was passed in registers.
5761 CGF.EmitBlock(InRegBlock);
5762
5763 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005764 llvm::Value *ScaledRegCount =
5765 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5766 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005767 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5768 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005769 llvm::Value *RegOffset =
5770 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005771 Address RegSaveAreaPtr =
5772 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5773 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005774 llvm::Value *RegSaveArea =
5775 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005776 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5777 "raw_reg_addr"),
5778 PaddedSize);
5779 Address RegAddr =
5780 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005781
5782 // Update the register count
5783 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5784 llvm::Value *NewRegCount =
5785 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5786 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5787 CGF.EmitBranch(ContBlock);
5788
5789 // Emit code to load the value if it was passed in memory.
5790 CGF.EmitBlock(InMemBlock);
5791
5792 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005793 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5794 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5795 Address OverflowArgArea =
5796 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5797 PaddedSize);
5798 Address RawMemAddr =
5799 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5800 Address MemAddr =
5801 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005802
5803 // Update overflow_arg_area_ptr pointer
5804 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005805 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5806 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005807 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5808 CGF.EmitBranch(ContBlock);
5809
5810 // Return the appropriate result.
5811 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005812 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5813 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005814
5815 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005816 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5817 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005818
5819 return ResAddr;
5820}
5821
Ulrich Weigand47445072013-05-06 16:26:41 +00005822ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5823 if (RetTy->isVoidType())
5824 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005825 if (isVectorArgumentType(RetTy))
5826 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005827 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00005828 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005829 return (isPromotableIntegerType(RetTy) ?
5830 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5831}
5832
5833ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5834 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005835 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00005836 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00005837
5838 // Integers and enums are extended to full register width.
5839 if (isPromotableIntegerType(Ty))
5840 return ABIArgInfo::getExtend();
5841
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005842 // Handle vector types and vector-like structure types. Note that
5843 // as opposed to float-like structure types, we do not allow any
5844 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005845 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005846 QualType SingleElementTy = GetSingleElementType(Ty);
5847 if (isVectorArgumentType(SingleElementTy) &&
5848 getContext().getTypeSize(SingleElementTy) == Size)
5849 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5850
5851 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005852 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00005853 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005854
5855 // Handle small structures.
5856 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5857 // Structures with flexible arrays have variable length, so really
5858 // fail the size test above.
5859 const RecordDecl *RD = RT->getDecl();
5860 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00005861 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005862
5863 // The structure is passed as an unextended integer, a float, or a double.
5864 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005865 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005866 assert(Size == 32 || Size == 64);
5867 if (Size == 32)
5868 PassTy = llvm::Type::getFloatTy(getVMContext());
5869 else
5870 PassTy = llvm::Type::getDoubleTy(getVMContext());
5871 } else
5872 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5873 return ABIArgInfo::getDirect(PassTy);
5874 }
5875
5876 // Non-structure compounds are passed indirectly.
5877 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005878 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005879
Craig Topper8a13c412014-05-21 05:09:00 +00005880 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005881}
5882
5883//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005884// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005885//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005886
5887namespace {
5888
5889class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5890public:
Chris Lattner2b037972010-07-29 02:01:43 +00005891 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5892 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005893 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005894 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005895};
5896
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005897}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005898
Eric Christopher162c91c2015-06-05 22:03:00 +00005899void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005900 llvm::GlobalValue *GV,
5901 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005902 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005903 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5904 // Handle 'interrupt' attribute:
5905 llvm::Function *F = cast<llvm::Function>(GV);
5906
5907 // Step 1: Set ISR calling convention.
5908 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5909
5910 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005911 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005912
5913 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005914 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005915 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5916 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005917 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005918 }
5919}
5920
Chris Lattner0cf24192010-06-28 20:05:43 +00005921//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005922// MIPS ABI Implementation. This works for both little-endian and
5923// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005924//===----------------------------------------------------------------------===//
5925
John McCall943fae92010-05-27 06:19:26 +00005926namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005927class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005928 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005929 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5930 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005931 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005932 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005933 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005934 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005935public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005936 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005937 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005938 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005939
5940 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005941 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005942 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005943 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5944 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005945 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005946};
5947
John McCall943fae92010-05-27 06:19:26 +00005948class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005949 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005950public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005951 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5952 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005953 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005954
Craig Topper4f12f102014-03-12 06:41:41 +00005955 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005956 return 29;
5957 }
5958
Eric Christopher162c91c2015-06-05 22:03:00 +00005959 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005960 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005961 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005962 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005963 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005964 if (FD->hasAttr<Mips16Attr>()) {
5965 Fn->addFnAttr("mips16");
5966 }
5967 else if (FD->hasAttr<NoMips16Attr>()) {
5968 Fn->addFnAttr("nomips16");
5969 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005970
5971 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
5972 if (!Attr)
5973 return;
5974
5975 const char *Kind;
5976 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005977 case MipsInterruptAttr::eic: Kind = "eic"; break;
5978 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
5979 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
5980 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
5981 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
5982 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
5983 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
5984 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
5985 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
5986 }
5987
5988 Fn->addFnAttr("interrupt", Kind);
5989
Reed Kotler373feca2013-01-16 17:10:28 +00005990 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005991
John McCall943fae92010-05-27 06:19:26 +00005992 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005993 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005994
Craig Topper4f12f102014-03-12 06:41:41 +00005995 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005996 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005997 }
John McCall943fae92010-05-27 06:19:26 +00005998};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005999}
John McCall943fae92010-05-27 06:19:26 +00006000
Eric Christopher7565e0d2015-05-29 23:09:49 +00006001void MipsABIInfo::CoerceToIntArgs(
6002 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006003 llvm::IntegerType *IntTy =
6004 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006005
6006 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6007 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6008 ArgList.push_back(IntTy);
6009
6010 // If necessary, add one more integer type to ArgList.
6011 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6012
6013 if (R)
6014 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006015}
6016
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006017// In N32/64, an aligned double precision floating point field is passed in
6018// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006019llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006020 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6021
6022 if (IsO32) {
6023 CoerceToIntArgs(TySize, ArgList);
6024 return llvm::StructType::get(getVMContext(), ArgList);
6025 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006026
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006027 if (Ty->isComplexType())
6028 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006029
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006030 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006031
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006032 // Unions/vectors are passed in integer registers.
6033 if (!RT || !RT->isStructureOrClassType()) {
6034 CoerceToIntArgs(TySize, ArgList);
6035 return llvm::StructType::get(getVMContext(), ArgList);
6036 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006037
6038 const RecordDecl *RD = RT->getDecl();
6039 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006040 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006041
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006042 uint64_t LastOffset = 0;
6043 unsigned idx = 0;
6044 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6045
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006046 // Iterate over fields in the struct/class and check if there are any aligned
6047 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006048 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6049 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006050 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006051 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6052
6053 if (!BT || BT->getKind() != BuiltinType::Double)
6054 continue;
6055
6056 uint64_t Offset = Layout.getFieldOffset(idx);
6057 if (Offset % 64) // Ignore doubles that are not aligned.
6058 continue;
6059
6060 // Add ((Offset - LastOffset) / 64) args of type i64.
6061 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6062 ArgList.push_back(I64);
6063
6064 // Add double type.
6065 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6066 LastOffset = Offset + 64;
6067 }
6068
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006069 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6070 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006071
6072 return llvm::StructType::get(getVMContext(), ArgList);
6073}
6074
Akira Hatanakaddd66342013-10-29 18:41:15 +00006075llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6076 uint64_t Offset) const {
6077 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006078 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006079
Akira Hatanakaddd66342013-10-29 18:41:15 +00006080 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006081}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006082
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006083ABIArgInfo
6084MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006085 Ty = useFirstFieldIfTransparentUnion(Ty);
6086
Akira Hatanaka1632af62012-01-09 19:31:25 +00006087 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006088 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006089 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006090
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006091 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6092 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006093 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6094 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006095
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006096 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006097 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006098 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006099 return ABIArgInfo::getIgnore();
6100
Mark Lacey3825e832013-10-06 01:33:34 +00006101 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006102 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006103 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006104 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006105
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006106 // If we have reached here, aggregates are passed directly by coercing to
6107 // another structure type. Padding is inserted if the offset of the
6108 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006109 ABIArgInfo ArgInfo =
6110 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6111 getPaddingType(OrigOffset, CurrOffset));
6112 ArgInfo.setInReg(true);
6113 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006114 }
6115
6116 // Treat an enum type as its underlying type.
6117 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6118 Ty = EnumTy->getDecl()->getIntegerType();
6119
Daniel Sanders5b445b32014-10-24 14:42:42 +00006120 // All integral types are promoted to the GPR width.
6121 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006122 return ABIArgInfo::getExtend();
6123
Akira Hatanakaddd66342013-10-29 18:41:15 +00006124 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006125 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006126}
6127
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006128llvm::Type*
6129MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006130 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006131 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006132
Akira Hatanakab6f74432012-02-09 18:49:26 +00006133 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006134 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006135 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6136 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006137
Akira Hatanakab6f74432012-02-09 18:49:26 +00006138 // N32/64 returns struct/classes in floating point registers if the
6139 // following conditions are met:
6140 // 1. The size of the struct/class is no larger than 128-bit.
6141 // 2. The struct/class has one or two fields all of which are floating
6142 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006143 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006144 //
6145 // Any other composite results are returned in integer registers.
6146 //
6147 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6148 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6149 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006150 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006151
Akira Hatanakab6f74432012-02-09 18:49:26 +00006152 if (!BT || !BT->isFloatingPoint())
6153 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006154
David Blaikie2d7c57e2012-04-30 02:36:29 +00006155 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006156 }
6157
6158 if (b == e)
6159 return llvm::StructType::get(getVMContext(), RTList,
6160 RD->hasAttr<PackedAttr>());
6161
6162 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006163 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006164 }
6165
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006166 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006167 return llvm::StructType::get(getVMContext(), RTList);
6168}
6169
Akira Hatanakab579fe52011-06-02 00:09:17 +00006170ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006171 uint64_t Size = getContext().getTypeSize(RetTy);
6172
Daniel Sandersed39f582014-09-04 13:28:14 +00006173 if (RetTy->isVoidType())
6174 return ABIArgInfo::getIgnore();
6175
6176 // O32 doesn't treat zero-sized structs differently from other structs.
6177 // However, N32/N64 ignores zero sized return values.
6178 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006179 return ABIArgInfo::getIgnore();
6180
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006181 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006182 if (Size <= 128) {
6183 if (RetTy->isAnyComplexType())
6184 return ABIArgInfo::getDirect();
6185
Daniel Sanderse5018b62014-09-04 15:05:39 +00006186 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006187 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006188 if (!IsO32 ||
6189 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6190 ABIArgInfo ArgInfo =
6191 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6192 ArgInfo.setInReg(true);
6193 return ArgInfo;
6194 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006195 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006196
John McCall7f416cc2015-09-08 08:05:57 +00006197 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006198 }
6199
6200 // Treat an enum type as its underlying type.
6201 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6202 RetTy = EnumTy->getDecl()->getIntegerType();
6203
6204 return (RetTy->isPromotableIntegerType() ?
6205 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6206}
6207
6208void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006209 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006210 if (!getCXXABI().classifyReturnType(FI))
6211 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006212
Eric Christopher7565e0d2015-05-29 23:09:49 +00006213 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006214 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006215
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006216 for (auto &I : FI.arguments())
6217 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006218}
6219
John McCall7f416cc2015-09-08 08:05:57 +00006220Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6221 QualType OrigTy) const {
6222 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006223
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006224 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6225 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006226 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006227 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006228 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006229 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006230 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006231 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006232 DidPromote = true;
6233 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6234 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006235 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006236
John McCall7f416cc2015-09-08 08:05:57 +00006237 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006238
John McCall7f416cc2015-09-08 08:05:57 +00006239 // The alignment of things in the argument area is never larger than
6240 // StackAlignInBytes.
6241 TyInfo.second =
6242 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6243
6244 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6245 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6246
6247 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6248 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6249
6250
6251 // If there was a promotion, "unpromote" into a temporary.
6252 // TODO: can we just use a pointer into a subset of the original slot?
6253 if (DidPromote) {
6254 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6255 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6256
6257 // Truncate down to the right width.
6258 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6259 : CGF.IntPtrTy);
6260 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6261 if (OrigTy->isPointerType())
6262 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6263
6264 CGF.Builder.CreateStore(V, Temp);
6265 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006266 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006267
John McCall7f416cc2015-09-08 08:05:57 +00006268 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006269}
6270
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006271bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6272 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006273
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006274 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6275 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6276 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006277
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006278 return false;
6279}
6280
John McCall943fae92010-05-27 06:19:26 +00006281bool
6282MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6283 llvm::Value *Address) const {
6284 // This information comes from gcc's implementation, which seems to
6285 // as canonical as it gets.
6286
John McCall943fae92010-05-27 06:19:26 +00006287 // Everything on MIPS is 4 bytes. Double-precision FP registers
6288 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006289 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006290
6291 // 0-31 are the general purpose registers, $0 - $31.
6292 // 32-63 are the floating-point registers, $f0 - $f31.
6293 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6294 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006295 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006296
6297 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6298 // They are one bit wide and ignored here.
6299
6300 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6301 // (coprocessor 1 is the FP unit)
6302 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6303 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6304 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006305 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006306 return false;
6307}
6308
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006309//===----------------------------------------------------------------------===//
6310// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006311// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006312// handling.
6313//===----------------------------------------------------------------------===//
6314
6315namespace {
6316
6317class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6318public:
6319 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6320 : DefaultTargetCodeGenInfo(CGT) {}
6321
Eric Christopher162c91c2015-06-05 22:03:00 +00006322 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006323 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006324};
6325
Eric Christopher162c91c2015-06-05 22:03:00 +00006326void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006327 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006328 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006329 if (!FD) return;
6330
6331 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006332
David Blaikiebbafb8a2012-03-11 07:00:24 +00006333 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006334 if (FD->hasAttr<OpenCLKernelAttr>()) {
6335 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006336 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006337 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6338 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006339 // Convert the reqd_work_group_size() attributes to metadata.
6340 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006341 llvm::NamedMDNode *OpenCLMetadata =
6342 M.getModule().getOrInsertNamedMetadata(
6343 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006344
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006345 SmallVector<llvm::Metadata *, 5> Operands;
6346 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006347
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006348 Operands.push_back(
6349 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6350 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6351 Operands.push_back(
6352 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6353 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6354 Operands.push_back(
6355 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6356 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006357
Eric Christopher7565e0d2015-05-29 23:09:49 +00006358 // Add a boolean constant operand for "required" (true) or "hint"
6359 // (false) for implementing the work_group_size_hint attr later.
6360 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006361 Operands.push_back(
6362 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006363 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6364 }
6365 }
6366 }
6367}
6368
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006369}
John McCall943fae92010-05-27 06:19:26 +00006370
Tony Linthicum76329bf2011-12-12 21:14:55 +00006371//===----------------------------------------------------------------------===//
6372// Hexagon ABI Implementation
6373//===----------------------------------------------------------------------===//
6374
6375namespace {
6376
6377class HexagonABIInfo : public ABIInfo {
6378
6379
6380public:
6381 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6382
6383private:
6384
6385 ABIArgInfo classifyReturnType(QualType RetTy) const;
6386 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6387
Craig Topper4f12f102014-03-12 06:41:41 +00006388 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006389
John McCall7f416cc2015-09-08 08:05:57 +00006390 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6391 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006392};
6393
6394class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6395public:
6396 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6397 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6398
Craig Topper4f12f102014-03-12 06:41:41 +00006399 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006400 return 29;
6401 }
6402};
6403
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006404}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006405
6406void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006407 if (!getCXXABI().classifyReturnType(FI))
6408 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006409 for (auto &I : FI.arguments())
6410 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006411}
6412
6413ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6414 if (!isAggregateTypeForABI(Ty)) {
6415 // Treat an enum type as its underlying type.
6416 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6417 Ty = EnumTy->getDecl()->getIntegerType();
6418
6419 return (Ty->isPromotableIntegerType() ?
6420 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6421 }
6422
6423 // Ignore empty records.
6424 if (isEmptyRecord(getContext(), Ty, true))
6425 return ABIArgInfo::getIgnore();
6426
Mark Lacey3825e832013-10-06 01:33:34 +00006427 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006428 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006429
6430 uint64_t Size = getContext().getTypeSize(Ty);
6431 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006432 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006433 // Pass in the smallest viable integer type.
6434 else if (Size > 32)
6435 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6436 else if (Size > 16)
6437 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6438 else if (Size > 8)
6439 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6440 else
6441 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6442}
6443
6444ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6445 if (RetTy->isVoidType())
6446 return ABIArgInfo::getIgnore();
6447
6448 // Large vector types should be returned via memory.
6449 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006450 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006451
6452 if (!isAggregateTypeForABI(RetTy)) {
6453 // Treat an enum type as its underlying type.
6454 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6455 RetTy = EnumTy->getDecl()->getIntegerType();
6456
6457 return (RetTy->isPromotableIntegerType() ?
6458 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6459 }
6460
Tony Linthicum76329bf2011-12-12 21:14:55 +00006461 if (isEmptyRecord(getContext(), RetTy, true))
6462 return ABIArgInfo::getIgnore();
6463
6464 // Aggregates <= 8 bytes are returned in r0; other aggregates
6465 // are returned indirectly.
6466 uint64_t Size = getContext().getTypeSize(RetTy);
6467 if (Size <= 64) {
6468 // Return in the smallest viable integer type.
6469 if (Size <= 8)
6470 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6471 if (Size <= 16)
6472 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6473 if (Size <= 32)
6474 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6475 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6476 }
6477
John McCall7f416cc2015-09-08 08:05:57 +00006478 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006479}
6480
John McCall7f416cc2015-09-08 08:05:57 +00006481Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6482 QualType Ty) const {
6483 // FIXME: Someone needs to audit that this handle alignment correctly.
6484 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6485 getContext().getTypeInfoInChars(Ty),
6486 CharUnits::fromQuantity(4),
6487 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006488}
6489
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006490//===----------------------------------------------------------------------===//
6491// AMDGPU ABI Implementation
6492//===----------------------------------------------------------------------===//
6493
6494namespace {
6495
6496class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6497public:
6498 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6499 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006500 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006501 CodeGen::CodeGenModule &M) const override;
6502};
6503
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006504}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006505
Eric Christopher162c91c2015-06-05 22:03:00 +00006506void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006507 const Decl *D,
6508 llvm::GlobalValue *GV,
6509 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006510 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006511 if (!FD)
6512 return;
6513
6514 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6515 llvm::Function *F = cast<llvm::Function>(GV);
6516 uint32_t NumVGPR = Attr->getNumVGPR();
6517 if (NumVGPR != 0)
6518 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6519 }
6520
6521 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6522 llvm::Function *F = cast<llvm::Function>(GV);
6523 unsigned NumSGPR = Attr->getNumSGPR();
6524 if (NumSGPR != 0)
6525 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6526 }
6527}
6528
Tony Linthicum76329bf2011-12-12 21:14:55 +00006529
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006530//===----------------------------------------------------------------------===//
6531// SPARC v9 ABI Implementation.
6532// Based on the SPARC Compliance Definition version 2.4.1.
6533//
6534// Function arguments a mapped to a nominal "parameter array" and promoted to
6535// registers depending on their type. Each argument occupies 8 or 16 bytes in
6536// the array, structs larger than 16 bytes are passed indirectly.
6537//
6538// One case requires special care:
6539//
6540// struct mixed {
6541// int i;
6542// float f;
6543// };
6544//
6545// When a struct mixed is passed by value, it only occupies 8 bytes in the
6546// parameter array, but the int is passed in an integer register, and the float
6547// is passed in a floating point register. This is represented as two arguments
6548// with the LLVM IR inreg attribute:
6549//
6550// declare void f(i32 inreg %i, float inreg %f)
6551//
6552// The code generator will only allocate 4 bytes from the parameter array for
6553// the inreg arguments. All other arguments are allocated a multiple of 8
6554// bytes.
6555//
6556namespace {
6557class SparcV9ABIInfo : public ABIInfo {
6558public:
6559 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6560
6561private:
6562 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006563 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006564 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6565 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006566
6567 // Coercion type builder for structs passed in registers. The coercion type
6568 // serves two purposes:
6569 //
6570 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6571 // in registers.
6572 // 2. Expose aligned floating point elements as first-level elements, so the
6573 // code generator knows to pass them in floating point registers.
6574 //
6575 // We also compute the InReg flag which indicates that the struct contains
6576 // aligned 32-bit floats.
6577 //
6578 struct CoerceBuilder {
6579 llvm::LLVMContext &Context;
6580 const llvm::DataLayout &DL;
6581 SmallVector<llvm::Type*, 8> Elems;
6582 uint64_t Size;
6583 bool InReg;
6584
6585 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6586 : Context(c), DL(dl), Size(0), InReg(false) {}
6587
6588 // Pad Elems with integers until Size is ToSize.
6589 void pad(uint64_t ToSize) {
6590 assert(ToSize >= Size && "Cannot remove elements");
6591 if (ToSize == Size)
6592 return;
6593
6594 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006595 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006596 if (Aligned > Size && Aligned <= ToSize) {
6597 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6598 Size = Aligned;
6599 }
6600
6601 // Add whole 64-bit words.
6602 while (Size + 64 <= ToSize) {
6603 Elems.push_back(llvm::Type::getInt64Ty(Context));
6604 Size += 64;
6605 }
6606
6607 // Final in-word padding.
6608 if (Size < ToSize) {
6609 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6610 Size = ToSize;
6611 }
6612 }
6613
6614 // Add a floating point element at Offset.
6615 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6616 // Unaligned floats are treated as integers.
6617 if (Offset % Bits)
6618 return;
6619 // The InReg flag is only required if there are any floats < 64 bits.
6620 if (Bits < 64)
6621 InReg = true;
6622 pad(Offset);
6623 Elems.push_back(Ty);
6624 Size = Offset + Bits;
6625 }
6626
6627 // Add a struct type to the coercion type, starting at Offset (in bits).
6628 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6629 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6630 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6631 llvm::Type *ElemTy = StrTy->getElementType(i);
6632 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6633 switch (ElemTy->getTypeID()) {
6634 case llvm::Type::StructTyID:
6635 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6636 break;
6637 case llvm::Type::FloatTyID:
6638 addFloat(ElemOffset, ElemTy, 32);
6639 break;
6640 case llvm::Type::DoubleTyID:
6641 addFloat(ElemOffset, ElemTy, 64);
6642 break;
6643 case llvm::Type::FP128TyID:
6644 addFloat(ElemOffset, ElemTy, 128);
6645 break;
6646 case llvm::Type::PointerTyID:
6647 if (ElemOffset % 64 == 0) {
6648 pad(ElemOffset);
6649 Elems.push_back(ElemTy);
6650 Size += 64;
6651 }
6652 break;
6653 default:
6654 break;
6655 }
6656 }
6657 }
6658
6659 // Check if Ty is a usable substitute for the coercion type.
6660 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006661 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006662 }
6663
6664 // Get the coercion type as a literal struct type.
6665 llvm::Type *getType() const {
6666 if (Elems.size() == 1)
6667 return Elems.front();
6668 else
6669 return llvm::StructType::get(Context, Elems);
6670 }
6671 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006672};
6673} // end anonymous namespace
6674
6675ABIArgInfo
6676SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6677 if (Ty->isVoidType())
6678 return ABIArgInfo::getIgnore();
6679
6680 uint64_t Size = getContext().getTypeSize(Ty);
6681
6682 // Anything too big to fit in registers is passed with an explicit indirect
6683 // pointer / sret pointer.
6684 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006685 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006686
6687 // Treat an enum type as its underlying type.
6688 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6689 Ty = EnumTy->getDecl()->getIntegerType();
6690
6691 // Integer types smaller than a register are extended.
6692 if (Size < 64 && Ty->isIntegerType())
6693 return ABIArgInfo::getExtend();
6694
6695 // Other non-aggregates go in registers.
6696 if (!isAggregateTypeForABI(Ty))
6697 return ABIArgInfo::getDirect();
6698
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006699 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6700 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6701 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006702 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006703
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006704 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006705 // Build a coercion type from the LLVM struct type.
6706 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6707 if (!StrTy)
6708 return ABIArgInfo::getDirect();
6709
6710 CoerceBuilder CB(getVMContext(), getDataLayout());
6711 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006712 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006713
6714 // Try to use the original type for coercion.
6715 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6716
6717 if (CB.InReg)
6718 return ABIArgInfo::getDirectInReg(CoerceTy);
6719 else
6720 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006721}
6722
John McCall7f416cc2015-09-08 08:05:57 +00006723Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6724 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006725 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6726 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6727 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6728 AI.setCoerceToType(ArgTy);
6729
John McCall7f416cc2015-09-08 08:05:57 +00006730 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006731
John McCall7f416cc2015-09-08 08:05:57 +00006732 CGBuilderTy &Builder = CGF.Builder;
6733 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6734 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6735
6736 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
6737
6738 Address ArgAddr = Address::invalid();
6739 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006740 switch (AI.getKind()) {
6741 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006742 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006743 llvm_unreachable("Unsupported ABI kind for va_arg");
6744
John McCall7f416cc2015-09-08 08:05:57 +00006745 case ABIArgInfo::Extend: {
6746 Stride = SlotSize;
6747 CharUnits Offset = SlotSize - TypeInfo.first;
6748 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006749 break;
John McCall7f416cc2015-09-08 08:05:57 +00006750 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006751
John McCall7f416cc2015-09-08 08:05:57 +00006752 case ABIArgInfo::Direct: {
6753 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00006754 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006755 ArgAddr = Addr;
6756 break;
John McCall7f416cc2015-09-08 08:05:57 +00006757 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006758
6759 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006760 Stride = SlotSize;
6761 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
6762 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
6763 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006764 break;
6765
6766 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006767 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006768 }
6769
6770 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006771 llvm::Value *NextPtr =
6772 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
6773 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006774
John McCall7f416cc2015-09-08 08:05:57 +00006775 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006776}
6777
6778void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6779 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006780 for (auto &I : FI.arguments())
6781 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006782}
6783
6784namespace {
6785class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6786public:
6787 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6788 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006789
Craig Topper4f12f102014-03-12 06:41:41 +00006790 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006791 return 14;
6792 }
6793
6794 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006795 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006796};
6797} // end anonymous namespace
6798
Roman Divackyf02c9942014-02-24 18:46:27 +00006799bool
6800SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6801 llvm::Value *Address) const {
6802 // This is calculated from the LLVM and GCC tables and verified
6803 // against gcc output. AFAIK all ABIs use the same encoding.
6804
6805 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6806
6807 llvm::IntegerType *i8 = CGF.Int8Ty;
6808 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6809 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6810
6811 // 0-31: the 8-byte general-purpose registers
6812 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6813
6814 // 32-63: f0-31, the 4-byte floating-point registers
6815 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6816
6817 // Y = 64
6818 // PSR = 65
6819 // WIM = 66
6820 // TBR = 67
6821 // PC = 68
6822 // NPC = 69
6823 // FSR = 70
6824 // CSR = 71
6825 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006826
Roman Divackyf02c9942014-02-24 18:46:27 +00006827 // 72-87: d0-15, the 8-byte floating-point registers
6828 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6829
6830 return false;
6831}
6832
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006833
Robert Lytton0e076492013-08-13 09:43:10 +00006834//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006835// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006836//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006837
Robert Lytton0e076492013-08-13 09:43:10 +00006838namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006839
6840/// A SmallStringEnc instance is used to build up the TypeString by passing
6841/// it by reference between functions that append to it.
6842typedef llvm::SmallString<128> SmallStringEnc;
6843
6844/// TypeStringCache caches the meta encodings of Types.
6845///
6846/// The reason for caching TypeStrings is two fold:
6847/// 1. To cache a type's encoding for later uses;
6848/// 2. As a means to break recursive member type inclusion.
6849///
6850/// A cache Entry can have a Status of:
6851/// NonRecursive: The type encoding is not recursive;
6852/// Recursive: The type encoding is recursive;
6853/// Incomplete: An incomplete TypeString;
6854/// IncompleteUsed: An incomplete TypeString that has been used in a
6855/// Recursive type encoding.
6856///
6857/// A NonRecursive entry will have all of its sub-members expanded as fully
6858/// as possible. Whilst it may contain types which are recursive, the type
6859/// itself is not recursive and thus its encoding may be safely used whenever
6860/// the type is encountered.
6861///
6862/// A Recursive entry will have all of its sub-members expanded as fully as
6863/// possible. The type itself is recursive and it may contain other types which
6864/// are recursive. The Recursive encoding must not be used during the expansion
6865/// of a recursive type's recursive branch. For simplicity the code uses
6866/// IncompleteCount to reject all usage of Recursive encodings for member types.
6867///
6868/// An Incomplete entry is always a RecordType and only encodes its
6869/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6870/// are placed into the cache during type expansion as a means to identify and
6871/// handle recursive inclusion of types as sub-members. If there is recursion
6872/// the entry becomes IncompleteUsed.
6873///
6874/// During the expansion of a RecordType's members:
6875///
6876/// If the cache contains a NonRecursive encoding for the member type, the
6877/// cached encoding is used;
6878///
6879/// If the cache contains a Recursive encoding for the member type, the
6880/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6881///
6882/// If the member is a RecordType, an Incomplete encoding is placed into the
6883/// cache to break potential recursive inclusion of itself as a sub-member;
6884///
6885/// Once a member RecordType has been expanded, its temporary incomplete
6886/// entry is removed from the cache. If a Recursive encoding was swapped out
6887/// it is swapped back in;
6888///
6889/// If an incomplete entry is used to expand a sub-member, the incomplete
6890/// entry is marked as IncompleteUsed. The cache keeps count of how many
6891/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6892///
6893/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6894/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6895/// Else the member is part of a recursive type and thus the recursion has
6896/// been exited too soon for the encoding to be correct for the member.
6897///
6898class TypeStringCache {
6899 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6900 struct Entry {
6901 std::string Str; // The encoded TypeString for the type.
6902 enum Status State; // Information about the encoding in 'Str'.
6903 std::string Swapped; // A temporary place holder for a Recursive encoding
6904 // during the expansion of RecordType's members.
6905 };
6906 std::map<const IdentifierInfo *, struct Entry> Map;
6907 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6908 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6909public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006910 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006911 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6912 bool removeIncomplete(const IdentifierInfo *ID);
6913 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6914 bool IsRecursive);
6915 StringRef lookupStr(const IdentifierInfo *ID);
6916};
6917
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006918/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006919/// FieldEncoding is a helper for this ordering process.
6920class FieldEncoding {
6921 bool HasName;
6922 std::string Enc;
6923public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006924 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6925 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006926 bool operator<(const FieldEncoding &rhs) const {
6927 if (HasName != rhs.HasName) return HasName;
6928 return Enc < rhs.Enc;
6929 }
6930};
6931
Robert Lytton7d1db152013-08-19 09:46:39 +00006932class XCoreABIInfo : public DefaultABIInfo {
6933public:
6934 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00006935 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6936 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006937};
6938
Robert Lyttond21e2d72014-03-03 13:45:29 +00006939class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006940 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006941public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006942 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006943 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006944 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6945 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006946};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006947
Robert Lytton2d196952013-10-11 10:29:34 +00006948} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006949
John McCall7f416cc2015-09-08 08:05:57 +00006950Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6951 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006952 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006953
Robert Lytton2d196952013-10-11 10:29:34 +00006954 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006955 CharUnits SlotSize = CharUnits::fromQuantity(4);
6956 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00006957
Robert Lytton2d196952013-10-11 10:29:34 +00006958 // Handle the argument.
6959 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006960 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00006961 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6962 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6963 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006964 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00006965
6966 Address Val = Address::invalid();
6967 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00006968 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006969 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006970 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006971 llvm_unreachable("Unsupported ABI kind for va_arg");
6972 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006973 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
6974 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00006975 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006976 case ABIArgInfo::Extend:
6977 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00006978 Val = Builder.CreateBitCast(AP, ArgPtrTy);
6979 ArgSize = CharUnits::fromQuantity(
6980 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00006981 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00006982 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006983 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006984 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
6985 Val = Address(Builder.CreateLoad(Val), TypeAlign);
6986 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00006987 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006988 }
Robert Lytton2d196952013-10-11 10:29:34 +00006989
6990 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006991 if (!ArgSize.isZero()) {
6992 llvm::Value *APN =
6993 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
6994 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006995 }
John McCall7f416cc2015-09-08 08:05:57 +00006996
Robert Lytton2d196952013-10-11 10:29:34 +00006997 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006998}
Robert Lytton0e076492013-08-13 09:43:10 +00006999
Robert Lytton844aeeb2014-05-02 09:33:20 +00007000/// During the expansion of a RecordType, an incomplete TypeString is placed
7001/// into the cache as a means to identify and break recursion.
7002/// If there is a Recursive encoding in the cache, it is swapped out and will
7003/// be reinserted by removeIncomplete().
7004/// All other types of encoding should have been used rather than arriving here.
7005void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7006 std::string StubEnc) {
7007 if (!ID)
7008 return;
7009 Entry &E = Map[ID];
7010 assert( (E.Str.empty() || E.State == Recursive) &&
7011 "Incorrectly use of addIncomplete");
7012 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7013 E.Swapped.swap(E.Str); // swap out the Recursive
7014 E.Str.swap(StubEnc);
7015 E.State = Incomplete;
7016 ++IncompleteCount;
7017}
7018
7019/// Once the RecordType has been expanded, the temporary incomplete TypeString
7020/// must be removed from the cache.
7021/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7022/// Returns true if the RecordType was defined recursively.
7023bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7024 if (!ID)
7025 return false;
7026 auto I = Map.find(ID);
7027 assert(I != Map.end() && "Entry not present");
7028 Entry &E = I->second;
7029 assert( (E.State == Incomplete ||
7030 E.State == IncompleteUsed) &&
7031 "Entry must be an incomplete type");
7032 bool IsRecursive = false;
7033 if (E.State == IncompleteUsed) {
7034 // We made use of our Incomplete encoding, thus we are recursive.
7035 IsRecursive = true;
7036 --IncompleteUsedCount;
7037 }
7038 if (E.Swapped.empty())
7039 Map.erase(I);
7040 else {
7041 // Swap the Recursive back.
7042 E.Swapped.swap(E.Str);
7043 E.Swapped.clear();
7044 E.State = Recursive;
7045 }
7046 --IncompleteCount;
7047 return IsRecursive;
7048}
7049
7050/// Add the encoded TypeString to the cache only if it is NonRecursive or
7051/// Recursive (viz: all sub-members were expanded as fully as possible).
7052void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7053 bool IsRecursive) {
7054 if (!ID || IncompleteUsedCount)
7055 return; // No key or it is is an incomplete sub-type so don't add.
7056 Entry &E = Map[ID];
7057 if (IsRecursive && !E.Str.empty()) {
7058 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7059 "This is not the same Recursive entry");
7060 // The parent container was not recursive after all, so we could have used
7061 // this Recursive sub-member entry after all, but we assumed the worse when
7062 // we started viz: IncompleteCount!=0.
7063 return;
7064 }
7065 assert(E.Str.empty() && "Entry already present");
7066 E.Str = Str.str();
7067 E.State = IsRecursive? Recursive : NonRecursive;
7068}
7069
7070/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7071/// are recursively expanding a type (IncompleteCount != 0) and the cached
7072/// encoding is Recursive, return an empty StringRef.
7073StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7074 if (!ID)
7075 return StringRef(); // We have no key.
7076 auto I = Map.find(ID);
7077 if (I == Map.end())
7078 return StringRef(); // We have no encoding.
7079 Entry &E = I->second;
7080 if (E.State == Recursive && IncompleteCount)
7081 return StringRef(); // We don't use Recursive encodings for member types.
7082
7083 if (E.State == Incomplete) {
7084 // The incomplete type is being used to break out of recursion.
7085 E.State = IncompleteUsed;
7086 ++IncompleteUsedCount;
7087 }
7088 return E.Str.c_str();
7089}
7090
7091/// The XCore ABI includes a type information section that communicates symbol
7092/// type information to the linker. The linker uses this information to verify
7093/// safety/correctness of things such as array bound and pointers et al.
7094/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7095/// This type information (TypeString) is emitted into meta data for all global
7096/// symbols: definitions, declarations, functions & variables.
7097///
7098/// The TypeString carries type, qualifier, name, size & value details.
7099/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007100/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007101/// The output is tested by test/CodeGen/xcore-stringtype.c.
7102///
7103static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7104 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7105
7106/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7107void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7108 CodeGen::CodeGenModule &CGM) const {
7109 SmallStringEnc Enc;
7110 if (getTypeString(Enc, D, CGM, TSC)) {
7111 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007112 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7113 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007114 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7115 llvm::NamedMDNode *MD =
7116 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7117 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7118 }
7119}
7120
7121static bool appendType(SmallStringEnc &Enc, QualType QType,
7122 const CodeGen::CodeGenModule &CGM,
7123 TypeStringCache &TSC);
7124
7125/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007126/// Builds a SmallVector containing the encoded field types in declaration
7127/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007128static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7129 const RecordDecl *RD,
7130 const CodeGen::CodeGenModule &CGM,
7131 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007132 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007133 SmallStringEnc Enc;
7134 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007135 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007136 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007137 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007138 Enc += "b(";
7139 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007140 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007141 Enc += ':';
7142 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007143 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007144 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007145 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007146 Enc += ')';
7147 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007148 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007149 }
7150 return true;
7151}
7152
7153/// Appends structure and union types to Enc and adds encoding to cache.
7154/// Recursively calls appendType (via extractFieldType) for each field.
7155/// Union types have their fields ordered according to the ABI.
7156static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7157 const CodeGen::CodeGenModule &CGM,
7158 TypeStringCache &TSC, const IdentifierInfo *ID) {
7159 // Append the cached TypeString if we have one.
7160 StringRef TypeString = TSC.lookupStr(ID);
7161 if (!TypeString.empty()) {
7162 Enc += TypeString;
7163 return true;
7164 }
7165
7166 // Start to emit an incomplete TypeString.
7167 size_t Start = Enc.size();
7168 Enc += (RT->isUnionType()? 'u' : 's');
7169 Enc += '(';
7170 if (ID)
7171 Enc += ID->getName();
7172 Enc += "){";
7173
7174 // We collect all encoded fields and order as necessary.
7175 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007176 const RecordDecl *RD = RT->getDecl()->getDefinition();
7177 if (RD && !RD->field_empty()) {
7178 // An incomplete TypeString stub is placed in the cache for this RecordType
7179 // so that recursive calls to this RecordType will use it whilst building a
7180 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007181 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007182 std::string StubEnc(Enc.substr(Start).str());
7183 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7184 TSC.addIncomplete(ID, std::move(StubEnc));
7185 if (!extractFieldType(FE, RD, CGM, TSC)) {
7186 (void) TSC.removeIncomplete(ID);
7187 return false;
7188 }
7189 IsRecursive = TSC.removeIncomplete(ID);
7190 // The ABI requires unions to be sorted but not structures.
7191 // See FieldEncoding::operator< for sort algorithm.
7192 if (RT->isUnionType())
7193 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007194 // We can now complete the TypeString.
7195 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007196 for (unsigned I = 0; I != E; ++I) {
7197 if (I)
7198 Enc += ',';
7199 Enc += FE[I].str();
7200 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007201 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007202 Enc += '}';
7203 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7204 return true;
7205}
7206
7207/// Appends enum types to Enc and adds the encoding to the cache.
7208static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7209 TypeStringCache &TSC,
7210 const IdentifierInfo *ID) {
7211 // Append the cached TypeString if we have one.
7212 StringRef TypeString = TSC.lookupStr(ID);
7213 if (!TypeString.empty()) {
7214 Enc += TypeString;
7215 return true;
7216 }
7217
7218 size_t Start = Enc.size();
7219 Enc += "e(";
7220 if (ID)
7221 Enc += ID->getName();
7222 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007223
7224 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007225 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007226 SmallVector<FieldEncoding, 16> FE;
7227 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7228 ++I) {
7229 SmallStringEnc EnumEnc;
7230 EnumEnc += "m(";
7231 EnumEnc += I->getName();
7232 EnumEnc += "){";
7233 I->getInitVal().toString(EnumEnc);
7234 EnumEnc += '}';
7235 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7236 }
7237 std::sort(FE.begin(), FE.end());
7238 unsigned E = FE.size();
7239 for (unsigned I = 0; I != E; ++I) {
7240 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007241 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007242 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007243 }
7244 }
7245 Enc += '}';
7246 TSC.addIfComplete(ID, Enc.substr(Start), false);
7247 return true;
7248}
7249
7250/// Appends type's qualifier to Enc.
7251/// This is done prior to appending the type's encoding.
7252static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7253 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007254 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007255 int Lookup = 0;
7256 if (QT.isConstQualified())
7257 Lookup += 1<<0;
7258 if (QT.isRestrictQualified())
7259 Lookup += 1<<1;
7260 if (QT.isVolatileQualified())
7261 Lookup += 1<<2;
7262 Enc += Table[Lookup];
7263}
7264
7265/// Appends built-in types to Enc.
7266static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7267 const char *EncType;
7268 switch (BT->getKind()) {
7269 case BuiltinType::Void:
7270 EncType = "0";
7271 break;
7272 case BuiltinType::Bool:
7273 EncType = "b";
7274 break;
7275 case BuiltinType::Char_U:
7276 EncType = "uc";
7277 break;
7278 case BuiltinType::UChar:
7279 EncType = "uc";
7280 break;
7281 case BuiltinType::SChar:
7282 EncType = "sc";
7283 break;
7284 case BuiltinType::UShort:
7285 EncType = "us";
7286 break;
7287 case BuiltinType::Short:
7288 EncType = "ss";
7289 break;
7290 case BuiltinType::UInt:
7291 EncType = "ui";
7292 break;
7293 case BuiltinType::Int:
7294 EncType = "si";
7295 break;
7296 case BuiltinType::ULong:
7297 EncType = "ul";
7298 break;
7299 case BuiltinType::Long:
7300 EncType = "sl";
7301 break;
7302 case BuiltinType::ULongLong:
7303 EncType = "ull";
7304 break;
7305 case BuiltinType::LongLong:
7306 EncType = "sll";
7307 break;
7308 case BuiltinType::Float:
7309 EncType = "ft";
7310 break;
7311 case BuiltinType::Double:
7312 EncType = "d";
7313 break;
7314 case BuiltinType::LongDouble:
7315 EncType = "ld";
7316 break;
7317 default:
7318 return false;
7319 }
7320 Enc += EncType;
7321 return true;
7322}
7323
7324/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7325static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7326 const CodeGen::CodeGenModule &CGM,
7327 TypeStringCache &TSC) {
7328 Enc += "p(";
7329 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7330 return false;
7331 Enc += ')';
7332 return true;
7333}
7334
7335/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007336static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7337 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007338 const CodeGen::CodeGenModule &CGM,
7339 TypeStringCache &TSC, StringRef NoSizeEnc) {
7340 if (AT->getSizeModifier() != ArrayType::Normal)
7341 return false;
7342 Enc += "a(";
7343 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7344 CAT->getSize().toStringUnsigned(Enc);
7345 else
7346 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7347 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007348 // The Qualifiers should be attached to the type rather than the array.
7349 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007350 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7351 return false;
7352 Enc += ')';
7353 return true;
7354}
7355
7356/// Appends a function encoding to Enc, calling appendType for the return type
7357/// and the arguments.
7358static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7359 const CodeGen::CodeGenModule &CGM,
7360 TypeStringCache &TSC) {
7361 Enc += "f{";
7362 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7363 return false;
7364 Enc += "}(";
7365 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7366 // N.B. we are only interested in the adjusted param types.
7367 auto I = FPT->param_type_begin();
7368 auto E = FPT->param_type_end();
7369 if (I != E) {
7370 do {
7371 if (!appendType(Enc, *I, CGM, TSC))
7372 return false;
7373 ++I;
7374 if (I != E)
7375 Enc += ',';
7376 } while (I != E);
7377 if (FPT->isVariadic())
7378 Enc += ",va";
7379 } else {
7380 if (FPT->isVariadic())
7381 Enc += "va";
7382 else
7383 Enc += '0';
7384 }
7385 }
7386 Enc += ')';
7387 return true;
7388}
7389
7390/// Handles the type's qualifier before dispatching a call to handle specific
7391/// type encodings.
7392static bool appendType(SmallStringEnc &Enc, QualType QType,
7393 const CodeGen::CodeGenModule &CGM,
7394 TypeStringCache &TSC) {
7395
7396 QualType QT = QType.getCanonicalType();
7397
Robert Lytton6adb20f2014-06-05 09:06:21 +00007398 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7399 // The Qualifiers should be attached to the type rather than the array.
7400 // Thus we don't call appendQualifier() here.
7401 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7402
Robert Lytton844aeeb2014-05-02 09:33:20 +00007403 appendQualifier(Enc, QT);
7404
7405 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7406 return appendBuiltinType(Enc, BT);
7407
Robert Lytton844aeeb2014-05-02 09:33:20 +00007408 if (const PointerType *PT = QT->getAs<PointerType>())
7409 return appendPointerType(Enc, PT, CGM, TSC);
7410
7411 if (const EnumType *ET = QT->getAs<EnumType>())
7412 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7413
7414 if (const RecordType *RT = QT->getAsStructureType())
7415 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7416
7417 if (const RecordType *RT = QT->getAsUnionType())
7418 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7419
7420 if (const FunctionType *FT = QT->getAs<FunctionType>())
7421 return appendFunctionType(Enc, FT, CGM, TSC);
7422
7423 return false;
7424}
7425
7426static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7427 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7428 if (!D)
7429 return false;
7430
7431 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7432 if (FD->getLanguageLinkage() != CLanguageLinkage)
7433 return false;
7434 return appendType(Enc, FD->getType(), CGM, TSC);
7435 }
7436
7437 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7438 if (VD->getLanguageLinkage() != CLanguageLinkage)
7439 return false;
7440 QualType QT = VD->getType().getCanonicalType();
7441 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7442 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007443 // The Qualifiers should be attached to the type rather than the array.
7444 // Thus we don't call appendQualifier() here.
7445 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007446 }
7447 return appendType(Enc, QT, CGM, TSC);
7448 }
7449 return false;
7450}
7451
7452
Robert Lytton0e076492013-08-13 09:43:10 +00007453//===----------------------------------------------------------------------===//
7454// Driver code
7455//===----------------------------------------------------------------------===//
7456
Rafael Espindola9f834732014-09-19 01:54:22 +00007457const llvm::Triple &CodeGenModule::getTriple() const {
7458 return getTarget().getTriple();
7459}
7460
7461bool CodeGenModule::supportsCOMDAT() const {
7462 return !getTriple().isOSBinFormatMachO();
7463}
7464
Chris Lattner2b037972010-07-29 02:01:43 +00007465const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007466 if (TheTargetCodeGenInfo)
7467 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007468
John McCallc8e01702013-04-16 22:48:15 +00007469 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007470 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007471 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007472 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007473
Derek Schuff09338a22012-09-06 17:37:28 +00007474 case llvm::Triple::le32:
7475 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007476 case llvm::Triple::mips:
7477 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007478 if (Triple.getOS() == llvm::Triple::NaCl)
7479 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007480 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7481
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007482 case llvm::Triple::mips64:
7483 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007484 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7485
Tim Northover25e8a672014-05-24 12:51:25 +00007486 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007487 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007488 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007489 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007490 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007491
Tim Northover573cbee2014-05-24 12:52:07 +00007492 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007493 }
7494
Dan Gohmanc2853072015-09-03 22:51:53 +00007495 case llvm::Triple::wasm32:
7496 case llvm::Triple::wasm64:
7497 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7498
Daniel Dunbard59655c2009-09-12 00:59:49 +00007499 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007500 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007501 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007502 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007503 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007504 if (Triple.getOS() == llvm::Triple::Win32) {
7505 TheTargetCodeGenInfo =
7506 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7507 return *TheTargetCodeGenInfo;
7508 }
7509
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007510 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Tim Northover5627d392015-10-30 16:30:45 +00007511 StringRef ABIStr = getTarget().getABI();
7512 if (ABIStr == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007513 Kind = ARMABIInfo::APCS;
Tim Northover5627d392015-10-30 16:30:45 +00007514 else if (ABIStr == "aapcs16")
7515 Kind = ARMABIInfo::AAPCS16_VFP;
David Tweed8f676532012-10-25 13:33:01 +00007516 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007517 (CodeGenOpts.FloatABI != "soft" &&
7518 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007519 Kind = ARMABIInfo::AAPCS_VFP;
7520
Derek Schuff71658bd2015-01-29 00:47:04 +00007521 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007522 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007523
John McCallea8d8bb2010-03-11 00:10:12 +00007524 case llvm::Triple::ppc:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00007525 return *(TheTargetCodeGenInfo =
7526 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007527 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007528 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007529 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007530 if (getTarget().getABI() == "elfv2")
7531 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007532 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007533
Ulrich Weigandb7122372014-07-21 00:48:09 +00007534 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007535 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007536 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007537 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007538 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007539 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007540 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007541 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007542 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007543 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007544
Ulrich Weigandb7122372014-07-21 00:48:09 +00007545 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007546 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007547 }
John McCallea8d8bb2010-03-11 00:10:12 +00007548
Peter Collingbournec947aae2012-05-20 23:28:41 +00007549 case llvm::Triple::nvptx:
7550 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007551 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007552
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007553 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007554 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007555
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007556 case llvm::Triple::systemz: {
7557 bool HasVector = getTarget().getABI() == "vector";
7558 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7559 HasVector));
7560 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007561
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007562 case llvm::Triple::tce:
7563 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7564
Eli Friedman33465822011-07-08 23:31:17 +00007565 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007566 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007567 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007568 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007569 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007570
John McCall1fe2a8c2013-06-18 02:46:29 +00007571 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007572 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007573 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Eric Christopher7565e0d2015-05-29 23:09:49 +00007574 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007575 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007576 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007577 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00007578 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7579 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007580 }
Eli Friedman33465822011-07-08 23:31:17 +00007581 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007582
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007583 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007584 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007585 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7586 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007587 X86AVXABILevel::None);
7588
Chris Lattner04dc9572010-08-31 16:44:54 +00007589 switch (Triple.getOS()) {
7590 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007591 return *(TheTargetCodeGenInfo =
7592 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007593 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007594 return *(TheTargetCodeGenInfo =
7595 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007596 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007597 return *(TheTargetCodeGenInfo =
7598 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007599 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007600 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007601 case llvm::Triple::hexagon:
7602 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007603 case llvm::Triple::r600:
7604 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007605 case llvm::Triple::amdgcn:
7606 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007607 case llvm::Triple::sparcv9:
7608 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007609 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007610 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007611 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007612}