blob: 4e2e6f5f49631c4f919ebbc213abd0ad03720849 [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
Anton Korobeynikov244360d2009-06-05 22:08:42 +000064ABIInfo::~ABIInfo() {}
65
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000066static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000067 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
69 if (!RD)
70 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000071 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000072}
73
74static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000075 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000076 const RecordType *RT = T->getAs<RecordType>();
77 if (!RT)
78 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000079 return getRecordArgABI(RT, CXXABI);
80}
81
Reid Klecknerb1be6832014-11-15 01:41:41 +000082/// Pass transparent unions as if they were the type of the first element. Sema
83/// should ensure that all elements of the union have the same "machine type".
84static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
85 if (const RecordType *UT = Ty->getAsUnionType()) {
86 const RecordDecl *UD = UT->getDecl();
87 if (UD->hasAttr<TransparentUnionAttr>()) {
88 assert(!UD->field_empty() && "sema created an empty transparent union");
89 return UD->field_begin()->getType();
90 }
91 }
92 return Ty;
93}
94
Mark Lacey3825e832013-10-06 01:33:34 +000095CGCXXABI &ABIInfo::getCXXABI() const {
96 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000097}
98
Chris Lattner2b037972010-07-29 02:01:43 +000099ASTContext &ABIInfo::getContext() const {
100 return CGT.getContext();
101}
102
103llvm::LLVMContext &ABIInfo::getVMContext() const {
104 return CGT.getLLVMContext();
105}
106
Micah Villmowdd31ca12012-10-08 16:25:52 +0000107const llvm::DataLayout &ABIInfo::getDataLayout() const {
108 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000109}
110
John McCallc8e01702013-04-16 22:48:15 +0000111const TargetInfo &ABIInfo::getTarget() const {
112 return CGT.getTarget();
113}
Chris Lattner2b037972010-07-29 02:01:43 +0000114
Reid Klecknere9f6a712014-10-31 17:10:41 +0000115bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
116 return false;
117}
118
119bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
120 uint64_t Members) const {
121 return false;
122}
123
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000124bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
125 return false;
126}
127
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000128void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000129 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000130 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000131 switch (TheKind) {
132 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000133 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000134 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000135 Ty->print(OS);
136 else
137 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000138 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000139 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000140 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000141 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000142 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000143 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000144 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000145 case InAlloca:
146 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
147 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000148 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000149 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000150 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000151 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000152 break;
153 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000154 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000155 break;
156 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000157 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000158}
159
John McCall7f416cc2015-09-08 08:05:57 +0000160/// Emit va_arg for a platform using the common void* representation,
161/// where arguments are simply emitted in an array of slots on the stack.
162///
163/// This version implements the core direct-value passing rules.
164///
165/// \param SlotSize - The size and alignment of a stack slot.
166/// Each argument will be allocated to a multiple of this number of
167/// slots, and all the slots will be aligned to this value.
168/// \param AllowHigherAlign - The slot alignment is not a cap;
169/// an argument type with an alignment greater than the slot size
170/// will be emitted on a higher-alignment address, potentially
171/// leaving one or more empty slots behind as padding. If this
172/// is false, the returned address might be less-aligned than
173/// DirectAlign.
174static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
175 Address VAListAddr,
176 llvm::Type *DirectTy,
177 CharUnits DirectSize,
178 CharUnits DirectAlign,
179 CharUnits SlotSize,
180 bool AllowHigherAlign) {
181 // Cast the element type to i8* if necessary. Some platforms define
182 // va_list as a struct containing an i8* instead of just an i8*.
183 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
184 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
185
186 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
187
188 // If the CC aligns values higher than the slot size, do so if needed.
189 Address Addr = Address::invalid();
190 if (AllowHigherAlign && DirectAlign > SlotSize) {
191 llvm::Value *PtrAsInt = Ptr;
192 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
193 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
194 llvm::ConstantInt::get(CGF.IntPtrTy, DirectAlign.getQuantity() - 1));
195 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
196 llvm::ConstantInt::get(CGF.IntPtrTy, -DirectAlign.getQuantity()));
197 Addr = Address(CGF.Builder.CreateIntToPtr(PtrAsInt, Ptr->getType(),
198 "argp.cur.aligned"),
199 DirectAlign);
200 } else {
201 Addr = Address(Ptr, SlotSize);
202 }
203
204 // Advance the pointer past the argument, then store that back.
205 CharUnits FullDirectSize = DirectSize.RoundUpToAlignment(SlotSize);
206 llvm::Value *NextPtr =
207 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
208 "argp.next");
209 CGF.Builder.CreateStore(NextPtr, VAListAddr);
210
211 // If the argument is smaller than a slot, and this is a big-endian
212 // target, the argument will be right-adjusted in its slot.
213 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian()) {
214 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
215 }
216
217 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
218 return Addr;
219}
220
221/// Emit va_arg for a platform using the common void* representation,
222/// where arguments are simply emitted in an array of slots on the stack.
223///
224/// \param IsIndirect - Values of this type are passed indirectly.
225/// \param ValueInfo - The size and alignment of this type, generally
226/// computed with getContext().getTypeInfoInChars(ValueTy).
227/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
228/// Each argument will be allocated to a multiple of this number of
229/// slots, and all the slots will be aligned to this value.
230/// \param AllowHigherAlign - The slot alignment is not a cap;
231/// an argument type with an alignment greater than the slot size
232/// will be emitted on a higher-alignment address, potentially
233/// leaving one or more empty slots behind as padding.
234static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
235 QualType ValueTy, bool IsIndirect,
236 std::pair<CharUnits, CharUnits> ValueInfo,
237 CharUnits SlotSizeAndAlign,
238 bool AllowHigherAlign) {
239 // The size and alignment of the value that was passed directly.
240 CharUnits DirectSize, DirectAlign;
241 if (IsIndirect) {
242 DirectSize = CGF.getPointerSize();
243 DirectAlign = CGF.getPointerAlign();
244 } else {
245 DirectSize = ValueInfo.first;
246 DirectAlign = ValueInfo.second;
247 }
248
249 // Cast the address we've calculated to the right type.
250 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
251 if (IsIndirect)
252 DirectTy = DirectTy->getPointerTo(0);
253
254 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
255 DirectSize, DirectAlign,
256 SlotSizeAndAlign,
257 AllowHigherAlign);
258
259 if (IsIndirect) {
260 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
261 }
262
263 return Addr;
264
265}
266
267static Address emitMergePHI(CodeGenFunction &CGF,
268 Address Addr1, llvm::BasicBlock *Block1,
269 Address Addr2, llvm::BasicBlock *Block2,
270 const llvm::Twine &Name = "") {
271 assert(Addr1.getType() == Addr2.getType());
272 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
273 PHI->addIncoming(Addr1.getPointer(), Block1);
274 PHI->addIncoming(Addr2.getPointer(), Block2);
275 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
276 return Address(PHI, Align);
277}
278
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000279TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
280
John McCall3480ef22011-08-30 01:42:09 +0000281// If someone can figure out a general rule for this, that would be great.
282// It's probably just doomed to be platform-dependent, though.
283unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
284 // Verified for:
285 // x86-64 FreeBSD, Linux, Darwin
286 // x86-32 FreeBSD, Linux, Darwin
287 // PowerPC Linux, Darwin
288 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000289 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000290 return 32;
291}
292
John McCalla729c622012-02-17 03:33:10 +0000293bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
294 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000295 // The following conventions are known to require this to be false:
296 // x86_stdcall
297 // MIPS
298 // For everything else, we just prefer false unless we opt out.
299 return false;
300}
301
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000302void
303TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
304 llvm::SmallString<24> &Opt) const {
305 // This assumes the user is passing a library name like "rt" instead of a
306 // filename like "librt.a/so", and that they don't care whether it's static or
307 // dynamic.
308 Opt = "-l";
309 Opt += Lib;
310}
311
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000312static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000313
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000314/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000315/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000316static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
317 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000318 if (FD->isUnnamedBitfield())
319 return true;
320
321 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000322
Eli Friedman0b3f2012011-11-18 03:47:20 +0000323 // Constant arrays of empty records count as empty, strip them off.
324 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000325 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000326 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
327 if (AT->getSize() == 0)
328 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000329 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000330 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000331
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000332 const RecordType *RT = FT->getAs<RecordType>();
333 if (!RT)
334 return false;
335
336 // C++ record fields are never empty, at least in the Itanium ABI.
337 //
338 // FIXME: We should use a predicate for whether this behavior is true in the
339 // current ABI.
340 if (isa<CXXRecordDecl>(RT->getDecl()))
341 return false;
342
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000343 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000344}
345
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000346/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000347/// fields. Note that a structure with a flexible array member is not
348/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000349static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000350 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000351 if (!RT)
352 return 0;
353 const RecordDecl *RD = RT->getDecl();
354 if (RD->hasFlexibleArrayMember())
355 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000356
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000357 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000358 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000359 for (const auto &I : CXXRD->bases())
360 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000361 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000362
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000363 for (const auto *I : RD->fields())
364 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000365 return false;
366 return true;
367}
368
369/// isSingleElementStruct - Determine if a structure is a "single
370/// element struct", i.e. it has exactly one non-empty field or
371/// exactly one field which is itself a single element
372/// struct. Structures with flexible array members are never
373/// considered single element structs.
374///
375/// \return The field declaration for the single non-empty field, if
376/// it exists.
377static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000378 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000379 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000380 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000381
382 const RecordDecl *RD = RT->getDecl();
383 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000384 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000385
Craig Topper8a13c412014-05-21 05:09:00 +0000386 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000387
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000388 // If this is a C++ record, check the bases first.
389 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000390 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000391 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000392 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000393 continue;
394
395 // If we already found an element then this isn't a single-element struct.
396 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000397 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000398
399 // If this is non-empty and not a single element struct, the composite
400 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000401 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000402 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000403 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000404 }
405 }
406
407 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000408 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000409 QualType FT = FD->getType();
410
411 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000412 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000413 continue;
414
415 // If we already found an element then this isn't a single-element
416 // struct.
417 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000418 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000419
420 // Treat single element arrays as the element.
421 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
422 if (AT->getSize().getZExtValue() != 1)
423 break;
424 FT = AT->getElementType();
425 }
426
John McCalla1dee5302010-08-22 10:59:02 +0000427 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000428 Found = FT.getTypePtr();
429 } else {
430 Found = isSingleElementStruct(FT, Context);
431 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000432 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000433 }
434 }
435
Eli Friedmanee945342011-11-18 01:25:50 +0000436 // We don't consider a struct a single-element struct if it has
437 // padding beyond the element type.
438 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000439 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000440
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000441 return Found;
442}
443
444static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000445 // Treat complex types as the element type.
446 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
447 Ty = CTy->getElementType();
448
449 // Check for a type which we know has a simple scalar argument-passing
450 // convention without any padding. (We're specifically looking for 32
451 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000452 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000453 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000454 return false;
455
456 uint64_t Size = Context.getTypeSize(Ty);
457 return Size == 32 || Size == 64;
458}
459
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000460/// canExpandIndirectArgument - Test whether an argument type which is to be
461/// passed indirectly (on the stack) would have the equivalent layout if it was
462/// expanded into separate arguments. If so, we prefer to do the latter to avoid
463/// inhibiting optimizations.
464///
465// FIXME: This predicate is missing many cases, currently it just follows
466// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
467// should probably make this smarter, or better yet make the LLVM backend
468// capable of handling it.
469static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
470 // We can only expand structure types.
471 const RecordType *RT = Ty->getAs<RecordType>();
472 if (!RT)
473 return false;
474
475 // We can only expand (C) structures.
476 //
477 // FIXME: This needs to be generalized to handle classes as well.
478 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000479 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000480 return false;
481
Manman Ren27382782015-04-03 18:10:29 +0000482 // We try to expand CLike CXXRecordDecl.
483 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
484 if (!CXXRD->isCLike())
485 return false;
486 }
487
Eli Friedmane5c85622011-11-18 01:32:26 +0000488 uint64_t Size = 0;
489
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000490 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000491 if (!is32Or64BitBasicType(FD->getType(), Context))
492 return false;
493
494 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
495 // how to expand them yet, and the predicate for telling if a bitfield still
496 // counts as "basic" is more complicated than what we were doing previously.
497 if (FD->isBitField())
498 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000499
500 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000501 }
502
Eli Friedmane5c85622011-11-18 01:32:26 +0000503 // Make sure there are not any holes in the struct.
504 if (Size != Context.getTypeSize(Ty))
505 return false;
506
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000507 return true;
508}
509
510namespace {
511/// DefaultABIInfo - The default implementation for ABI specific
512/// details. This implementation provides information which results in
513/// self-consistent and sensible LLVM IR generation, but does not
514/// conform to any particular ABI.
515class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000516public:
517 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000518
Chris Lattner458b2aa2010-07-29 02:16:43 +0000519 ABIArgInfo classifyReturnType(QualType RetTy) const;
520 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000521
Craig Topper4f12f102014-03-12 06:41:41 +0000522 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000523 if (!getCXXABI().classifyReturnType(FI))
524 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000525 for (auto &I : FI.arguments())
526 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000527 }
528
John McCall7f416cc2015-09-08 08:05:57 +0000529 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
530 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000531};
532
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000533class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
534public:
Chris Lattner2b037972010-07-29 02:01:43 +0000535 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
536 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000537};
538
John McCall7f416cc2015-09-08 08:05:57 +0000539Address DefaultABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
540 QualType Ty) const {
541 return Address::invalid();
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000542}
543
Chris Lattner458b2aa2010-07-29 02:16:43 +0000544ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000545 Ty = useFirstFieldIfTransparentUnion(Ty);
546
547 if (isAggregateTypeForABI(Ty)) {
548 // Records with non-trivial destructors/copy-constructors should not be
549 // passed by value.
550 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000551 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000552
John McCall7f416cc2015-09-08 08:05:57 +0000553 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000554 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000555
Chris Lattner9723d6c2010-03-11 18:19:55 +0000556 // Treat an enum type as its underlying type.
557 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
558 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000559
Chris Lattner9723d6c2010-03-11 18:19:55 +0000560 return (Ty->isPromotableIntegerType() ?
561 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000562}
563
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000564ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
565 if (RetTy->isVoidType())
566 return ABIArgInfo::getIgnore();
567
568 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000569 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000570
571 // Treat an enum type as its underlying type.
572 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
573 RetTy = EnumTy->getDecl()->getIntegerType();
574
575 return (RetTy->isPromotableIntegerType() ?
576 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
577}
578
Derek Schuff09338a22012-09-06 17:37:28 +0000579//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000580// WebAssembly ABI Implementation
581//
582// This is a very simple ABI that relies a lot on DefaultABIInfo.
583//===----------------------------------------------------------------------===//
584
585class WebAssemblyABIInfo final : public DefaultABIInfo {
586public:
587 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
588 : DefaultABIInfo(CGT) {}
589
590private:
591 ABIArgInfo classifyReturnType(QualType RetTy) const;
592 ABIArgInfo classifyArgumentType(QualType Ty) const;
593
594 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
595 // non-virtual, but computeInfo is virtual, so we overload that.
596 void computeInfo(CGFunctionInfo &FI) const override {
597 if (!getCXXABI().classifyReturnType(FI))
598 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
599 for (auto &Arg : FI.arguments())
600 Arg.info = classifyArgumentType(Arg.type);
601 }
602};
603
604class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
605public:
606 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
607 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
608};
609
610/// \brief Classify argument of given type \p Ty.
611ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
612 Ty = useFirstFieldIfTransparentUnion(Ty);
613
614 if (isAggregateTypeForABI(Ty)) {
615 // Records with non-trivial destructors/copy-constructors should not be
616 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000617 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000618 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000619 // Ignore empty structs/unions.
620 if (isEmptyRecord(getContext(), Ty, true))
621 return ABIArgInfo::getIgnore();
622 // Lower single-element structs to just pass a regular value. TODO: We
623 // could do reasonable-size multiple-element structs too, using getExpand(),
624 // though watch out for things like bitfields.
625 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
626 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
John McCall7f416cc2015-09-08 08:05:57 +0000627 return getNaturalAlignIndirect(Ty);
Dan Gohmanc2853072015-09-03 22:51:53 +0000628 }
629
630 // Otherwise just do the default thing.
631 return DefaultABIInfo::classifyArgumentType(Ty);
632}
633
634ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
635 if (isAggregateTypeForABI(RetTy)) {
636 // Records with non-trivial destructors/copy-constructors should not be
637 // returned by value.
638 if (!getRecordArgABI(RetTy, getCXXABI())) {
639 // Ignore empty structs/unions.
640 if (isEmptyRecord(getContext(), RetTy, true))
641 return ABIArgInfo::getIgnore();
642 // Lower single-element structs to just return a regular value. TODO: We
643 // could do reasonable-size multiple-element structs too, using
644 // ABIArgInfo::getDirect().
645 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
646 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
647 }
648 }
649
650 // Otherwise just do the default thing.
651 return DefaultABIInfo::classifyReturnType(RetTy);
652}
653
654//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000655// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000656//
657// This is a simplified version of the x86_32 ABI. Arguments and return values
658// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000659//===----------------------------------------------------------------------===//
660
661class PNaClABIInfo : public ABIInfo {
662 public:
663 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
664
665 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000666 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000667
Craig Topper4f12f102014-03-12 06:41:41 +0000668 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000669 Address EmitVAArg(CodeGenFunction &CGF,
670 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000671};
672
673class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
674 public:
675 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
676 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
677};
678
679void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000680 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000681 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
682
Reid Kleckner40ca9132014-05-13 22:05:45 +0000683 for (auto &I : FI.arguments())
684 I.info = classifyArgumentType(I.type);
685}
Derek Schuff09338a22012-09-06 17:37:28 +0000686
John McCall7f416cc2015-09-08 08:05:57 +0000687Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
688 QualType Ty) const {
689 return Address::invalid();
Derek Schuff09338a22012-09-06 17:37:28 +0000690}
691
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000692/// \brief Classify argument of given type \p Ty.
693ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000694 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000695 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000696 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
697 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000698 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
699 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000700 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000701 } else if (Ty->isFloatingType()) {
702 // Floating-point types don't go inreg.
703 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000704 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000705
706 return (Ty->isPromotableIntegerType() ?
707 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000708}
709
710ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
711 if (RetTy->isVoidType())
712 return ABIArgInfo::getIgnore();
713
Eli Benderskye20dad62013-04-04 22:49:35 +0000714 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000715 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000716 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000717
718 // Treat an enum type as its underlying type.
719 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
720 RetTy = EnumTy->getDecl()->getIntegerType();
721
722 return (RetTy->isPromotableIntegerType() ?
723 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
724}
725
Chad Rosier651c1832013-03-25 21:00:27 +0000726/// IsX86_MMXType - Return true if this is an MMX type.
727bool IsX86_MMXType(llvm::Type *IRType) {
728 // 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 +0000729 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
730 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
731 IRType->getScalarSizeInBits() != 64;
732}
733
Jay Foad7c57be32011-07-11 09:56:20 +0000734static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000735 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000736 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000737 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
738 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
739 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000740 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000741 }
742
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000743 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000744 }
745
746 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000747 return Ty;
748}
749
Reid Kleckner80944df2014-10-31 22:00:51 +0000750/// Returns true if this type can be passed in SSE registers with the
751/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
752static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
753 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
754 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
755 return true;
756 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
757 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
758 // registers specially.
759 unsigned VecSize = Context.getTypeSize(VT);
760 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
761 return true;
762 }
763 return false;
764}
765
766/// Returns true if this aggregate is small enough to be passed in SSE registers
767/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
768static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
769 return NumMembers <= 4;
770}
771
Chris Lattner0cf24192010-06-28 20:05:43 +0000772//===----------------------------------------------------------------------===//
773// X86-32 ABI Implementation
774//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000775
Reid Kleckner661f35b2014-01-18 01:12:41 +0000776/// \brief Similar to llvm::CCState, but for Clang.
777struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000778 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000779
780 unsigned CC;
781 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000782 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000783};
784
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000785/// X86_32ABIInfo - The X86-32 ABI information.
786class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000787 enum Class {
788 Integer,
789 Float
790 };
791
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000792 static const unsigned MinABIStackAlignInBytes = 4;
793
David Chisnallde3a0692009-08-17 23:08:21 +0000794 bool IsDarwinVectorABI;
795 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000796 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000797 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000798
799 static bool isRegisterSize(unsigned Size) {
800 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
801 }
802
Reid Kleckner80944df2014-10-31 22:00:51 +0000803 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
804 // FIXME: Assumes vectorcall is in use.
805 return isX86VectorTypeForVectorCall(getContext(), Ty);
806 }
807
808 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
809 uint64_t NumMembers) const override {
810 // FIXME: Assumes vectorcall is in use.
811 return isX86VectorCallAggregateSmallEnough(NumMembers);
812 }
813
Reid Kleckner40ca9132014-05-13 22:05:45 +0000814 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000815
Daniel Dunbar557893d2010-04-21 19:10:51 +0000816 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
817 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000818 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
819
John McCall7f416cc2015-09-08 08:05:57 +0000820 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000821
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000822 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000823 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000824
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000825 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000826 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000827 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
828 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000829
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000830 /// \brief Rewrite the function info so that all memory arguments use
831 /// inalloca.
832 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
833
834 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000835 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000836 QualType Type) const;
837
Rafael Espindola75419dc2012-07-23 23:30:29 +0000838public:
839
Craig Topper4f12f102014-03-12 06:41:41 +0000840 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000841 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
842 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000843
Chad Rosier651c1832013-03-25 21:00:27 +0000844 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000845 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000846 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000847 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000848};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000849
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000850class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
851public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000852 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000853 bool d, bool p, bool w, unsigned r)
854 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000855
John McCall1fe2a8c2013-06-18 02:46:29 +0000856 static bool isStructReturnInRegABI(
857 const llvm::Triple &Triple, const CodeGenOptions &Opts);
858
Eric Christopher162c91c2015-06-05 22:03:00 +0000859 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000860 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000861
Craig Topper4f12f102014-03-12 06:41:41 +0000862 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000863 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000864 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000865 return 4;
866 }
867
868 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000869 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000870
Jay Foad7c57be32011-07-11 09:56:20 +0000871 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000872 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000873 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000874 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
875 }
876
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000877 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
878 std::string &Constraints,
879 std::vector<llvm::Type *> &ResultRegTypes,
880 std::vector<llvm::Type *> &ResultTruncRegTypes,
881 std::vector<LValue> &ResultRegDests,
882 std::string &AsmString,
883 unsigned NumOutputs) const override;
884
Craig Topper4f12f102014-03-12 06:41:41 +0000885 llvm::Constant *
886 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000887 unsigned Sig = (0xeb << 0) | // jmp rel8
888 (0x06 << 8) | // .+0x08
889 ('F' << 16) |
890 ('T' << 24);
891 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
892 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000893};
894
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000895}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000896
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000897/// Rewrite input constraint references after adding some output constraints.
898/// In the case where there is one output and one input and we add one output,
899/// we need to replace all operand references greater than or equal to 1:
900/// mov $0, $1
901/// mov eax, $1
902/// The result will be:
903/// mov $0, $2
904/// mov eax, $2
905static void rewriteInputConstraintReferences(unsigned FirstIn,
906 unsigned NumNewOuts,
907 std::string &AsmString) {
908 std::string Buf;
909 llvm::raw_string_ostream OS(Buf);
910 size_t Pos = 0;
911 while (Pos < AsmString.size()) {
912 size_t DollarStart = AsmString.find('$', Pos);
913 if (DollarStart == std::string::npos)
914 DollarStart = AsmString.size();
915 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
916 if (DollarEnd == std::string::npos)
917 DollarEnd = AsmString.size();
918 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
919 Pos = DollarEnd;
920 size_t NumDollars = DollarEnd - DollarStart;
921 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
922 // We have an operand reference.
923 size_t DigitStart = Pos;
924 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
925 if (DigitEnd == std::string::npos)
926 DigitEnd = AsmString.size();
927 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
928 unsigned OperandIndex;
929 if (!OperandStr.getAsInteger(10, OperandIndex)) {
930 if (OperandIndex >= FirstIn)
931 OperandIndex += NumNewOuts;
932 OS << OperandIndex;
933 } else {
934 OS << OperandStr;
935 }
936 Pos = DigitEnd;
937 }
938 }
939 AsmString = std::move(OS.str());
940}
941
942/// Add output constraints for EAX:EDX because they are return registers.
943void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
944 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
945 std::vector<llvm::Type *> &ResultRegTypes,
946 std::vector<llvm::Type *> &ResultTruncRegTypes,
947 std::vector<LValue> &ResultRegDests, std::string &AsmString,
948 unsigned NumOutputs) const {
949 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
950
951 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
952 // larger.
953 if (!Constraints.empty())
954 Constraints += ',';
955 if (RetWidth <= 32) {
956 Constraints += "={eax}";
957 ResultRegTypes.push_back(CGF.Int32Ty);
958 } else {
959 // Use the 'A' constraint for EAX:EDX.
960 Constraints += "=A";
961 ResultRegTypes.push_back(CGF.Int64Ty);
962 }
963
964 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
965 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
966 ResultTruncRegTypes.push_back(CoerceTy);
967
968 // Coerce the integer by bitcasting the return slot pointer.
969 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
970 CoerceTy->getPointerTo()));
971 ResultRegDests.push_back(ReturnSlot);
972
973 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
974}
975
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000976/// shouldReturnTypeInRegister - Determine if the given type should be
977/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000978bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
979 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000980 uint64_t Size = Context.getTypeSize(Ty);
981
982 // Type must be register sized.
983 if (!isRegisterSize(Size))
984 return false;
985
986 if (Ty->isVectorType()) {
987 // 64- and 128- bit vectors inside structures are not returned in
988 // registers.
989 if (Size == 64 || Size == 128)
990 return false;
991
992 return true;
993 }
994
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000995 // If this is a builtin, pointer, enum, complex type, member pointer, or
996 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000997 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000998 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000999 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001000 return true;
1001
1002 // Arrays are treated like records.
1003 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001004 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001005
1006 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001007 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001008 if (!RT) return false;
1009
Anders Carlsson40446e82010-01-27 03:25:19 +00001010 // FIXME: Traverse bases here too.
1011
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001012 // Structure types are passed in register if all fields would be
1013 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001014 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001015 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001016 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001017 continue;
1018
1019 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001020 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001021 return false;
1022 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001023 return true;
1024}
1025
John McCall7f416cc2015-09-08 08:05:57 +00001026ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001027 // If the return value is indirect, then the hidden argument is consuming one
1028 // integer register.
1029 if (State.FreeRegs) {
1030 --State.FreeRegs;
John McCall7f416cc2015-09-08 08:05:57 +00001031 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001032 }
John McCall7f416cc2015-09-08 08:05:57 +00001033 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001034}
1035
Eric Christopher7565e0d2015-05-29 23:09:49 +00001036ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1037 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001038 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001039 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001040
Reid Kleckner80944df2014-10-31 22:00:51 +00001041 const Type *Base = nullptr;
1042 uint64_t NumElts = 0;
1043 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1044 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1045 // The LLVM struct type for such an aggregate should lower properly.
1046 return ABIArgInfo::getDirect();
1047 }
1048
Chris Lattner458b2aa2010-07-29 02:16:43 +00001049 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001050 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001051 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001052 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001053
1054 // 128-bit vectors are a special case; they are returned in
1055 // registers and we need to make sure to pick a type the LLVM
1056 // backend will like.
1057 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001058 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001059 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001060
1061 // Always return in register if it fits in a general purpose
1062 // register, or if it is 64 bits and has a single element.
1063 if ((Size == 8 || Size == 16 || Size == 32) ||
1064 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001065 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001066 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001067
John McCall7f416cc2015-09-08 08:05:57 +00001068 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001069 }
1070
1071 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001072 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001073
John McCalla1dee5302010-08-22 10:59:02 +00001074 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001075 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001076 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001077 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001078 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001079 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001080
David Chisnallde3a0692009-08-17 23:08:21 +00001081 // If specified, structs and unions are always indirect.
1082 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001083 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001084
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001085 // Small structures which are register sized are generally returned
1086 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001087 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001088 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001089
1090 // As a special-case, if the struct is a "single-element" struct, and
1091 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001092 // floating-point register. (MSVC does not apply this special case.)
1093 // We apply a similar transformation for pointer types to improve the
1094 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001095 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001096 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001097 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001098 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1099
1100 // FIXME: We should be able to narrow this integer in cases with dead
1101 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001102 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001103 }
1104
John McCall7f416cc2015-09-08 08:05:57 +00001105 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001106 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001107
Chris Lattner458b2aa2010-07-29 02:16:43 +00001108 // Treat an enum type as its underlying type.
1109 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1110 RetTy = EnumTy->getDecl()->getIntegerType();
1111
1112 return (RetTy->isPromotableIntegerType() ?
1113 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001114}
1115
Eli Friedman7919bea2012-06-05 19:40:46 +00001116static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1117 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1118}
1119
Daniel Dunbared23de32010-09-16 20:42:00 +00001120static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1121 const RecordType *RT = Ty->getAs<RecordType>();
1122 if (!RT)
1123 return 0;
1124 const RecordDecl *RD = RT->getDecl();
1125
1126 // If this is a C++ record, check the bases first.
1127 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001128 for (const auto &I : CXXRD->bases())
1129 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001130 return false;
1131
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001132 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001133 QualType FT = i->getType();
1134
Eli Friedman7919bea2012-06-05 19:40:46 +00001135 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001136 return true;
1137
1138 if (isRecordWithSSEVectorType(Context, FT))
1139 return true;
1140 }
1141
1142 return false;
1143}
1144
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001145unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1146 unsigned Align) const {
1147 // Otherwise, if the alignment is less than or equal to the minimum ABI
1148 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001149 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001150 return 0; // Use default alignment.
1151
1152 // On non-Darwin, the stack type alignment is always 4.
1153 if (!IsDarwinVectorABI) {
1154 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001155 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001156 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001157
Daniel Dunbared23de32010-09-16 20:42:00 +00001158 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001159 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1160 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001161 return 16;
1162
1163 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001164}
1165
Rafael Espindola703c47f2012-10-19 05:04:37 +00001166ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001167 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001168 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001169 if (State.FreeRegs) {
1170 --State.FreeRegs; // Non-byval indirects just use one pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001171 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001172 }
John McCall7f416cc2015-09-08 08:05:57 +00001173 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001174 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001175
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001176 // Compute the byval alignment.
1177 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1178 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1179 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001180 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001181
1182 // If the stack alignment is less than the type alignment, realign the
1183 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001184 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001185 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1186 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001187}
1188
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001189X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1190 const Type *T = isSingleElementStruct(Ty, getContext());
1191 if (!T)
1192 T = Ty.getTypePtr();
1193
1194 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1195 BuiltinType::Kind K = BT->getKind();
1196 if (K == BuiltinType::Float || K == BuiltinType::Double)
1197 return Float;
1198 }
1199 return Integer;
1200}
1201
Reid Kleckner661f35b2014-01-18 01:12:41 +00001202bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
1203 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +00001204 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001205 Class C = classify(Ty);
1206 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +00001207 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001208
Rafael Espindola077dd592012-10-24 01:58:58 +00001209 unsigned Size = getContext().getTypeSize(Ty);
1210 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001211
1212 if (SizeInRegs == 0)
1213 return false;
1214
Reid Kleckner661f35b2014-01-18 01:12:41 +00001215 if (SizeInRegs > State.FreeRegs) {
1216 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001217 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001218 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001219
Reid Kleckner661f35b2014-01-18 01:12:41 +00001220 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001221
Reid Kleckner80944df2014-10-31 22:00:51 +00001222 if (State.CC == llvm::CallingConv::X86_FastCall ||
1223 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001224 if (Size > 32)
1225 return false;
1226
1227 if (Ty->isIntegralOrEnumerationType())
1228 return true;
1229
1230 if (Ty->isPointerType())
1231 return true;
1232
1233 if (Ty->isReferenceType())
1234 return true;
1235
Reid Kleckner661f35b2014-01-18 01:12:41 +00001236 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001237 NeedsPadding = true;
1238
Rafael Espindola077dd592012-10-24 01:58:58 +00001239 return false;
1240 }
1241
Rafael Espindola703c47f2012-10-19 05:04:37 +00001242 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001243}
1244
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001245ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1246 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001247 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001248
Reid Klecknerb1be6832014-11-15 01:41:41 +00001249 Ty = useFirstFieldIfTransparentUnion(Ty);
1250
Reid Kleckner80944df2014-10-31 22:00:51 +00001251 // Check with the C++ ABI first.
1252 const RecordType *RT = Ty->getAs<RecordType>();
1253 if (RT) {
1254 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1255 if (RAA == CGCXXABI::RAA_Indirect) {
1256 return getIndirectResult(Ty, false, State);
1257 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1258 // The field index doesn't matter, we'll fix it up later.
1259 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1260 }
1261 }
1262
1263 // vectorcall adds the concept of a homogenous vector aggregate, similar
1264 // to other targets.
1265 const Type *Base = nullptr;
1266 uint64_t NumElts = 0;
1267 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1268 isHomogeneousAggregate(Ty, Base, NumElts)) {
1269 if (State.FreeSSERegs >= NumElts) {
1270 State.FreeSSERegs -= NumElts;
1271 if (Ty->isBuiltinType() || Ty->isVectorType())
1272 return ABIArgInfo::getDirect();
1273 return ABIArgInfo::getExpand();
1274 }
1275 return getIndirectResult(Ty, /*ByVal=*/false, State);
1276 }
1277
1278 if (isAggregateTypeForABI(Ty)) {
1279 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001280 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001281 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001282 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001283
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001284 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001285 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001286 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001287 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001288
Eli Friedman9f061a32011-11-18 00:28:11 +00001289 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001290 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001291 return ABIArgInfo::getIgnore();
1292
Rafael Espindolafad28de2012-10-24 01:59:00 +00001293 llvm::LLVMContext &LLVMContext = getVMContext();
1294 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1295 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001296 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001297 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001298 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001299 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1300 return ABIArgInfo::getDirectInReg(Result);
1301 }
Craig Topper8a13c412014-05-21 05:09:00 +00001302 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001303
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001304 // Expand small (<= 128-bit) record types when we know that the stack layout
1305 // of those arguments will match the struct. This is important because the
1306 // LLVM backend isn't smart enough to remove byval, which inhibits many
1307 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001308 if (getContext().getTypeSize(Ty) <= 4*32 &&
1309 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001310 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001311 State.CC == llvm::CallingConv::X86_FastCall ||
1312 State.CC == llvm::CallingConv::X86_VectorCall,
1313 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001314
Reid Kleckner661f35b2014-01-18 01:12:41 +00001315 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001316 }
1317
Chris Lattnerd774ae92010-08-26 20:05:13 +00001318 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001319 // On Darwin, some vectors are passed in memory, we handle this by passing
1320 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001321 if (IsDarwinVectorABI) {
1322 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001323 if ((Size == 8 || Size == 16 || Size == 32) ||
1324 (Size == 64 && VT->getNumElements() == 1))
1325 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1326 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001327 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001328
Chad Rosier651c1832013-03-25 21:00:27 +00001329 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1330 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001331
Chris Lattnerd774ae92010-08-26 20:05:13 +00001332 return ABIArgInfo::getDirect();
1333 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001334
1335
Chris Lattner458b2aa2010-07-29 02:16:43 +00001336 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1337 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001338
Rafael Espindolafad28de2012-10-24 01:59:00 +00001339 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001340 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001341
1342 if (Ty->isPromotableIntegerType()) {
1343 if (InReg)
1344 return ABIArgInfo::getExtendInReg();
1345 return ABIArgInfo::getExtend();
1346 }
1347 if (InReg)
1348 return ABIArgInfo::getDirectInReg();
1349 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001350}
1351
Rafael Espindolaa6472962012-07-24 00:01:07 +00001352void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001353 CCState State(FI.getCallingConvention());
1354 if (State.CC == llvm::CallingConv::X86_FastCall)
1355 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001356 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1357 State.FreeRegs = 2;
1358 State.FreeSSERegs = 6;
1359 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001360 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001361 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001362 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001363
Reid Kleckner677539d2014-07-10 01:58:55 +00001364 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001365 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001366 } else if (FI.getReturnInfo().isIndirect()) {
1367 // The C++ ABI is not aware of register usage, so we have to check if the
1368 // return value was sret and put it in a register ourselves if appropriate.
1369 if (State.FreeRegs) {
1370 --State.FreeRegs; // The sret parameter consumes a register.
1371 FI.getReturnInfo().setInReg(true);
1372 }
1373 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001374
Peter Collingbournef7706832014-12-12 23:41:25 +00001375 // The chain argument effectively gives us another free register.
1376 if (FI.isChainCall())
1377 ++State.FreeRegs;
1378
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001379 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001380 for (auto &I : FI.arguments()) {
1381 I.info = classifyArgumentType(I.type, State);
1382 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001383 }
1384
1385 // If we needed to use inalloca for any argument, do a second pass and rewrite
1386 // all the memory arguments to use inalloca.
1387 if (UsedInAlloca)
1388 rewriteWithInAlloca(FI);
1389}
1390
1391void
1392X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001393 CharUnits &StackOffset, ABIArgInfo &Info,
1394 QualType Type) const {
1395 // Arguments are always 4-byte-aligned.
1396 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1397
1398 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001399 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1400 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001401 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001402
John McCall7f416cc2015-09-08 08:05:57 +00001403 // Insert padding bytes to respect alignment.
1404 CharUnits FieldEnd = StackOffset;
1405 StackOffset = FieldEnd.RoundUpToAlignment(FieldAlign);
1406 if (StackOffset != FieldEnd) {
1407 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001408 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001409 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001410 FrameFields.push_back(Ty);
1411 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001412}
1413
Reid Kleckner852361d2014-07-26 00:12:26 +00001414static bool isArgInAlloca(const ABIArgInfo &Info) {
1415 // Leave ignored and inreg arguments alone.
1416 switch (Info.getKind()) {
1417 case ABIArgInfo::InAlloca:
1418 return true;
1419 case ABIArgInfo::Indirect:
1420 assert(Info.getIndirectByVal());
1421 return true;
1422 case ABIArgInfo::Ignore:
1423 return false;
1424 case ABIArgInfo::Direct:
1425 case ABIArgInfo::Extend:
1426 case ABIArgInfo::Expand:
1427 if (Info.getInReg())
1428 return false;
1429 return true;
1430 }
1431 llvm_unreachable("invalid enum");
1432}
1433
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001434void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1435 assert(IsWin32StructABI && "inalloca only supported on win32");
1436
1437 // Build a packed struct type for all of the arguments in memory.
1438 SmallVector<llvm::Type *, 6> FrameFields;
1439
John McCall7f416cc2015-09-08 08:05:57 +00001440 // The stack alignment is always 4.
1441 CharUnits StackAlign = CharUnits::fromQuantity(4);
1442
1443 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001444 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1445
1446 // Put 'this' into the struct before 'sret', if necessary.
1447 bool IsThisCall =
1448 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1449 ABIArgInfo &Ret = FI.getReturnInfo();
1450 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1451 isArgInAlloca(I->info)) {
1452 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1453 ++I;
1454 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001455
1456 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001457 if (Ret.isIndirect() && !Ret.getInReg()) {
1458 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1459 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001460 // On Windows, the hidden sret parameter is always returned in eax.
1461 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001462 }
1463
1464 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001465 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001466 ++I;
1467
1468 // Put arguments passed in memory into the struct.
1469 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001470 if (isArgInAlloca(I->info))
1471 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001472 }
1473
1474 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001475 /*isPacked=*/true),
1476 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001477}
1478
John McCall7f416cc2015-09-08 08:05:57 +00001479Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1480 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001481
John McCall7f416cc2015-09-08 08:05:57 +00001482 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001483
John McCall7f416cc2015-09-08 08:05:57 +00001484 // x86-32 changes the alignment of certain arguments on the stack.
1485 //
1486 // Just messing with TypeInfo like this works because we never pass
1487 // anything indirectly.
1488 TypeInfo.second = CharUnits::fromQuantity(
1489 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001490
John McCall7f416cc2015-09-08 08:05:57 +00001491 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1492 TypeInfo, CharUnits::fromQuantity(4),
1493 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001494}
1495
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001496bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1497 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1498 assert(Triple.getArch() == llvm::Triple::x86);
1499
1500 switch (Opts.getStructReturnConvention()) {
1501 case CodeGenOptions::SRCK_Default:
1502 break;
1503 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1504 return false;
1505 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1506 return true;
1507 }
1508
1509 if (Triple.isOSDarwin())
1510 return true;
1511
1512 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001513 case llvm::Triple::DragonFly:
1514 case llvm::Triple::FreeBSD:
1515 case llvm::Triple::OpenBSD:
1516 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001517 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001518 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001519 default:
1520 return false;
1521 }
1522}
1523
Eric Christopher162c91c2015-06-05 22:03:00 +00001524void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001525 llvm::GlobalValue *GV,
1526 CodeGen::CodeGenModule &CGM) const {
1527 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1528 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1529 // Get the LLVM function.
1530 llvm::Function *Fn = cast<llvm::Function>(GV);
1531
1532 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001533 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001534 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001535 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1536 llvm::AttributeSet::get(CGM.getLLVMContext(),
1537 llvm::AttributeSet::FunctionIndex,
1538 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001539 }
1540 }
1541}
1542
John McCallbeec5a02010-03-06 00:35:14 +00001543bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1544 CodeGen::CodeGenFunction &CGF,
1545 llvm::Value *Address) const {
1546 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001547
Chris Lattnerece04092012-02-07 00:39:47 +00001548 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001549
John McCallbeec5a02010-03-06 00:35:14 +00001550 // 0-7 are the eight integer registers; the order is different
1551 // on Darwin (for EH), but the range is the same.
1552 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001553 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001554
John McCallc8e01702013-04-16 22:48:15 +00001555 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001556 // 12-16 are st(0..4). Not sure why we stop at 4.
1557 // These have size 16, which is sizeof(long double) on
1558 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001559 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001560 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001561
John McCallbeec5a02010-03-06 00:35:14 +00001562 } else {
1563 // 9 is %eflags, which doesn't get a size on Darwin for some
1564 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001565 Builder.CreateAlignedStore(
1566 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1567 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001568
1569 // 11-16 are st(0..5). Not sure why we stop at 5.
1570 // These have size 12, which is sizeof(long double) on
1571 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001572 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001573 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1574 }
John McCallbeec5a02010-03-06 00:35:14 +00001575
1576 return false;
1577}
1578
Chris Lattner0cf24192010-06-28 20:05:43 +00001579//===----------------------------------------------------------------------===//
1580// X86-64 ABI Implementation
1581//===----------------------------------------------------------------------===//
1582
1583
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001584namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001585/// The AVX ABI level for X86 targets.
1586enum class X86AVXABILevel {
1587 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001588 AVX,
1589 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001590};
1591
1592/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1593static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1594 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001595 case X86AVXABILevel::AVX512:
1596 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001597 case X86AVXABILevel::AVX:
1598 return 256;
1599 case X86AVXABILevel::None:
1600 return 128;
1601 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001602 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001603}
1604
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001605/// X86_64ABIInfo - The X86_64 ABI information.
1606class X86_64ABIInfo : public ABIInfo {
1607 enum Class {
1608 Integer = 0,
1609 SSE,
1610 SSEUp,
1611 X87,
1612 X87Up,
1613 ComplexX87,
1614 NoClass,
1615 Memory
1616 };
1617
1618 /// merge - Implement the X86_64 ABI merging algorithm.
1619 ///
1620 /// Merge an accumulating classification \arg Accum with a field
1621 /// classification \arg Field.
1622 ///
1623 /// \param Accum - The accumulating classification. This should
1624 /// always be either NoClass or the result of a previous merge
1625 /// call. In addition, this should never be Memory (the caller
1626 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001627 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001628
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001629 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1630 ///
1631 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1632 /// final MEMORY or SSE classes when necessary.
1633 ///
1634 /// \param AggregateSize - The size of the current aggregate in
1635 /// the classification process.
1636 ///
1637 /// \param Lo - The classification for the parts of the type
1638 /// residing in the low word of the containing object.
1639 ///
1640 /// \param Hi - The classification for the parts of the type
1641 /// residing in the higher words of the containing object.
1642 ///
1643 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1644
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001645 /// classify - Determine the x86_64 register classes in which the
1646 /// given type T should be passed.
1647 ///
1648 /// \param Lo - The classification for the parts of the type
1649 /// residing in the low word of the containing object.
1650 ///
1651 /// \param Hi - The classification for the parts of the type
1652 /// residing in the high word of the containing object.
1653 ///
1654 /// \param OffsetBase - The bit offset of this type in the
1655 /// containing object. Some parameters are classified different
1656 /// depending on whether they straddle an eightbyte boundary.
1657 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001658 /// \param isNamedArg - Whether the argument in question is a "named"
1659 /// argument, as used in AMD64-ABI 3.5.7.
1660 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001661 /// If a word is unused its result will be NoClass; if a type should
1662 /// be passed in Memory then at least the classification of \arg Lo
1663 /// will be Memory.
1664 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001665 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001666 ///
1667 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1668 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001669 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1670 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001671
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001672 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001673 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1674 unsigned IROffset, QualType SourceTy,
1675 unsigned SourceOffset) const;
1676 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1677 unsigned IROffset, QualType SourceTy,
1678 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001679
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001680 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001681 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001682 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001683
1684 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001685 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001686 ///
1687 /// \param freeIntRegs - The number of free integer registers remaining
1688 /// available.
1689 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001690
Chris Lattner458b2aa2010-07-29 02:16:43 +00001691 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001692
Bill Wendling5cd41c42010-10-18 03:41:31 +00001693 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001694 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001695 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001696 unsigned &neededSSE,
1697 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001698
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001699 bool IsIllegalVectorType(QualType Ty) const;
1700
John McCalle0fda732011-04-21 01:20:55 +00001701 /// The 0.98 ABI revision clarified a lot of ambiguities,
1702 /// unfortunately in ways that were not always consistent with
1703 /// certain previous compilers. In particular, platforms which
1704 /// required strict binary compatibility with older versions of GCC
1705 /// may need to exempt themselves.
1706 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001707 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001708 }
1709
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001710 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001711 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1712 // 64-bit hardware.
1713 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001714
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001715public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001716 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1717 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001718 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001719 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001720
John McCalla729c622012-02-17 03:33:10 +00001721 bool isPassedUsingAVXType(QualType type) const {
1722 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001723 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001724 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1725 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001726 if (info.isDirect()) {
1727 llvm::Type *ty = info.getCoerceToType();
1728 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1729 return (vectorTy->getBitWidth() > 128);
1730 }
1731 return false;
1732 }
1733
Craig Topper4f12f102014-03-12 06:41:41 +00001734 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001735
John McCall7f416cc2015-09-08 08:05:57 +00001736 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1737 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001738
1739 bool has64BitPointers() const {
1740 return Has64BitPointers;
1741 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001742};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001743
Chris Lattner04dc9572010-08-31 16:44:54 +00001744/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001745class WinX86_64ABIInfo : public ABIInfo {
1746
Reid Kleckner80944df2014-10-31 22:00:51 +00001747 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1748 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001749
Chris Lattner04dc9572010-08-31 16:44:54 +00001750public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001751 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1752
Craig Topper4f12f102014-03-12 06:41:41 +00001753 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001754
John McCall7f416cc2015-09-08 08:05:57 +00001755 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1756 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001757
1758 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1759 // FIXME: Assumes vectorcall is in use.
1760 return isX86VectorTypeForVectorCall(getContext(), Ty);
1761 }
1762
1763 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1764 uint64_t NumMembers) const override {
1765 // FIXME: Assumes vectorcall is in use.
1766 return isX86VectorCallAggregateSmallEnough(NumMembers);
1767 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001768};
1769
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001770class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1771public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001772 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001773 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001774
John McCalla729c622012-02-17 03:33:10 +00001775 const X86_64ABIInfo &getABIInfo() const {
1776 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1777 }
1778
Craig Topper4f12f102014-03-12 06:41:41 +00001779 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001780 return 7;
1781 }
1782
1783 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001784 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001785 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001786
John McCall943fae92010-05-27 06:19:26 +00001787 // 0-15 are the 16 integer registers.
1788 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001789 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001790 return false;
1791 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001792
Jay Foad7c57be32011-07-11 09:56:20 +00001793 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001794 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001795 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001796 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1797 }
1798
John McCalla729c622012-02-17 03:33:10 +00001799 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001800 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001801 // The default CC on x86-64 sets %al to the number of SSA
1802 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001803 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001804 // that when AVX types are involved: the ABI explicitly states it is
1805 // undefined, and it doesn't work in practice because of how the ABI
1806 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001807 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001808 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001809 for (CallArgList::const_iterator
1810 it = args.begin(), ie = args.end(); it != ie; ++it) {
1811 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1812 HasAVXType = true;
1813 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001814 }
1815 }
John McCalla729c622012-02-17 03:33:10 +00001816
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001817 if (!HasAVXType)
1818 return true;
1819 }
John McCallcbc038a2011-09-21 08:08:30 +00001820
John McCalla729c622012-02-17 03:33:10 +00001821 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001822 }
1823
Craig Topper4f12f102014-03-12 06:41:41 +00001824 llvm::Constant *
1825 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001826 unsigned Sig;
1827 if (getABIInfo().has64BitPointers())
1828 Sig = (0xeb << 0) | // jmp rel8
1829 (0x0a << 8) | // .+0x0c
1830 ('F' << 16) |
1831 ('T' << 24);
1832 else
1833 Sig = (0xeb << 0) | // jmp rel8
1834 (0x06 << 8) | // .+0x08
1835 ('F' << 16) |
1836 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001837 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1838 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001839};
1840
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001841class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1842public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001843 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1844 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001845
1846 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001847 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001848 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00001849 // If the argument contains a space, enclose it in quotes.
1850 if (Lib.find(" ") != StringRef::npos)
1851 Opt += "\"" + Lib.str() + "\"";
1852 else
1853 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001854 }
1855};
1856
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001857static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001858 // If the argument does not end in .lib, automatically add the suffix.
1859 // If the argument contains a space, enclose it in quotes.
1860 // This matches the behavior of MSVC.
1861 bool Quote = (Lib.find(" ") != StringRef::npos);
1862 std::string ArgStr = Quote ? "\"" : "";
1863 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001864 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001865 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001866 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001867 return ArgStr;
1868}
1869
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001870class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1871public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001872 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1873 bool d, bool p, bool w, unsigned RegParms)
1874 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001875
Eric Christopher162c91c2015-06-05 22:03:00 +00001876 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001877 CodeGen::CodeGenModule &CGM) const override;
1878
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001879 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001880 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001881 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001882 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001883 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001884
1885 void getDetectMismatchOption(llvm::StringRef Name,
1886 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001887 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001888 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001889 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001890};
1891
Hans Wennborg77dc2362015-01-20 19:45:50 +00001892static void addStackProbeSizeTargetAttribute(const Decl *D,
1893 llvm::GlobalValue *GV,
1894 CodeGen::CodeGenModule &CGM) {
1895 if (isa<FunctionDecl>(D)) {
1896 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1897 llvm::Function *Fn = cast<llvm::Function>(GV);
1898
Eric Christopher7565e0d2015-05-29 23:09:49 +00001899 Fn->addFnAttr("stack-probe-size",
1900 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00001901 }
1902 }
1903}
1904
Eric Christopher162c91c2015-06-05 22:03:00 +00001905void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001906 llvm::GlobalValue *GV,
1907 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001908 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001909
1910 addStackProbeSizeTargetAttribute(D, GV, CGM);
1911}
1912
Chris Lattner04dc9572010-08-31 16:44:54 +00001913class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1914public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001915 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1916 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001917 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001918
Eric Christopher162c91c2015-06-05 22:03:00 +00001919 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001920 CodeGen::CodeGenModule &CGM) const override;
1921
Craig Topper4f12f102014-03-12 06:41:41 +00001922 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001923 return 7;
1924 }
1925
1926 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001927 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001928 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001929
Chris Lattner04dc9572010-08-31 16:44:54 +00001930 // 0-15 are the 16 integer registers.
1931 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001932 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001933 return false;
1934 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001935
1936 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001937 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001938 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001939 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001940 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001941
1942 void getDetectMismatchOption(llvm::StringRef Name,
1943 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001944 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001945 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001946 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001947};
1948
Eric Christopher162c91c2015-06-05 22:03:00 +00001949void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001950 llvm::GlobalValue *GV,
1951 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001952 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001953
1954 addStackProbeSizeTargetAttribute(D, GV, CGM);
1955}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001956}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001957
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001958void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1959 Class &Hi) const {
1960 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1961 //
1962 // (a) If one of the classes is Memory, the whole argument is passed in
1963 // memory.
1964 //
1965 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1966 // memory.
1967 //
1968 // (c) If the size of the aggregate exceeds two eightbytes and the first
1969 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1970 // argument is passed in memory. NOTE: This is necessary to keep the
1971 // ABI working for processors that don't support the __m256 type.
1972 //
1973 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1974 //
1975 // Some of these are enforced by the merging logic. Others can arise
1976 // only with unions; for example:
1977 // union { _Complex double; unsigned; }
1978 //
1979 // Note that clauses (b) and (c) were added in 0.98.
1980 //
1981 if (Hi == Memory)
1982 Lo = Memory;
1983 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1984 Lo = Memory;
1985 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1986 Lo = Memory;
1987 if (Hi == SSEUp && Lo != SSE)
1988 Hi = SSE;
1989}
1990
Chris Lattnerd776fb12010-06-28 21:43:59 +00001991X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001992 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1993 // classified recursively so that always two fields are
1994 // considered. The resulting class is calculated according to
1995 // the classes of the fields in the eightbyte:
1996 //
1997 // (a) If both classes are equal, this is the resulting class.
1998 //
1999 // (b) If one of the classes is NO_CLASS, the resulting class is
2000 // the other class.
2001 //
2002 // (c) If one of the classes is MEMORY, the result is the MEMORY
2003 // class.
2004 //
2005 // (d) If one of the classes is INTEGER, the result is the
2006 // INTEGER.
2007 //
2008 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2009 // MEMORY is used as class.
2010 //
2011 // (f) Otherwise class SSE is used.
2012
2013 // Accum should never be memory (we should have returned) or
2014 // ComplexX87 (because this cannot be passed in a structure).
2015 assert((Accum != Memory && Accum != ComplexX87) &&
2016 "Invalid accumulated classification during merge.");
2017 if (Accum == Field || Field == NoClass)
2018 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002019 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002020 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002021 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002022 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002023 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002024 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002025 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2026 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002027 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002028 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002029}
2030
Chris Lattner5c740f12010-06-30 19:14:05 +00002031void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002032 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002033 // FIXME: This code can be simplified by introducing a simple value class for
2034 // Class pairs with appropriate constructor methods for the various
2035 // situations.
2036
2037 // FIXME: Some of the split computations are wrong; unaligned vectors
2038 // shouldn't be passed in registers for example, so there is no chance they
2039 // can straddle an eightbyte. Verify & simplify.
2040
2041 Lo = Hi = NoClass;
2042
2043 Class &Current = OffsetBase < 64 ? Lo : Hi;
2044 Current = Memory;
2045
John McCall9dd450b2009-09-21 23:43:11 +00002046 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002047 BuiltinType::Kind k = BT->getKind();
2048
2049 if (k == BuiltinType::Void) {
2050 Current = NoClass;
2051 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2052 Lo = Integer;
2053 Hi = Integer;
2054 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2055 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002056 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002057 Current = SSE;
2058 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002059 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2060 if (LDF == &llvm::APFloat::IEEEquad) {
2061 Lo = SSE;
2062 Hi = SSEUp;
2063 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2064 Lo = X87;
2065 Hi = X87Up;
2066 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2067 Current = SSE;
2068 } else
2069 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002070 }
2071 // FIXME: _Decimal32 and _Decimal64 are SSE.
2072 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002073 return;
2074 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002075
Chris Lattnerd776fb12010-06-28 21:43:59 +00002076 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002077 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002078 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002079 return;
2080 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002081
Chris Lattnerd776fb12010-06-28 21:43:59 +00002082 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002083 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002084 return;
2085 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002086
Chris Lattnerd776fb12010-06-28 21:43:59 +00002087 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002088 if (Ty->isMemberFunctionPointerType()) {
2089 if (Has64BitPointers) {
2090 // If Has64BitPointers, this is an {i64, i64}, so classify both
2091 // Lo and Hi now.
2092 Lo = Hi = Integer;
2093 } else {
2094 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2095 // straddles an eightbyte boundary, Hi should be classified as well.
2096 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2097 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2098 if (EB_FuncPtr != EB_ThisAdj) {
2099 Lo = Hi = Integer;
2100 } else {
2101 Current = Integer;
2102 }
2103 }
2104 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002105 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002106 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002107 return;
2108 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002109
Chris Lattnerd776fb12010-06-28 21:43:59 +00002110 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002111 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002112 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2113 // gcc passes the following as integer:
2114 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2115 // 2 bytes - <2 x char>, <1 x short>
2116 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002117 Current = Integer;
2118
2119 // If this type crosses an eightbyte boundary, it should be
2120 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002121 uint64_t EB_Lo = (OffsetBase) / 64;
2122 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2123 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002124 Hi = Lo;
2125 } else if (Size == 64) {
2126 // gcc passes <1 x double> in memory. :(
2127 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
2128 return;
2129
2130 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00002131 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00002132 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2133 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
2134 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002135 Current = Integer;
2136 else
2137 Current = SSE;
2138
2139 // If this type crosses an eightbyte boundary, it should be
2140 // split.
2141 if (OffsetBase && OffsetBase != 64)
2142 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002143 } else if (Size == 128 ||
2144 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002145 // Arguments of 256-bits are split into four eightbyte chunks. The
2146 // least significant one belongs to class SSE and all the others to class
2147 // SSEUP. The original Lo and Hi design considers that types can't be
2148 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2149 // This design isn't correct for 256-bits, but since there're no cases
2150 // where the upper parts would need to be inspected, avoid adding
2151 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002152 //
2153 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2154 // registers if they are "named", i.e. not part of the "..." of a
2155 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002156 //
2157 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2158 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002159 Lo = SSE;
2160 Hi = SSEUp;
2161 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002162 return;
2163 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002164
Chris Lattnerd776fb12010-06-28 21:43:59 +00002165 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002166 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002167
Chris Lattner2b037972010-07-29 02:01:43 +00002168 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002169 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002170 if (Size <= 64)
2171 Current = Integer;
2172 else if (Size <= 128)
2173 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002174 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002175 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002176 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002177 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002178 } else if (ET == getContext().LongDoubleTy) {
2179 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2180 if (LDF == &llvm::APFloat::IEEEquad)
2181 Current = Memory;
2182 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2183 Current = ComplexX87;
2184 else if (LDF == &llvm::APFloat::IEEEdouble)
2185 Lo = Hi = SSE;
2186 else
2187 llvm_unreachable("unexpected long double representation!");
2188 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002189
2190 // If this complex type crosses an eightbyte boundary then it
2191 // should be split.
2192 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002193 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002194 if (Hi == NoClass && EB_Real != EB_Imag)
2195 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002196
Chris Lattnerd776fb12010-06-28 21:43:59 +00002197 return;
2198 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002199
Chris Lattner2b037972010-07-29 02:01:43 +00002200 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002201 // Arrays are treated like structures.
2202
Chris Lattner2b037972010-07-29 02:01:43 +00002203 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002204
2205 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002206 // than four eightbytes, ..., it has class MEMORY.
2207 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002208 return;
2209
2210 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2211 // fields, it has class MEMORY.
2212 //
2213 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002214 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002215 return;
2216
2217 // Otherwise implement simplified merge. We could be smarter about
2218 // this, but it isn't worth it and would be harder to verify.
2219 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002220 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002221 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002222
2223 // The only case a 256-bit wide vector could be used is when the array
2224 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2225 // to work for sizes wider than 128, early check and fallback to memory.
2226 if (Size > 128 && EltSize != 256)
2227 return;
2228
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002229 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2230 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002231 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002232 Lo = merge(Lo, FieldLo);
2233 Hi = merge(Hi, FieldHi);
2234 if (Lo == Memory || Hi == Memory)
2235 break;
2236 }
2237
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002238 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002239 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002240 return;
2241 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002242
Chris Lattnerd776fb12010-06-28 21:43:59 +00002243 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002244 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002245
2246 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002247 // than four eightbytes, ..., it has class MEMORY.
2248 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002249 return;
2250
Anders Carlsson20759ad2009-09-16 15:53:40 +00002251 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2252 // copy constructor or a non-trivial destructor, it is passed by invisible
2253 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002254 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002255 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002256
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002257 const RecordDecl *RD = RT->getDecl();
2258
2259 // Assume variable sized types are passed in memory.
2260 if (RD->hasFlexibleArrayMember())
2261 return;
2262
Chris Lattner2b037972010-07-29 02:01:43 +00002263 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002264
2265 // Reset Lo class, this will be recomputed.
2266 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002267
2268 // If this is a C++ record, classify the bases first.
2269 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002270 for (const auto &I : CXXRD->bases()) {
2271 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002272 "Unexpected base class!");
2273 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002274 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002275
2276 // Classify this field.
2277 //
2278 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2279 // single eightbyte, each is classified separately. Each eightbyte gets
2280 // initialized to class NO_CLASS.
2281 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002282 uint64_t Offset =
2283 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002284 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002285 Lo = merge(Lo, FieldLo);
2286 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002287 if (Lo == Memory || Hi == Memory) {
2288 postMerge(Size, Lo, Hi);
2289 return;
2290 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002291 }
2292 }
2293
2294 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002295 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002296 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002297 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002298 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2299 bool BitField = i->isBitField();
2300
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002301 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2302 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002303 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002304 // The only case a 256-bit wide vector could be used is when the struct
2305 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2306 // to work for sizes wider than 128, early check and fallback to memory.
2307 //
2308 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2309 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002310 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002311 return;
2312 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002313 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002314 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002315 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002316 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002317 return;
2318 }
2319
2320 // Classify this field.
2321 //
2322 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2323 // exceeds a single eightbyte, each is classified
2324 // separately. Each eightbyte gets initialized to class
2325 // NO_CLASS.
2326 Class FieldLo, FieldHi;
2327
2328 // Bit-fields require special handling, they do not force the
2329 // structure to be passed in memory even if unaligned, and
2330 // therefore they can straddle an eightbyte.
2331 if (BitField) {
2332 // Ignore padding bit-fields.
2333 if (i->isUnnamedBitfield())
2334 continue;
2335
2336 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002337 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002338
2339 uint64_t EB_Lo = Offset / 64;
2340 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002341
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002342 if (EB_Lo) {
2343 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2344 FieldLo = NoClass;
2345 FieldHi = Integer;
2346 } else {
2347 FieldLo = Integer;
2348 FieldHi = EB_Hi ? Integer : NoClass;
2349 }
2350 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002351 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002352 Lo = merge(Lo, FieldLo);
2353 Hi = merge(Hi, FieldHi);
2354 if (Lo == Memory || Hi == Memory)
2355 break;
2356 }
2357
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002358 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002359 }
2360}
2361
Chris Lattner22a931e2010-06-29 06:01:59 +00002362ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002363 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2364 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002365 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002366 // Treat an enum type as its underlying type.
2367 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2368 Ty = EnumTy->getDecl()->getIntegerType();
2369
2370 return (Ty->isPromotableIntegerType() ?
2371 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2372 }
2373
John McCall7f416cc2015-09-08 08:05:57 +00002374 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002375}
2376
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002377bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2378 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2379 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002380 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002381 if (Size <= 64 || Size > LargestVector)
2382 return true;
2383 }
2384
2385 return false;
2386}
2387
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002388ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2389 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002390 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2391 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002392 //
2393 // This assumption is optimistic, as there could be free registers available
2394 // when we need to pass this argument in memory, and LLVM could try to pass
2395 // the argument in the free register. This does not seem to happen currently,
2396 // but this code would be much safer if we could mark the argument with
2397 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002398 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002399 // Treat an enum type as its underlying type.
2400 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2401 Ty = EnumTy->getDecl()->getIntegerType();
2402
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002403 return (Ty->isPromotableIntegerType() ?
2404 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002405 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002406
Mark Lacey3825e832013-10-06 01:33:34 +00002407 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002408 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002409
Chris Lattner44c2b902011-05-22 23:21:23 +00002410 // Compute the byval alignment. We specify the alignment of the byval in all
2411 // cases so that the mid-level optimizer knows the alignment of the byval.
2412 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002413
2414 // Attempt to avoid passing indirect results using byval when possible. This
2415 // is important for good codegen.
2416 //
2417 // We do this by coercing the value into a scalar type which the backend can
2418 // handle naturally (i.e., without using byval).
2419 //
2420 // For simplicity, we currently only do this when we have exhausted all of the
2421 // free integer registers. Doing this when there are free integer registers
2422 // would require more care, as we would have to ensure that the coerced value
2423 // did not claim the unused register. That would require either reording the
2424 // arguments to the function (so that any subsequent inreg values came first),
2425 // or only doing this optimization when there were no following arguments that
2426 // might be inreg.
2427 //
2428 // We currently expect it to be rare (particularly in well written code) for
2429 // arguments to be passed on the stack when there are still free integer
2430 // registers available (this would typically imply large structs being passed
2431 // by value), so this seems like a fair tradeoff for now.
2432 //
2433 // We can revisit this if the backend grows support for 'onstack' parameter
2434 // attributes. See PR12193.
2435 if (freeIntRegs == 0) {
2436 uint64_t Size = getContext().getTypeSize(Ty);
2437
2438 // If this type fits in an eightbyte, coerce it into the matching integral
2439 // type, which will end up on the stack (with alignment 8).
2440 if (Align == 8 && Size <= 64)
2441 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2442 Size));
2443 }
2444
John McCall7f416cc2015-09-08 08:05:57 +00002445 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002446}
2447
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002448/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2449/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002450llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002451 // Wrapper structs/arrays that only contain vectors are passed just like
2452 // vectors; strip them off if present.
2453 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2454 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002455
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002456 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002457 if (isa<llvm::VectorType>(IRType) ||
2458 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002459 return IRType;
2460
2461 // We couldn't find the preferred IR vector type for 'Ty'.
2462 uint64_t Size = getContext().getTypeSize(Ty);
2463 assert((Size == 128 || Size == 256) && "Invalid type found!");
2464
2465 // Return a LLVM IR vector type based on the size of 'Ty'.
2466 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2467 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002468}
2469
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002470/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2471/// is known to either be off the end of the specified type or being in
2472/// alignment padding. The user type specified is known to be at most 128 bits
2473/// in size, and have passed through X86_64ABIInfo::classify with a successful
2474/// classification that put one of the two halves in the INTEGER class.
2475///
2476/// It is conservatively correct to return false.
2477static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2478 unsigned EndBit, ASTContext &Context) {
2479 // If the bytes being queried are off the end of the type, there is no user
2480 // data hiding here. This handles analysis of builtins, vectors and other
2481 // types that don't contain interesting padding.
2482 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2483 if (TySize <= StartBit)
2484 return true;
2485
Chris Lattner98076a22010-07-29 07:43:55 +00002486 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2487 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2488 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2489
2490 // Check each element to see if the element overlaps with the queried range.
2491 for (unsigned i = 0; i != NumElts; ++i) {
2492 // If the element is after the span we care about, then we're done..
2493 unsigned EltOffset = i*EltSize;
2494 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002495
Chris Lattner98076a22010-07-29 07:43:55 +00002496 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2497 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2498 EndBit-EltOffset, Context))
2499 return false;
2500 }
2501 // If it overlaps no elements, then it is safe to process as padding.
2502 return true;
2503 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002504
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002505 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2506 const RecordDecl *RD = RT->getDecl();
2507 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002508
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002509 // If this is a C++ record, check the bases first.
2510 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002511 for (const auto &I : CXXRD->bases()) {
2512 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002513 "Unexpected base class!");
2514 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002515 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002516
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002517 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002518 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002519 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002520
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002521 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002522 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002523 EndBit-BaseOffset, Context))
2524 return false;
2525 }
2526 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002527
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002528 // Verify that no field has data that overlaps the region of interest. Yes
2529 // this could be sped up a lot by being smarter about queried fields,
2530 // however we're only looking at structs up to 16 bytes, so we don't care
2531 // much.
2532 unsigned idx = 0;
2533 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2534 i != e; ++i, ++idx) {
2535 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002536
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002537 // If we found a field after the region we care about, then we're done.
2538 if (FieldOffset >= EndBit) break;
2539
2540 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2541 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2542 Context))
2543 return false;
2544 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002545
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002546 // If nothing in this record overlapped the area of interest, then we're
2547 // clean.
2548 return true;
2549 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002550
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002551 return false;
2552}
2553
Chris Lattnere556a712010-07-29 18:39:32 +00002554/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2555/// float member at the specified offset. For example, {int,{float}} has a
2556/// float at offset 4. It is conservatively correct for this routine to return
2557/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002558static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002559 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002560 // Base case if we find a float.
2561 if (IROffset == 0 && IRType->isFloatTy())
2562 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002563
Chris Lattnere556a712010-07-29 18:39:32 +00002564 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002565 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002566 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2567 unsigned Elt = SL->getElementContainingOffset(IROffset);
2568 IROffset -= SL->getElementOffset(Elt);
2569 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2570 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002571
Chris Lattnere556a712010-07-29 18:39:32 +00002572 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002573 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2574 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002575 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2576 IROffset -= IROffset/EltSize*EltSize;
2577 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2578 }
2579
2580 return false;
2581}
2582
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002583
2584/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2585/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002586llvm::Type *X86_64ABIInfo::
2587GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002588 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002589 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002590 // pass as float if the last 4 bytes is just padding. This happens for
2591 // structs that contain 3 floats.
2592 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2593 SourceOffset*8+64, getContext()))
2594 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002595
Chris Lattnere556a712010-07-29 18:39:32 +00002596 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2597 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2598 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002599 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2600 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002601 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002602
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002603 return llvm::Type::getDoubleTy(getVMContext());
2604}
2605
2606
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002607/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2608/// an 8-byte GPR. This means that we either have a scalar or we are talking
2609/// about the high or low part of an up-to-16-byte struct. This routine picks
2610/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002611/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2612/// etc).
2613///
2614/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2615/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2616/// the 8-byte value references. PrefType may be null.
2617///
Alp Toker9907f082014-07-09 14:06:35 +00002618/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002619/// an offset into this that we're processing (which is always either 0 or 8).
2620///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002621llvm::Type *X86_64ABIInfo::
2622GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002623 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002624 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2625 // returning an 8-byte unit starting with it. See if we can safely use it.
2626 if (IROffset == 0) {
2627 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002628 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2629 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002630 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002631
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002632 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2633 // goodness in the source type is just tail padding. This is allowed to
2634 // kick in for struct {double,int} on the int, but not on
2635 // struct{double,int,int} because we wouldn't return the second int. We
2636 // have to do this analysis on the source type because we can't depend on
2637 // unions being lowered a specific way etc.
2638 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002639 IRType->isIntegerTy(32) ||
2640 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2641 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2642 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002643
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002644 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2645 SourceOffset*8+64, getContext()))
2646 return IRType;
2647 }
2648 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002649
Chris Lattner2192fe52011-07-18 04:24:23 +00002650 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002651 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002652 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002653 if (IROffset < SL->getSizeInBytes()) {
2654 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2655 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002656
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002657 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2658 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002659 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002660 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002661
Chris Lattner2192fe52011-07-18 04:24:23 +00002662 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002663 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002664 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002665 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002666 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2667 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002668 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002669
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002670 // Okay, we don't have any better idea of what to pass, so we pass this in an
2671 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002672 unsigned TySizeInBytes =
2673 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002674
Chris Lattner3f763422010-07-29 17:34:39 +00002675 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002676
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002677 // It is always safe to classify this as an integer type up to i64 that
2678 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002679 return llvm::IntegerType::get(getVMContext(),
2680 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002681}
2682
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002683
2684/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2685/// be used as elements of a two register pair to pass or return, return a
2686/// first class aggregate to represent them. For example, if the low part of
2687/// a by-value argument should be passed as i32* and the high part as float,
2688/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002689static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002690GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002691 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002692 // In order to correctly satisfy the ABI, we need to the high part to start
2693 // at offset 8. If the high and low parts we inferred are both 4-byte types
2694 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2695 // the second element at offset 8. Check for this:
2696 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2697 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002698 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002699 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002700
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002701 // To handle this, we have to increase the size of the low part so that the
2702 // second element will start at an 8 byte offset. We can't increase the size
2703 // of the second element because it might make us access off the end of the
2704 // struct.
2705 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002706 // There are usually two sorts of types the ABI generation code can produce
2707 // for the low part of a pair that aren't 8 bytes in size: float or
2708 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2709 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002710 // Promote these to a larger type.
2711 if (Lo->isFloatTy())
2712 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2713 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002714 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2715 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002716 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2717 }
2718 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002719
Reid Kleckneree7cf842014-12-01 22:02:27 +00002720 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002721
2722
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002723 // Verify that the second element is at an 8-byte offset.
2724 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2725 "Invalid x86-64 argument pair!");
2726 return Result;
2727}
2728
Chris Lattner31faff52010-07-28 23:06:14 +00002729ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002730classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002731 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2732 // classification algorithm.
2733 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002734 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002735
2736 // Check some invariants.
2737 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002738 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2739
Craig Topper8a13c412014-05-21 05:09:00 +00002740 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002741 switch (Lo) {
2742 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002743 if (Hi == NoClass)
2744 return ABIArgInfo::getIgnore();
2745 // If the low part is just padding, it takes no register, leave ResType
2746 // null.
2747 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2748 "Unknown missing lo part");
2749 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002750
2751 case SSEUp:
2752 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002753 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002754
2755 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2756 // hidden argument.
2757 case Memory:
2758 return getIndirectReturnResult(RetTy);
2759
2760 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2761 // available register of the sequence %rax, %rdx is used.
2762 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002763 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002764
Chris Lattner1f3a0632010-07-29 21:42:50 +00002765 // If we have a sign or zero extended integer, make sure to return Extend
2766 // so that the parameter gets the right LLVM IR attributes.
2767 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2768 // Treat an enum type as its underlying type.
2769 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2770 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002771
Chris Lattner1f3a0632010-07-29 21:42:50 +00002772 if (RetTy->isIntegralOrEnumerationType() &&
2773 RetTy->isPromotableIntegerType())
2774 return ABIArgInfo::getExtend();
2775 }
Chris Lattner31faff52010-07-28 23:06:14 +00002776 break;
2777
2778 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2779 // available SSE register of the sequence %xmm0, %xmm1 is used.
2780 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002781 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002782 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002783
2784 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2785 // returned on the X87 stack in %st0 as 80-bit x87 number.
2786 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002787 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002788 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002789
2790 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2791 // part of the value is returned in %st0 and the imaginary part in
2792 // %st1.
2793 case ComplexX87:
2794 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002795 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002796 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002797 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002798 break;
2799 }
2800
Craig Topper8a13c412014-05-21 05:09:00 +00002801 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002802 switch (Hi) {
2803 // Memory was handled previously and X87 should
2804 // never occur as a hi class.
2805 case Memory:
2806 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002807 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002808
2809 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002810 case NoClass:
2811 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002812
Chris Lattner52b3c132010-09-01 00:20:33 +00002813 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002814 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002815 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2816 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002817 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002818 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002819 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002820 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2821 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002822 break;
2823
2824 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002825 // is passed in the next available eightbyte chunk if the last used
2826 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002827 //
Chris Lattner57540c52011-04-15 05:22:18 +00002828 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002829 case SSEUp:
2830 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002831 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002832 break;
2833
2834 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2835 // returned together with the previous X87 value in %st0.
2836 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002837 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002838 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002839 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002840 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002841 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002842 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002843 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2844 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002845 }
Chris Lattner31faff52010-07-28 23:06:14 +00002846 break;
2847 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002848
Chris Lattner52b3c132010-09-01 00:20:33 +00002849 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002850 // known to pass in the high eightbyte of the result. We do this by forming a
2851 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002852 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002853 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002854
Chris Lattner1f3a0632010-07-29 21:42:50 +00002855 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002856}
2857
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002858ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002859 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2860 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002861 const
2862{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002863 Ty = useFirstFieldIfTransparentUnion(Ty);
2864
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002865 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002866 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002867
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002868 // Check some invariants.
2869 // FIXME: Enforce these by construction.
2870 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002871 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2872
2873 neededInt = 0;
2874 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002875 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002876 switch (Lo) {
2877 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002878 if (Hi == NoClass)
2879 return ABIArgInfo::getIgnore();
2880 // If the low part is just padding, it takes no register, leave ResType
2881 // null.
2882 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2883 "Unknown missing lo part");
2884 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002885
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002886 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2887 // on the stack.
2888 case Memory:
2889
2890 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2891 // COMPLEX_X87, it is passed in memory.
2892 case X87:
2893 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002894 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002895 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002896 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002897
2898 case SSEUp:
2899 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002900 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002901
2902 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2903 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2904 // and %r9 is used.
2905 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002906 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002907
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002908 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002909 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002910
2911 // If we have a sign or zero extended integer, make sure to return Extend
2912 // so that the parameter gets the right LLVM IR attributes.
2913 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2914 // Treat an enum type as its underlying type.
2915 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2916 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002917
Chris Lattner1f3a0632010-07-29 21:42:50 +00002918 if (Ty->isIntegralOrEnumerationType() &&
2919 Ty->isPromotableIntegerType())
2920 return ABIArgInfo::getExtend();
2921 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002922
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002923 break;
2924
2925 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2926 // available SSE register is used, the registers are taken in the
2927 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002928 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002929 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002930 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002931 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002932 break;
2933 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002934 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002935
Craig Topper8a13c412014-05-21 05:09:00 +00002936 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002937 switch (Hi) {
2938 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002939 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002940 // which is passed in memory.
2941 case Memory:
2942 case X87:
2943 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002944 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002945
2946 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002947
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002948 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002949 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002950 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002951 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002952
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002953 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2954 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002955 break;
2956
2957 // X87Up generally doesn't occur here (long double is passed in
2958 // memory), except in situations involving unions.
2959 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002960 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002961 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002962
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002963 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2964 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002965
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002966 ++neededSSE;
2967 break;
2968
2969 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2970 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002971 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002972 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002973 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002974 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002975 break;
2976 }
2977
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002978 // If a high part was specified, merge it together with the low part. It is
2979 // known to pass in the high eightbyte of the result. We do this by forming a
2980 // first class struct aggregate with the high and low part: {low, high}
2981 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002982 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002983
Chris Lattner1f3a0632010-07-29 21:42:50 +00002984 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002985}
2986
Chris Lattner22326a12010-07-29 02:31:05 +00002987void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002988
Reid Kleckner40ca9132014-05-13 22:05:45 +00002989 if (!getCXXABI().classifyReturnType(FI))
2990 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002991
2992 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002993 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002994
2995 // If the return value is indirect, then the hidden argument is consuming one
2996 // integer register.
2997 if (FI.getReturnInfo().isIndirect())
2998 --freeIntRegs;
2999
Peter Collingbournef7706832014-12-12 23:41:25 +00003000 // The chain argument effectively gives us another free register.
3001 if (FI.isChainCall())
3002 ++freeIntRegs;
3003
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003004 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003005 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3006 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003007 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003008 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003009 it != ie; ++it, ++ArgNo) {
3010 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003011
Bill Wendling9987c0e2010-10-18 23:51:38 +00003012 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003013 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003014 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003015
3016 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3017 // eightbyte of an argument, the whole argument is passed on the
3018 // stack. If registers have already been assigned for some
3019 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003020 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003021 freeIntRegs -= neededInt;
3022 freeSSERegs -= neededSSE;
3023 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003024 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003025 }
3026 }
3027}
3028
John McCall7f416cc2015-09-08 08:05:57 +00003029static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3030 Address VAListAddr, QualType Ty) {
3031 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3032 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003033 llvm::Value *overflow_arg_area =
3034 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3035
3036 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3037 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003038 // It isn't stated explicitly in the standard, but in practice we use
3039 // alignment greater than 16 where necessary.
John McCall7f416cc2015-09-08 08:05:57 +00003040 uint64_t Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003041 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00003042 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00003043 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00003044 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003045 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
3046 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003047 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00003048 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003049 overflow_arg_area =
3050 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
3051 overflow_arg_area->getType(),
3052 "overflow_arg_area.align");
3053 }
3054
3055 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003056 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003057 llvm::Value *Res =
3058 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003059 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003060
3061 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3062 // l->overflow_arg_area + sizeof(type).
3063 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3064 // an 8 byte boundary.
3065
3066 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003067 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003068 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003069 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3070 "overflow_arg_area.next");
3071 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3072
3073 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
John McCall7f416cc2015-09-08 08:05:57 +00003074 return Address(Res, CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003075}
3076
John McCall7f416cc2015-09-08 08:05:57 +00003077Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3078 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003079 // Assume that va_list type is correct; should be pointer to LLVM type:
3080 // struct {
3081 // i32 gp_offset;
3082 // i32 fp_offset;
3083 // i8* overflow_arg_area;
3084 // i8* reg_save_area;
3085 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003086 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003087
John McCall7f416cc2015-09-08 08:05:57 +00003088 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003089 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003090 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003091
3092 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3093 // in the registers. If not go to step 7.
3094 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003095 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003096
3097 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3098 // general purpose registers needed to pass type and num_fp to hold
3099 // the number of floating point registers needed.
3100
3101 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3102 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3103 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3104 //
3105 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3106 // register save space).
3107
Craig Topper8a13c412014-05-21 05:09:00 +00003108 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003109 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3110 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003111 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003112 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003113 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3114 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003115 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003116 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3117 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003118 }
3119
3120 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003121 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003122 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3123 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003124 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3125 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003126 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3127 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003128 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3129 }
3130
3131 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3132 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3133 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3134 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3135
3136 // Emit code to load the value if it was passed in registers.
3137
3138 CGF.EmitBlock(InRegBlock);
3139
3140 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3141 // an offset of l->gp_offset and/or l->fp_offset. This may require
3142 // copying to a temporary location in case the parameter is passed
3143 // in different register classes or requires an alignment greater
3144 // than 8 for general purpose registers and 16 for XMM registers.
3145 //
3146 // FIXME: This really results in shameful code when we end up needing to
3147 // collect arguments from different places; often what should result in a
3148 // simple assembling of a structure from scattered addresses has many more
3149 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003150 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003151 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3152 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3153 "reg_save_area");
3154
3155 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003156 if (neededInt && neededSSE) {
3157 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003158 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003159 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003160 Address Tmp = CGF.CreateMemTemp(Ty);
3161 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003162 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003163 llvm::Type *TyLo = ST->getElementType(0);
3164 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003165 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003166 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003167 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3168 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003169 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3170 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003171 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3172 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003173
John McCall7f416cc2015-09-08 08:05:57 +00003174 // Copy the first element.
3175 llvm::Value *V =
3176 CGF.Builder.CreateDefaultAlignedLoad(
3177 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3178 CGF.Builder.CreateStore(V,
3179 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3180
3181 // Copy the second element.
3182 V = CGF.Builder.CreateDefaultAlignedLoad(
3183 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3184 CharUnits Offset = CharUnits::fromQuantity(
3185 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3186 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3187
3188 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003189 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003190 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3191 CharUnits::fromQuantity(8));
3192 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003193
3194 // Copy to a temporary if necessary to ensure the appropriate alignment.
3195 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003196 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003197 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003198 CharUnits TyAlign = SizeAlign.second;
3199
3200 // Copy into a temporary if the type is more aligned than the
3201 // register save area.
3202 if (TyAlign.getQuantity() > 8) {
3203 Address Tmp = CGF.CreateMemTemp(Ty);
3204 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003205 RegAddr = Tmp;
3206 }
John McCall7f416cc2015-09-08 08:05:57 +00003207
Chris Lattner0cf24192010-06-28 20:05:43 +00003208 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003209 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3210 CharUnits::fromQuantity(16));
3211 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003212 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003213 assert(neededSSE == 2 && "Invalid number of needed registers!");
3214 // SSE registers are spaced 16 bytes apart in the register save
3215 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003216 // The ABI isn't explicit about this, but it seems reasonable
3217 // to assume that the slots are 16-byte aligned, since the stack is
3218 // naturally 16-byte aligned and the prologue is expected to store
3219 // all the SSE registers to the RSA.
3220 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3221 CharUnits::fromQuantity(16));
3222 Address RegAddrHi =
3223 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3224 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003225 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003226 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003227 llvm::Value *V;
3228 Address Tmp = CGF.CreateMemTemp(Ty);
3229 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3230 V = CGF.Builder.CreateLoad(
3231 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3232 CGF.Builder.CreateStore(V,
3233 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3234 V = CGF.Builder.CreateLoad(
3235 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3236 CGF.Builder.CreateStore(V,
3237 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3238
3239 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003240 }
3241
3242 // AMD64-ABI 3.5.7p5: Step 5. Set:
3243 // l->gp_offset = l->gp_offset + num_gp * 8
3244 // l->fp_offset = l->fp_offset + num_fp * 16.
3245 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003246 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003247 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3248 gp_offset_p);
3249 }
3250 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003251 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003252 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3253 fp_offset_p);
3254 }
3255 CGF.EmitBranch(ContBlock);
3256
3257 // Emit code to load the value if it was passed in memory.
3258
3259 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003260 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003261
3262 // Return the appropriate result.
3263
3264 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003265 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3266 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003267 return ResAddr;
3268}
3269
Reid Kleckner80944df2014-10-31 22:00:51 +00003270ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3271 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003272
3273 if (Ty->isVoidType())
3274 return ABIArgInfo::getIgnore();
3275
3276 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3277 Ty = EnumTy->getDecl()->getIntegerType();
3278
Reid Kleckner80944df2014-10-31 22:00:51 +00003279 TypeInfo Info = getContext().getTypeInfo(Ty);
3280 uint64_t Width = Info.Width;
3281 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003282
Reid Kleckner9005f412014-05-02 00:51:20 +00003283 const RecordType *RT = Ty->getAs<RecordType>();
3284 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003285 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003286 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003287 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003288 }
3289
3290 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003291 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003292
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003293 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003294 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003295 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003296 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003297 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003298
Reid Kleckner80944df2014-10-31 22:00:51 +00003299 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3300 // other targets.
3301 const Type *Base = nullptr;
3302 uint64_t NumElts = 0;
3303 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3304 if (FreeSSERegs >= NumElts) {
3305 FreeSSERegs -= NumElts;
3306 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3307 return ABIArgInfo::getDirect();
3308 return ABIArgInfo::getExpand();
3309 }
John McCall7f416cc2015-09-08 08:05:57 +00003310 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align),
3311 /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003312 }
3313
3314
Reid Klecknerec87fec2014-05-02 01:17:12 +00003315 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003316 // If the member pointer is represented by an LLVM int or ptr, pass it
3317 // directly.
3318 llvm::Type *LLTy = CGT.ConvertType(Ty);
3319 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3320 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003321 }
3322
Michael Kuperstein4f818702015-02-24 09:35:58 +00003323 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003324 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3325 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003326 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003327 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003328
Reid Kleckner9005f412014-05-02 00:51:20 +00003329 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003330 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003331 }
3332
Julien Lerouge10dcff82014-08-27 00:36:55 +00003333 // Bool type is always extended to the ABI, other builtin types are not
3334 // extended.
3335 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3336 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003337 return ABIArgInfo::getExtend();
3338
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003339 return ABIArgInfo::getDirect();
3340}
3341
3342void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003343 bool IsVectorCall =
3344 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003345
Reid Kleckner80944df2014-10-31 22:00:51 +00003346 // We can use up to 4 SSE return registers with vectorcall.
3347 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3348 if (!getCXXABI().classifyReturnType(FI))
3349 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3350
3351 // We can use up to 6 SSE register parameters with vectorcall.
3352 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003353 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003354 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003355}
3356
John McCall7f416cc2015-09-08 08:05:57 +00003357Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3358 QualType Ty) const {
3359 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3360 CGF.getContext().getTypeInfoInChars(Ty),
3361 CharUnits::fromQuantity(8),
3362 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003363}
Chris Lattner0cf24192010-06-28 20:05:43 +00003364
John McCallea8d8bb2010-03-11 00:10:12 +00003365// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003366namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003367/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3368class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003369public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003370 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3371
John McCall7f416cc2015-09-08 08:05:57 +00003372 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3373 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003374};
3375
3376class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3377public:
Eric Christopher7565e0d2015-05-29 23:09:49 +00003378 PPC32TargetCodeGenInfo(CodeGenTypes &CGT)
3379 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003380
Craig Topper4f12f102014-03-12 06:41:41 +00003381 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003382 // This is recovered from gcc output.
3383 return 1; // r1 is the dedicated stack pointer
3384 }
3385
3386 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003387 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003388};
3389
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003390}
John McCallea8d8bb2010-03-11 00:10:12 +00003391
John McCall7f416cc2015-09-08 08:05:57 +00003392Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3393 QualType Ty) const {
Roman Divacky8a12d842014-11-03 18:32:54 +00003394 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3395 // TODO: Implement this. For now ignore.
3396 (void)CTy;
John McCall7f416cc2015-09-08 08:05:57 +00003397 return Address::invalid();
Roman Divacky8a12d842014-11-03 18:32:54 +00003398 }
3399
John McCall7f416cc2015-09-08 08:05:57 +00003400 // struct __va_list_tag {
3401 // unsigned char gpr;
3402 // unsigned char fpr;
3403 // unsigned short reserved;
3404 // void *overflow_arg_area;
3405 // void *reg_save_area;
3406 // };
3407
Roman Divacky8a12d842014-11-03 18:32:54 +00003408 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003409 bool isInt =
3410 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
John McCall7f416cc2015-09-08 08:05:57 +00003411
3412 // All aggregates are passed indirectly? That doesn't seem consistent
3413 // with the argument-lowering code.
3414 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003415
3416 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003417
3418 // The calling convention either uses 1-2 GPRs or 1 FPR.
3419 Address NumRegsAddr = Address::invalid();
3420 if (isInt) {
3421 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3422 } else {
3423 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003424 }
John McCall7f416cc2015-09-08 08:05:57 +00003425
3426 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3427
3428 // "Align" the register count when TY is i64.
3429 if (isI64) {
3430 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3431 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3432 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003433
Eric Christopher7565e0d2015-05-29 23:09:49 +00003434 llvm::Value *CC =
John McCall7f416cc2015-09-08 08:05:57 +00003435 Builder.CreateICmpULT(NumRegs, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003436
3437 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3438 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3439 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3440
3441 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3442
John McCall7f416cc2015-09-08 08:05:57 +00003443 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3444 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003445
John McCall7f416cc2015-09-08 08:05:57 +00003446 // Case 1: consume registers.
3447 Address RegAddr = Address::invalid();
3448 {
3449 CGF.EmitBlock(UsingRegs);
3450
3451 Address RegSaveAreaPtr =
3452 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3453 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3454 CharUnits::fromQuantity(8));
3455 assert(RegAddr.getElementType() == CGF.Int8Ty);
3456
3457 // Floating-point registers start after the general-purpose registers.
3458 if (!isInt) {
3459 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3460 CharUnits::fromQuantity(32));
3461 }
3462
3463 // Get the address of the saved value by scaling the number of
3464 // registers we've used by the number of
3465 CharUnits RegSize = CharUnits::fromQuantity(isInt ? 4 : 8);
3466 llvm::Value *RegOffset =
3467 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3468 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3469 RegAddr.getPointer(), RegOffset),
3470 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3471 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3472
3473 // Increase the used-register count.
3474 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(isI64 ? 2 : 1));
3475 Builder.CreateStore(NumRegs, NumRegsAddr);
3476
3477 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003478 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003479
John McCall7f416cc2015-09-08 08:05:57 +00003480 // Case 2: consume space in the overflow area.
3481 Address MemAddr = Address::invalid();
3482 {
3483 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003484
John McCall7f416cc2015-09-08 08:05:57 +00003485 // Everything in the overflow area is rounded up to a size of at least 4.
3486 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3487
3488 CharUnits Size;
3489 if (!isIndirect) {
3490 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
3491 Size = TypeInfo.first.RoundUpToAlignment(OverflowAreaAlign);
3492 } else {
3493 Size = CGF.getPointerSize();
3494 }
3495
3496 Address OverflowAreaAddr =
3497 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
3498 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr),
3499 OverflowAreaAlign);
3500
3501 // The current address is the address of the varargs element.
3502 // FIXME: do we not need to round up to alignment?
3503 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3504
3505 // Increase the overflow area.
3506 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3507 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3508 CGF.EmitBranch(Cont);
3509 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003510
3511 CGF.EmitBlock(Cont);
3512
John McCall7f416cc2015-09-08 08:05:57 +00003513 // Merge the cases with a phi.
3514 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3515 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003516
John McCall7f416cc2015-09-08 08:05:57 +00003517 // Load the pointer if the argument was passed indirectly.
3518 if (isIndirect) {
3519 Result = Address(Builder.CreateLoad(Result, "aggr"),
3520 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003521 }
3522
3523 return Result;
3524}
3525
John McCallea8d8bb2010-03-11 00:10:12 +00003526bool
3527PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3528 llvm::Value *Address) const {
3529 // This is calculated from the LLVM and GCC tables and verified
3530 // against gcc output. AFAIK all ABIs use the same encoding.
3531
3532 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003533
Chris Lattnerece04092012-02-07 00:39:47 +00003534 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003535 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3536 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3537 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3538
3539 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003540 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003541
3542 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003543 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003544
3545 // 64-76 are various 4-byte special-purpose registers:
3546 // 64: mq
3547 // 65: lr
3548 // 66: ctr
3549 // 67: ap
3550 // 68-75 cr0-7
3551 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003552 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003553
3554 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003555 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003556
3557 // 109: vrsave
3558 // 110: vscr
3559 // 111: spe_acc
3560 // 112: spefscr
3561 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003562 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003563
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003564 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003565}
3566
Roman Divackyd966e722012-05-09 18:22:46 +00003567// PowerPC-64
3568
3569namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003570/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3571class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003572public:
3573 enum ABIKind {
3574 ELFv1 = 0,
3575 ELFv2
3576 };
3577
3578private:
3579 static const unsigned GPRBits = 64;
3580 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003581 bool HasQPX;
3582
3583 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3584 // will be passed in a QPX register.
3585 bool IsQPXVectorTy(const Type *Ty) const {
3586 if (!HasQPX)
3587 return false;
3588
3589 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3590 unsigned NumElements = VT->getNumElements();
3591 if (NumElements == 1)
3592 return false;
3593
3594 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3595 if (getContext().getTypeSize(Ty) <= 256)
3596 return true;
3597 } else if (VT->getElementType()->
3598 isSpecificBuiltinType(BuiltinType::Float)) {
3599 if (getContext().getTypeSize(Ty) <= 128)
3600 return true;
3601 }
3602 }
3603
3604 return false;
3605 }
3606
3607 bool IsQPXVectorTy(QualType Ty) const {
3608 return IsQPXVectorTy(Ty.getTypePtr());
3609 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003610
3611public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003612 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3613 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003614
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003615 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003616 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003617
3618 ABIArgInfo classifyReturnType(QualType RetTy) const;
3619 ABIArgInfo classifyArgumentType(QualType Ty) const;
3620
Reid Klecknere9f6a712014-10-31 17:10:41 +00003621 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3622 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3623 uint64_t Members) const override;
3624
Bill Schmidt84d37792012-10-12 19:26:17 +00003625 // TODO: We can add more logic to computeInfo to improve performance.
3626 // Example: For aggregate arguments that fit in a register, we could
3627 // use getDirectInReg (as is done below for structs containing a single
3628 // floating-point value) to avoid pushing them to memory on function
3629 // entry. This would require changing the logic in PPCISelLowering
3630 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003631 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003632 if (!getCXXABI().classifyReturnType(FI))
3633 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003634 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003635 // We rely on the default argument classification for the most part.
3636 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003637 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003638 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003639 if (T) {
3640 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003641 if (IsQPXVectorTy(T) ||
3642 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003643 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003644 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003645 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003646 continue;
3647 }
3648 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003649 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003650 }
3651 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003652
John McCall7f416cc2015-09-08 08:05:57 +00003653 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3654 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003655};
3656
3657class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003658
Bill Schmidt25cb3492012-10-03 19:18:57 +00003659public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003660 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003661 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003662 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003663
Craig Topper4f12f102014-03-12 06:41:41 +00003664 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003665 // This is recovered from gcc output.
3666 return 1; // r1 is the dedicated stack pointer
3667 }
3668
3669 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003670 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003671};
3672
Roman Divackyd966e722012-05-09 18:22:46 +00003673class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3674public:
3675 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3676
Craig Topper4f12f102014-03-12 06:41:41 +00003677 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003678 // This is recovered from gcc output.
3679 return 1; // r1 is the dedicated stack pointer
3680 }
3681
3682 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003683 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003684};
3685
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003686}
Roman Divackyd966e722012-05-09 18:22:46 +00003687
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003688// Return true if the ABI requires Ty to be passed sign- or zero-
3689// extended to 64 bits.
3690bool
3691PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3692 // Treat an enum type as its underlying type.
3693 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3694 Ty = EnumTy->getDecl()->getIntegerType();
3695
3696 // Promotable integer types are required to be promoted by the ABI.
3697 if (Ty->isPromotableIntegerType())
3698 return true;
3699
3700 // In addition to the usual promotable integer types, we also need to
3701 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3702 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3703 switch (BT->getKind()) {
3704 case BuiltinType::Int:
3705 case BuiltinType::UInt:
3706 return true;
3707 default:
3708 break;
3709 }
3710
3711 return false;
3712}
3713
John McCall7f416cc2015-09-08 08:05:57 +00003714/// isAlignedParamType - Determine whether a type requires 16-byte or
3715/// higher alignment in the parameter area. Always returns at least 8.
3716CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003717 // Complex types are passed just like their elements.
3718 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3719 Ty = CTy->getElementType();
3720
3721 // Only vector types of size 16 bytes need alignment (larger types are
3722 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003723 if (IsQPXVectorTy(Ty)) {
3724 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003725 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003726
John McCall7f416cc2015-09-08 08:05:57 +00003727 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003728 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00003729 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003730 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003731
3732 // For single-element float/vector structs, we consider the whole type
3733 // to have the same alignment requirements as its single element.
3734 const Type *AlignAsType = nullptr;
3735 const Type *EltType = isSingleElementStruct(Ty, getContext());
3736 if (EltType) {
3737 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003738 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003739 getContext().getTypeSize(EltType) == 128) ||
3740 (BT && BT->isFloatingPoint()))
3741 AlignAsType = EltType;
3742 }
3743
Ulrich Weigandb7122372014-07-21 00:48:09 +00003744 // Likewise for ELFv2 homogeneous aggregates.
3745 const Type *Base = nullptr;
3746 uint64_t Members = 0;
3747 if (!AlignAsType && Kind == ELFv2 &&
3748 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3749 AlignAsType = Base;
3750
Ulrich Weigand581badc2014-07-10 17:20:07 +00003751 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003752 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3753 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003754 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003755
John McCall7f416cc2015-09-08 08:05:57 +00003756 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003757 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00003758 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003759 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003760
3761 // Otherwise, we only need alignment for any aggregate type that
3762 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003763 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3764 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00003765 return CharUnits::fromQuantity(32);
3766 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003767 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003768
John McCall7f416cc2015-09-08 08:05:57 +00003769 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00003770}
3771
Ulrich Weigandb7122372014-07-21 00:48:09 +00003772/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3773/// aggregate. Base is set to the base element type, and Members is set
3774/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003775bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3776 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003777 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3778 uint64_t NElements = AT->getSize().getZExtValue();
3779 if (NElements == 0)
3780 return false;
3781 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3782 return false;
3783 Members *= NElements;
3784 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3785 const RecordDecl *RD = RT->getDecl();
3786 if (RD->hasFlexibleArrayMember())
3787 return false;
3788
3789 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003790
3791 // If this is a C++ record, check the bases first.
3792 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3793 for (const auto &I : CXXRD->bases()) {
3794 // Ignore empty records.
3795 if (isEmptyRecord(getContext(), I.getType(), true))
3796 continue;
3797
3798 uint64_t FldMembers;
3799 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3800 return false;
3801
3802 Members += FldMembers;
3803 }
3804 }
3805
Ulrich Weigandb7122372014-07-21 00:48:09 +00003806 for (const auto *FD : RD->fields()) {
3807 // Ignore (non-zero arrays of) empty records.
3808 QualType FT = FD->getType();
3809 while (const ConstantArrayType *AT =
3810 getContext().getAsConstantArrayType(FT)) {
3811 if (AT->getSize().getZExtValue() == 0)
3812 return false;
3813 FT = AT->getElementType();
3814 }
3815 if (isEmptyRecord(getContext(), FT, true))
3816 continue;
3817
3818 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3819 if (getContext().getLangOpts().CPlusPlus &&
3820 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3821 continue;
3822
3823 uint64_t FldMembers;
3824 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3825 return false;
3826
3827 Members = (RD->isUnion() ?
3828 std::max(Members, FldMembers) : Members + FldMembers);
3829 }
3830
3831 if (!Base)
3832 return false;
3833
3834 // Ensure there is no padding.
3835 if (getContext().getTypeSize(Base) * Members !=
3836 getContext().getTypeSize(Ty))
3837 return false;
3838 } else {
3839 Members = 1;
3840 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3841 Members = 2;
3842 Ty = CT->getElementType();
3843 }
3844
Reid Klecknere9f6a712014-10-31 17:10:41 +00003845 // Most ABIs only support float, double, and some vector type widths.
3846 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003847 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003848
3849 // The base type must be the same for all members. Types that
3850 // agree in both total size and mode (float vs. vector) are
3851 // treated as being equivalent here.
3852 const Type *TyPtr = Ty.getTypePtr();
3853 if (!Base)
3854 Base = TyPtr;
3855
3856 if (Base->isVectorType() != TyPtr->isVectorType() ||
3857 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3858 return false;
3859 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003860 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3861}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003862
Reid Klecknere9f6a712014-10-31 17:10:41 +00003863bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3864 // Homogeneous aggregates for ELFv2 must have base types of float,
3865 // double, long double, or 128-bit vectors.
3866 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3867 if (BT->getKind() == BuiltinType::Float ||
3868 BT->getKind() == BuiltinType::Double ||
3869 BT->getKind() == BuiltinType::LongDouble)
3870 return true;
3871 }
3872 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003873 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003874 return true;
3875 }
3876 return false;
3877}
3878
3879bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3880 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003881 // Vector types require one register, floating point types require one
3882 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003883 uint32_t NumRegs =
3884 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003885
3886 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003887 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003888}
3889
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003890ABIArgInfo
3891PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003892 Ty = useFirstFieldIfTransparentUnion(Ty);
3893
Bill Schmidt90b22c92012-11-27 02:46:43 +00003894 if (Ty->isAnyComplexType())
3895 return ABIArgInfo::getDirect();
3896
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003897 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3898 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003899 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003900 uint64_t Size = getContext().getTypeSize(Ty);
3901 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003902 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003903 else if (Size < 128) {
3904 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3905 return ABIArgInfo::getDirect(CoerceTy);
3906 }
3907 }
3908
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003909 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003910 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003911 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003912
John McCall7f416cc2015-09-08 08:05:57 +00003913 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
3914 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00003915
3916 // ELFv2 homogeneous aggregates are passed as array types.
3917 const Type *Base = nullptr;
3918 uint64_t Members = 0;
3919 if (Kind == ELFv2 &&
3920 isHomogeneousAggregate(Ty, Base, Members)) {
3921 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3922 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3923 return ABIArgInfo::getDirect(CoerceTy);
3924 }
3925
Ulrich Weigand601957f2014-07-21 00:56:36 +00003926 // If an aggregate may end up fully in registers, we do not
3927 // use the ByVal method, but pass the aggregate as array.
3928 // This is usually beneficial since we avoid forcing the
3929 // back-end to store the argument to memory.
3930 uint64_t Bits = getContext().getTypeSize(Ty);
3931 if (Bits > 0 && Bits <= 8 * GPRBits) {
3932 llvm::Type *CoerceTy;
3933
3934 // Types up to 8 bytes are passed as integer type (which will be
3935 // properly aligned in the argument save area doubleword).
3936 if (Bits <= GPRBits)
3937 CoerceTy = llvm::IntegerType::get(getVMContext(),
3938 llvm::RoundUpToAlignment(Bits, 8));
3939 // Larger types are passed as arrays, with the base type selected
3940 // according to the required alignment in the save area.
3941 else {
3942 uint64_t RegBits = ABIAlign * 8;
3943 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3944 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3945 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3946 }
3947
3948 return ABIArgInfo::getDirect(CoerceTy);
3949 }
3950
Ulrich Weigandb7122372014-07-21 00:48:09 +00003951 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00003952 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
3953 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00003954 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003955 }
3956
3957 return (isPromotableTypeForABI(Ty) ?
3958 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3959}
3960
3961ABIArgInfo
3962PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3963 if (RetTy->isVoidType())
3964 return ABIArgInfo::getIgnore();
3965
Bill Schmidta3d121c2012-12-17 04:20:17 +00003966 if (RetTy->isAnyComplexType())
3967 return ABIArgInfo::getDirect();
3968
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003969 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3970 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003971 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003972 uint64_t Size = getContext().getTypeSize(RetTy);
3973 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003974 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003975 else if (Size < 128) {
3976 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3977 return ABIArgInfo::getDirect(CoerceTy);
3978 }
3979 }
3980
Ulrich Weigandb7122372014-07-21 00:48:09 +00003981 if (isAggregateTypeForABI(RetTy)) {
3982 // ELFv2 homogeneous aggregates are returned as array types.
3983 const Type *Base = nullptr;
3984 uint64_t Members = 0;
3985 if (Kind == ELFv2 &&
3986 isHomogeneousAggregate(RetTy, Base, Members)) {
3987 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3988 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3989 return ABIArgInfo::getDirect(CoerceTy);
3990 }
3991
3992 // ELFv2 small aggregates are returned in up to two registers.
3993 uint64_t Bits = getContext().getTypeSize(RetTy);
3994 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3995 if (Bits == 0)
3996 return ABIArgInfo::getIgnore();
3997
3998 llvm::Type *CoerceTy;
3999 if (Bits > GPRBits) {
4000 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004001 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004002 } else
4003 CoerceTy = llvm::IntegerType::get(getVMContext(),
4004 llvm::RoundUpToAlignment(Bits, 8));
4005 return ABIArgInfo::getDirect(CoerceTy);
4006 }
4007
4008 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004009 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004010 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004011
4012 return (isPromotableTypeForABI(RetTy) ?
4013 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4014}
4015
Bill Schmidt25cb3492012-10-03 19:18:57 +00004016// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004017Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4018 QualType Ty) const {
4019 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4020 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004021
John McCall7f416cc2015-09-08 08:05:57 +00004022 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004023
Bill Schmidt924c4782013-01-14 17:45:36 +00004024 // If we have a complex type and the base type is smaller than 8 bytes,
4025 // the ABI calls for the real and imaginary parts to be right-adjusted
4026 // in separate doublewords. However, Clang expects us to produce a
4027 // pointer to a structure with the two parts packed tightly. So generate
4028 // loads of the real and imaginary parts relative to the va_list pointer,
4029 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004030 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4031 CharUnits EltSize = TypeInfo.first / 2;
4032 if (EltSize < SlotSize) {
4033 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4034 SlotSize * 2, SlotSize,
4035 SlotSize, /*AllowHigher*/ true);
4036
4037 Address RealAddr = Addr;
4038 Address ImagAddr = RealAddr;
4039 if (CGF.CGM.getDataLayout().isBigEndian()) {
4040 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4041 SlotSize - EltSize);
4042 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4043 2 * SlotSize - EltSize);
4044 } else {
4045 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4046 }
4047
4048 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4049 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4050 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4051 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4052 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4053
4054 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4055 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4056 /*init*/ true);
4057 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004058 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004059 }
4060
John McCall7f416cc2015-09-08 08:05:57 +00004061 // Otherwise, just use the general rule.
4062 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4063 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004064}
4065
4066static bool
4067PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4068 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004069 // This is calculated from the LLVM and GCC tables and verified
4070 // against gcc output. AFAIK all ABIs use the same encoding.
4071
4072 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4073
4074 llvm::IntegerType *i8 = CGF.Int8Ty;
4075 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4076 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4077 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4078
4079 // 0-31: r0-31, the 8-byte general-purpose registers
4080 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4081
4082 // 32-63: fp0-31, the 8-byte floating-point registers
4083 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4084
4085 // 64-76 are various 4-byte special-purpose registers:
4086 // 64: mq
4087 // 65: lr
4088 // 66: ctr
4089 // 67: ap
4090 // 68-75 cr0-7
4091 // 76: xer
4092 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4093
4094 // 77-108: v0-31, the 16-byte vector registers
4095 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4096
4097 // 109: vrsave
4098 // 110: vscr
4099 // 111: spe_acc
4100 // 112: spefscr
4101 // 113: sfp
4102 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4103
4104 return false;
4105}
John McCallea8d8bb2010-03-11 00:10:12 +00004106
Bill Schmidt25cb3492012-10-03 19:18:57 +00004107bool
4108PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4109 CodeGen::CodeGenFunction &CGF,
4110 llvm::Value *Address) const {
4111
4112 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4113}
4114
4115bool
4116PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4117 llvm::Value *Address) const {
4118
4119 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4120}
4121
Chris Lattner0cf24192010-06-28 20:05:43 +00004122//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004123// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004124//===----------------------------------------------------------------------===//
4125
4126namespace {
4127
Tim Northover573cbee2014-05-24 12:52:07 +00004128class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004129public:
4130 enum ABIKind {
4131 AAPCS = 0,
4132 DarwinPCS
4133 };
4134
4135private:
4136 ABIKind Kind;
4137
4138public:
Tim Northover573cbee2014-05-24 12:52:07 +00004139 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004140
4141private:
4142 ABIKind getABIKind() const { return Kind; }
4143 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4144
4145 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004146 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004147 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4148 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4149 uint64_t Members) const override;
4150
Tim Northovera2ee4332014-03-29 15:09:45 +00004151 bool isIllegalVectorType(QualType Ty) const;
4152
David Blaikie1cbb9712014-11-14 19:09:44 +00004153 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004154 if (!getCXXABI().classifyReturnType(FI))
4155 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004156
Tim Northoverb047bfa2014-11-27 21:02:49 +00004157 for (auto &it : FI.arguments())
4158 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004159 }
4160
John McCall7f416cc2015-09-08 08:05:57 +00004161 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4162 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004163
John McCall7f416cc2015-09-08 08:05:57 +00004164 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4165 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004166
John McCall7f416cc2015-09-08 08:05:57 +00004167 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4168 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004169 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4170 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4171 }
4172};
4173
Tim Northover573cbee2014-05-24 12:52:07 +00004174class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004175public:
Tim Northover573cbee2014-05-24 12:52:07 +00004176 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4177 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004178
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004179 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004180 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4181 }
4182
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004183 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4184 return 31;
4185 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004186
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004187 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004188};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004189}
Tim Northovera2ee4332014-03-29 15:09:45 +00004190
Tim Northoverb047bfa2014-11-27 21:02:49 +00004191ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004192 Ty = useFirstFieldIfTransparentUnion(Ty);
4193
Tim Northovera2ee4332014-03-29 15:09:45 +00004194 // Handle illegal vector types here.
4195 if (isIllegalVectorType(Ty)) {
4196 uint64_t Size = getContext().getTypeSize(Ty);
4197 if (Size <= 32) {
4198 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004199 return ABIArgInfo::getDirect(ResType);
4200 }
4201 if (Size == 64) {
4202 llvm::Type *ResType =
4203 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004204 return ABIArgInfo::getDirect(ResType);
4205 }
4206 if (Size == 128) {
4207 llvm::Type *ResType =
4208 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004209 return ABIArgInfo::getDirect(ResType);
4210 }
John McCall7f416cc2015-09-08 08:05:57 +00004211 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004212 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004213
4214 if (!isAggregateTypeForABI(Ty)) {
4215 // Treat an enum type as its underlying type.
4216 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4217 Ty = EnumTy->getDecl()->getIntegerType();
4218
Tim Northovera2ee4332014-03-29 15:09:45 +00004219 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4220 ? ABIArgInfo::getExtend()
4221 : ABIArgInfo::getDirect());
4222 }
4223
4224 // Structures with either a non-trivial destructor or a non-trivial
4225 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004226 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004227 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4228 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004229 }
4230
4231 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4232 // elsewhere for GNU compatibility.
4233 if (isEmptyRecord(getContext(), Ty, true)) {
4234 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4235 return ABIArgInfo::getIgnore();
4236
Tim Northovera2ee4332014-03-29 15:09:45 +00004237 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4238 }
4239
4240 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004241 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004242 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004243 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004244 return ABIArgInfo::getDirect(
4245 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004246 }
4247
4248 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4249 uint64_t Size = getContext().getTypeSize(Ty);
4250 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004251 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004252 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004253
Tim Northovera2ee4332014-03-29 15:09:45 +00004254 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4255 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004256 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004257 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4258 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4259 }
4260 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4261 }
4262
John McCall7f416cc2015-09-08 08:05:57 +00004263 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004264}
4265
Tim Northover573cbee2014-05-24 12:52:07 +00004266ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004267 if (RetTy->isVoidType())
4268 return ABIArgInfo::getIgnore();
4269
4270 // Large vector types should be returned via memory.
4271 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004272 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004273
4274 if (!isAggregateTypeForABI(RetTy)) {
4275 // Treat an enum type as its underlying type.
4276 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4277 RetTy = EnumTy->getDecl()->getIntegerType();
4278
Tim Northover4dab6982014-04-18 13:46:08 +00004279 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4280 ? ABIArgInfo::getExtend()
4281 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004282 }
4283
Tim Northovera2ee4332014-03-29 15:09:45 +00004284 if (isEmptyRecord(getContext(), RetTy, true))
4285 return ABIArgInfo::getIgnore();
4286
Craig Topper8a13c412014-05-21 05:09:00 +00004287 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004288 uint64_t Members = 0;
4289 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004290 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4291 return ABIArgInfo::getDirect();
4292
4293 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4294 uint64_t Size = getContext().getTypeSize(RetTy);
4295 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004296 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004297 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004298
4299 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4300 // For aggregates with 16-byte alignment, we use i128.
4301 if (Alignment < 128 && Size == 128) {
4302 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4303 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4304 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004305 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4306 }
4307
John McCall7f416cc2015-09-08 08:05:57 +00004308 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004309}
4310
Tim Northover573cbee2014-05-24 12:52:07 +00004311/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4312bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004313 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4314 // Check whether VT is legal.
4315 unsigned NumElements = VT->getNumElements();
4316 uint64_t Size = getContext().getTypeSize(VT);
4317 // NumElements should be power of 2 between 1 and 16.
4318 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4319 return true;
4320 return Size != 64 && (Size != 128 || NumElements == 1);
4321 }
4322 return false;
4323}
4324
Reid Klecknere9f6a712014-10-31 17:10:41 +00004325bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4326 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4327 // point type or a short-vector type. This is the same as the 32-bit ABI,
4328 // but with the difference that any floating-point type is allowed,
4329 // including __fp16.
4330 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4331 if (BT->isFloatingPoint())
4332 return true;
4333 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4334 unsigned VecSize = getContext().getTypeSize(VT);
4335 if (VecSize == 64 || VecSize == 128)
4336 return true;
4337 }
4338 return false;
4339}
4340
4341bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4342 uint64_t Members) const {
4343 return Members <= 4;
4344}
4345
John McCall7f416cc2015-09-08 08:05:57 +00004346Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004347 QualType Ty,
4348 CodeGenFunction &CGF) const {
4349 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004350 bool IsIndirect = AI.isIndirect();
4351
Tim Northoverb047bfa2014-11-27 21:02:49 +00004352 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4353 if (IsIndirect)
4354 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4355 else if (AI.getCoerceToType())
4356 BaseTy = AI.getCoerceToType();
4357
4358 unsigned NumRegs = 1;
4359 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4360 BaseTy = ArrTy->getElementType();
4361 NumRegs = ArrTy->getNumElements();
4362 }
4363 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4364
Tim Northovera2ee4332014-03-29 15:09:45 +00004365 // The AArch64 va_list type and handling is specified in the Procedure Call
4366 // Standard, section B.4:
4367 //
4368 // struct {
4369 // void *__stack;
4370 // void *__gr_top;
4371 // void *__vr_top;
4372 // int __gr_offs;
4373 // int __vr_offs;
4374 // };
4375
4376 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4377 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4378 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4379 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004380
John McCall7f416cc2015-09-08 08:05:57 +00004381 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4382 CharUnits TyAlign = TyInfo.second;
4383
4384 Address reg_offs_p = Address::invalid();
4385 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004386 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004387 CharUnits reg_top_offset;
4388 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004389 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004390 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004391 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004392 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4393 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004394 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4395 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004396 reg_top_offset = CharUnits::fromQuantity(8);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004397 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004398 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004399 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004400 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004401 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4402 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004403 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4404 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004405 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004406 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004407 }
4408
4409 //=======================================
4410 // Find out where argument was passed
4411 //=======================================
4412
4413 // If reg_offs >= 0 we're already using the stack for this type of
4414 // argument. We don't want to keep updating reg_offs (in case it overflows,
4415 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4416 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004417 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004418 UsingStack = CGF.Builder.CreateICmpSGE(
4419 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4420
4421 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4422
4423 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004424 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004425 CGF.EmitBlock(MaybeRegBlock);
4426
4427 // Integer arguments may need to correct register alignment (for example a
4428 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4429 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004430 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4431 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004432
4433 reg_offs = CGF.Builder.CreateAdd(
4434 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4435 "align_regoffs");
4436 reg_offs = CGF.Builder.CreateAnd(
4437 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4438 "aligned_regoffs");
4439 }
4440
4441 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004442 // The fact that this is done unconditionally reflects the fact that
4443 // allocating an argument to the stack also uses up all the remaining
4444 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004445 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004446 NewOffset = CGF.Builder.CreateAdd(
4447 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4448 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4449
4450 // Now we're in a position to decide whether this argument really was in
4451 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004452 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004453 InRegs = CGF.Builder.CreateICmpSLE(
4454 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4455
4456 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4457
4458 //=======================================
4459 // Argument was in registers
4460 //=======================================
4461
4462 // Now we emit the code for if the argument was originally passed in
4463 // registers. First start the appropriate block:
4464 CGF.EmitBlock(InRegBlock);
4465
John McCall7f416cc2015-09-08 08:05:57 +00004466 llvm::Value *reg_top = nullptr;
4467 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4468 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004469 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004470 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4471 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4472 Address RegAddr = Address::invalid();
4473 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004474
4475 if (IsIndirect) {
4476 // If it's been passed indirectly (actually a struct), whatever we find from
4477 // stored registers or on the stack will actually be a struct **.
4478 MemTy = llvm::PointerType::getUnqual(MemTy);
4479 }
4480
Craig Topper8a13c412014-05-21 05:09:00 +00004481 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004482 uint64_t NumMembers = 0;
4483 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004484 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004485 // Homogeneous aggregates passed in registers will have their elements split
4486 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4487 // qN+1, ...). We reload and store into a temporary local variable
4488 // contiguously.
4489 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004490 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004491 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4492 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004493 Address Tmp = CGF.CreateTempAlloca(HFATy,
4494 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004495
John McCall7f416cc2015-09-08 08:05:57 +00004496 // On big-endian platforms, the value will be right-aligned in its slot.
4497 int Offset = 0;
4498 if (CGF.CGM.getDataLayout().isBigEndian() &&
4499 BaseTyInfo.first.getQuantity() < 16)
4500 Offset = 16 - BaseTyInfo.first.getQuantity();
4501
Tim Northovera2ee4332014-03-29 15:09:45 +00004502 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004503 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4504 Address LoadAddr =
4505 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4506 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4507
4508 Address StoreAddr =
4509 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004510
4511 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4512 CGF.Builder.CreateStore(Elem, StoreAddr);
4513 }
4514
John McCall7f416cc2015-09-08 08:05:57 +00004515 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004516 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004517 // Otherwise the object is contiguous in memory.
4518
4519 // It might be right-aligned in its slot.
4520 CharUnits SlotSize = BaseAddr.getAlignment();
4521 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004522 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004523 TyInfo.first < SlotSize) {
4524 CharUnits Offset = SlotSize - TyInfo.first;
4525 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004526 }
4527
John McCall7f416cc2015-09-08 08:05:57 +00004528 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004529 }
4530
4531 CGF.EmitBranch(ContBlock);
4532
4533 //=======================================
4534 // Argument was on the stack
4535 //=======================================
4536 CGF.EmitBlock(OnStackBlock);
4537
John McCall7f416cc2015-09-08 08:05:57 +00004538 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4539 CharUnits::Zero(), "stack_p");
4540 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004541
John McCall7f416cc2015-09-08 08:05:57 +00004542 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004543 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004544 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4545 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004546
John McCall7f416cc2015-09-08 08:05:57 +00004547 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004548
John McCall7f416cc2015-09-08 08:05:57 +00004549 OnStackPtr = CGF.Builder.CreateAdd(
4550 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004551 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004552 OnStackPtr = CGF.Builder.CreateAnd(
4553 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004554 "align_stack");
4555
John McCall7f416cc2015-09-08 08:05:57 +00004556 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004557 }
John McCall7f416cc2015-09-08 08:05:57 +00004558 Address OnStackAddr(OnStackPtr,
4559 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004560
John McCall7f416cc2015-09-08 08:05:57 +00004561 // All stack slots are multiples of 8 bytes.
4562 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4563 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004564 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004565 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004566 else
John McCall7f416cc2015-09-08 08:05:57 +00004567 StackSize = TyInfo.first.RoundUpToAlignment(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004568
John McCall7f416cc2015-09-08 08:05:57 +00004569 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004570 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004571 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004572
4573 // Write the new value of __stack for the next call to va_arg
4574 CGF.Builder.CreateStore(NewStack, stack_p);
4575
4576 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004577 TyInfo.first < StackSlotSize) {
4578 CharUnits Offset = StackSlotSize - TyInfo.first;
4579 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004580 }
4581
John McCall7f416cc2015-09-08 08:05:57 +00004582 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004583
4584 CGF.EmitBranch(ContBlock);
4585
4586 //=======================================
4587 // Tidy up
4588 //=======================================
4589 CGF.EmitBlock(ContBlock);
4590
John McCall7f416cc2015-09-08 08:05:57 +00004591 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4592 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004593
4594 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004595 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4596 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004597
4598 return ResAddr;
4599}
4600
John McCall7f416cc2015-09-08 08:05:57 +00004601Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4602 CodeGenFunction &CGF) const {
4603 // The backend's lowering doesn't support va_arg for aggregates or
4604 // illegal vector types. Lower VAArg here for these cases and use
4605 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004606 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00004607 return Address::invalid();
Tim Northovera2ee4332014-03-29 15:09:45 +00004608
John McCall7f416cc2015-09-08 08:05:57 +00004609 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004610
John McCall7f416cc2015-09-08 08:05:57 +00004611 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004612 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004613 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4614 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4615 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004616 }
4617
John McCall7f416cc2015-09-08 08:05:57 +00004618 // The size of the actual thing passed, which might end up just
4619 // being a pointer for indirect types.
4620 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4621
4622 // Arguments bigger than 16 bytes which aren't homogeneous
4623 // aggregates should be passed indirectly.
4624 bool IsIndirect = false;
4625 if (TyInfo.first.getQuantity() > 16) {
4626 const Type *Base = nullptr;
4627 uint64_t Members = 0;
4628 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004629 }
4630
John McCall7f416cc2015-09-08 08:05:57 +00004631 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4632 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004633}
4634
4635//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004636// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004637//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004638
4639namespace {
4640
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004641class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004642public:
4643 enum ABIKind {
4644 APCS = 0,
4645 AAPCS = 1,
4646 AAPCS_VFP
4647 };
4648
4649private:
4650 ABIKind Kind;
4651
4652public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004653 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004654 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004655 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004656
John McCall3480ef22011-08-30 01:42:09 +00004657 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004658 switch (getTarget().getTriple().getEnvironment()) {
4659 case llvm::Triple::Android:
4660 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004661 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004662 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004663 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004664 return true;
4665 default:
4666 return false;
4667 }
John McCall3480ef22011-08-30 01:42:09 +00004668 }
4669
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004670 bool isEABIHF() const {
4671 switch (getTarget().getTriple().getEnvironment()) {
4672 case llvm::Triple::EABIHF:
4673 case llvm::Triple::GNUEABIHF:
4674 return true;
4675 default:
4676 return false;
4677 }
4678 }
4679
Daniel Dunbar020daa92009-09-12 01:00:39 +00004680 ABIKind getABIKind() const { return Kind; }
4681
Tim Northovera484bc02013-10-01 14:34:25 +00004682private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004683 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004684 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004685 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004686
Reid Klecknere9f6a712014-10-31 17:10:41 +00004687 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4688 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4689 uint64_t Members) const override;
4690
Craig Topper4f12f102014-03-12 06:41:41 +00004691 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004692
John McCall7f416cc2015-09-08 08:05:57 +00004693 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4694 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004695
4696 llvm::CallingConv::ID getLLVMDefaultCC() const;
4697 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004698 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004699};
4700
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004701class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4702public:
Chris Lattner2b037972010-07-29 02:01:43 +00004703 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4704 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004705
John McCall3480ef22011-08-30 01:42:09 +00004706 const ARMABIInfo &getABIInfo() const {
4707 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4708 }
4709
Craig Topper4f12f102014-03-12 06:41:41 +00004710 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004711 return 13;
4712 }
Roman Divackyc1617352011-05-18 19:36:54 +00004713
Craig Topper4f12f102014-03-12 06:41:41 +00004714 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004715 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4716 }
4717
Roman Divackyc1617352011-05-18 19:36:54 +00004718 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004719 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004720 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004721
4722 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004723 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004724 return false;
4725 }
John McCall3480ef22011-08-30 01:42:09 +00004726
Craig Topper4f12f102014-03-12 06:41:41 +00004727 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004728 if (getABIInfo().isEABI()) return 88;
4729 return TargetCodeGenInfo::getSizeOfUnwindException();
4730 }
Tim Northovera484bc02013-10-01 14:34:25 +00004731
Eric Christopher162c91c2015-06-05 22:03:00 +00004732 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004733 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004734 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4735 if (!FD)
4736 return;
4737
4738 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4739 if (!Attr)
4740 return;
4741
4742 const char *Kind;
4743 switch (Attr->getInterrupt()) {
4744 case ARMInterruptAttr::Generic: Kind = ""; break;
4745 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4746 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4747 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4748 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4749 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4750 }
4751
4752 llvm::Function *Fn = cast<llvm::Function>(GV);
4753
4754 Fn->addFnAttr("interrupt", Kind);
4755
4756 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4757 return;
4758
4759 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4760 // however this is not necessarily true on taking any interrupt. Instruct
4761 // the backend to perform a realignment as part of the function prologue.
4762 llvm::AttrBuilder B;
4763 B.addStackAlignmentAttr(8);
4764 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4765 llvm::AttributeSet::get(CGM.getLLVMContext(),
4766 llvm::AttributeSet::FunctionIndex,
4767 B));
4768 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004769};
4770
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004771class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4772 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4773 CodeGen::CodeGenModule &CGM) const;
4774
4775public:
4776 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4777 : ARMTargetCodeGenInfo(CGT, K) {}
4778
Eric Christopher162c91c2015-06-05 22:03:00 +00004779 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004780 CodeGen::CodeGenModule &CGM) const override;
4781};
4782
4783void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4784 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4785 if (!isa<FunctionDecl>(D))
4786 return;
4787 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4788 return;
4789
4790 llvm::Function *F = cast<llvm::Function>(GV);
4791 F->addFnAttr("stack-probe-size",
4792 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4793}
4794
Eric Christopher162c91c2015-06-05 22:03:00 +00004795void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004796 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004797 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004798 addStackProbeSizeTargetAttribute(D, GV, CGM);
4799}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004800}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004801
Chris Lattner22326a12010-07-29 02:31:05 +00004802void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004803 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004804 FI.getReturnInfo() =
4805 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004806
Tim Northoverbc784d12015-02-24 17:22:40 +00004807 for (auto &I : FI.arguments())
4808 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004809
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004810 // Always honor user-specified calling convention.
4811 if (FI.getCallingConvention() != llvm::CallingConv::C)
4812 return;
4813
John McCall882987f2013-02-28 19:01:20 +00004814 llvm::CallingConv::ID cc = getRuntimeCC();
4815 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004816 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004817}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004818
John McCall882987f2013-02-28 19:01:20 +00004819/// Return the default calling convention that LLVM will use.
4820llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4821 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004822 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004823 return llvm::CallingConv::ARM_AAPCS_VFP;
4824 else if (isEABI())
4825 return llvm::CallingConv::ARM_AAPCS;
4826 else
4827 return llvm::CallingConv::ARM_APCS;
4828}
4829
4830/// Return the calling convention that our ABI would like us to use
4831/// as the C calling convention.
4832llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004833 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004834 case APCS: return llvm::CallingConv::ARM_APCS;
4835 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4836 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004837 }
John McCall882987f2013-02-28 19:01:20 +00004838 llvm_unreachable("bad ABI kind");
4839}
4840
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004841void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004842 assert(getRuntimeCC() == llvm::CallingConv::C);
4843
4844 // Don't muddy up the IR with a ton of explicit annotations if
4845 // they'd just match what LLVM will infer from the triple.
4846 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4847 if (abiCC != getLLVMDefaultCC())
4848 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004849
4850 BuiltinCC = (getABIKind() == APCS ?
4851 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004852}
4853
Tim Northoverbc784d12015-02-24 17:22:40 +00004854ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4855 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004856 // 6.1.2.1 The following argument types are VFP CPRCs:
4857 // A single-precision floating-point type (including promoted
4858 // half-precision types); A double-precision floating-point type;
4859 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4860 // with a Base Type of a single- or double-precision floating-point type,
4861 // 64-bit containerized vectors or 128-bit containerized vectors with one
4862 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004863 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004864
Reid Klecknerb1be6832014-11-15 01:41:41 +00004865 Ty = useFirstFieldIfTransparentUnion(Ty);
4866
Manman Renfef9e312012-10-16 19:18:39 +00004867 // Handle illegal vector types here.
4868 if (isIllegalVectorType(Ty)) {
4869 uint64_t Size = getContext().getTypeSize(Ty);
4870 if (Size <= 32) {
4871 llvm::Type *ResType =
4872 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004873 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004874 }
4875 if (Size == 64) {
4876 llvm::Type *ResType = llvm::VectorType::get(
4877 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004878 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004879 }
4880 if (Size == 128) {
4881 llvm::Type *ResType = llvm::VectorType::get(
4882 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004883 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004884 }
John McCall7f416cc2015-09-08 08:05:57 +00004885 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00004886 }
4887
Oliver Stannarddc2854c2015-09-03 12:40:58 +00004888 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
4889 // unspecified. This is not done for OpenCL as it handles the half type
4890 // natively, and does not need to interwork with AAPCS code.
4891 if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
4892 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
4893 llvm::Type::getFloatTy(getVMContext()) :
4894 llvm::Type::getInt32Ty(getVMContext());
4895 return ABIArgInfo::getDirect(ResType);
4896 }
4897
John McCalla1dee5302010-08-22 10:59:02 +00004898 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004899 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004900 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004901 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004902 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004903
Tim Northover5a1558e2014-11-07 22:30:50 +00004904 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4905 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004906 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004907
Oliver Stannard405bded2014-02-11 09:25:50 +00004908 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004909 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004910 }
Tim Northover1060eae2013-06-21 22:49:34 +00004911
Daniel Dunbar09d33622009-09-14 21:54:03 +00004912 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004913 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004914 return ABIArgInfo::getIgnore();
4915
Tim Northover5a1558e2014-11-07 22:30:50 +00004916 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004917 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4918 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004919 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004920 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004921 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004922 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004923 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004924 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004925 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004926 }
4927
Manman Ren6c30e132012-08-13 21:23:55 +00004928 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004929 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4930 // most 8-byte. We realign the indirect argument if type alignment is bigger
4931 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004932 uint64_t ABIAlign = 4;
4933 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4934 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004935 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004936 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004937
Manman Ren8cd99812012-11-06 04:58:01 +00004938 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
John McCall7f416cc2015-09-08 08:05:57 +00004939 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4940 /*ByVal=*/true,
4941 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004942 }
4943
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004944 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004945 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004946 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004947 // FIXME: Try to match the types of the arguments more accurately where
4948 // we can.
4949 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004950 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4951 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004952 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004953 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4954 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004955 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004956
Tim Northover5a1558e2014-11-07 22:30:50 +00004957 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004958}
4959
Chris Lattner458b2aa2010-07-29 02:16:43 +00004960static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004961 llvm::LLVMContext &VMContext) {
4962 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4963 // is called integer-like if its size is less than or equal to one word, and
4964 // the offset of each of its addressable sub-fields is zero.
4965
4966 uint64_t Size = Context.getTypeSize(Ty);
4967
4968 // Check that the type fits in a word.
4969 if (Size > 32)
4970 return false;
4971
4972 // FIXME: Handle vector types!
4973 if (Ty->isVectorType())
4974 return false;
4975
Daniel Dunbard53bac72009-09-14 02:20:34 +00004976 // Float types are never treated as "integer like".
4977 if (Ty->isRealFloatingType())
4978 return false;
4979
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004980 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004981 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004982 return true;
4983
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004984 // Small complex integer types are "integer like".
4985 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4986 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004987
4988 // Single element and zero sized arrays should be allowed, by the definition
4989 // above, but they are not.
4990
4991 // Otherwise, it must be a record type.
4992 const RecordType *RT = Ty->getAs<RecordType>();
4993 if (!RT) return false;
4994
4995 // Ignore records with flexible arrays.
4996 const RecordDecl *RD = RT->getDecl();
4997 if (RD->hasFlexibleArrayMember())
4998 return false;
4999
5000 // Check that all sub-fields are at offset 0, and are themselves "integer
5001 // like".
5002 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5003
5004 bool HadField = false;
5005 unsigned idx = 0;
5006 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5007 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005008 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005009
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005010 // Bit-fields are not addressable, we only need to verify they are "integer
5011 // like". We still have to disallow a subsequent non-bitfield, for example:
5012 // struct { int : 0; int x }
5013 // is non-integer like according to gcc.
5014 if (FD->isBitField()) {
5015 if (!RD->isUnion())
5016 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005017
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005018 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5019 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005020
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005021 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005022 }
5023
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005024 // Check if this field is at offset 0.
5025 if (Layout.getFieldOffset(idx) != 0)
5026 return false;
5027
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005028 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5029 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005030
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005031 // Only allow at most one field in a structure. This doesn't match the
5032 // wording above, but follows gcc in situations with a field following an
5033 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005034 if (!RD->isUnion()) {
5035 if (HadField)
5036 return false;
5037
5038 HadField = true;
5039 }
5040 }
5041
5042 return true;
5043}
5044
Oliver Stannard405bded2014-02-11 09:25:50 +00005045ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5046 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00005047 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005048
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005049 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005050 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005051
Daniel Dunbar19964db2010-09-23 01:54:32 +00005052 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005053 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005054 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005055 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005056
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005057 // __fp16 gets returned as if it were an int or float, but with the top 16
5058 // bits unspecified. This is not done for OpenCL as it handles the half type
5059 // natively, and does not need to interwork with AAPCS code.
5060 if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
5061 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5062 llvm::Type::getFloatTy(getVMContext()) :
5063 llvm::Type::getInt32Ty(getVMContext());
5064 return ABIArgInfo::getDirect(ResType);
5065 }
5066
John McCalla1dee5302010-08-22 10:59:02 +00005067 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005068 // Treat an enum type as its underlying type.
5069 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5070 RetTy = EnumTy->getDecl()->getIntegerType();
5071
Tim Northover5a1558e2014-11-07 22:30:50 +00005072 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5073 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005074 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005075
5076 // Are we following APCS?
5077 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005078 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005079 return ABIArgInfo::getIgnore();
5080
Daniel Dunbareedf1512010-02-01 23:31:19 +00005081 // Complex types are all returned as packed integers.
5082 //
5083 // FIXME: Consider using 2 x vector types if the back end handles them
5084 // correctly.
5085 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005086 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5087 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005088
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005089 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005090 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005091 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005092 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005093 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005094 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005095 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005096 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5097 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005098 }
5099
5100 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005101 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005102 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005103
5104 // Otherwise this is an AAPCS variant.
5105
Chris Lattner458b2aa2010-07-29 02:16:43 +00005106 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005107 return ABIArgInfo::getIgnore();
5108
Bob Wilson1d9269a2011-11-02 04:51:36 +00005109 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005110 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005111 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005112 uint64_t Members;
5113 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005114 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005115 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005116 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005117 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005118 }
5119
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005120 // Aggregates <= 4 bytes are returned in r0; other aggregates
5121 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005122 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005123 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005124 if (getDataLayout().isBigEndian())
5125 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005126 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005127
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005128 // Return in the smallest viable integer type.
5129 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005130 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005131 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005132 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5133 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005134 }
5135
John McCall7f416cc2015-09-08 08:05:57 +00005136 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005137}
5138
Manman Renfef9e312012-10-16 19:18:39 +00005139/// isIllegalVector - check whether Ty is an illegal vector type.
5140bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5141 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5142 // Check whether VT is legal.
5143 unsigned NumElements = VT->getNumElements();
5144 uint64_t Size = getContext().getTypeSize(VT);
5145 // NumElements should be power of 2.
5146 if ((NumElements & (NumElements - 1)) != 0)
5147 return true;
5148 // Size should be greater than 32 bits.
5149 return Size <= 32;
5150 }
5151 return false;
5152}
5153
Reid Klecknere9f6a712014-10-31 17:10:41 +00005154bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5155 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5156 // double, or 64-bit or 128-bit vectors.
5157 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5158 if (BT->getKind() == BuiltinType::Float ||
5159 BT->getKind() == BuiltinType::Double ||
5160 BT->getKind() == BuiltinType::LongDouble)
5161 return true;
5162 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5163 unsigned VecSize = getContext().getTypeSize(VT);
5164 if (VecSize == 64 || VecSize == 128)
5165 return true;
5166 }
5167 return false;
5168}
5169
5170bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5171 uint64_t Members) const {
5172 return Members <= 4;
5173}
5174
John McCall7f416cc2015-09-08 08:05:57 +00005175Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5176 QualType Ty) const {
5177 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005178
John McCall7f416cc2015-09-08 08:05:57 +00005179 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005180 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005181 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5182 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5183 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005184 }
5185
John McCall7f416cc2015-09-08 08:05:57 +00005186 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5187 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005188
John McCall7f416cc2015-09-08 08:05:57 +00005189 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5190 bool IsIndirect = false;
5191 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5192 IsIndirect = true;
5193
5194 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005195 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5196 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005197 // Our callers should be prepared to handle an under-aligned address.
5198 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5199 getABIKind() == ARMABIInfo::AAPCS) {
5200 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5201 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
5202 } else {
5203 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005204 }
John McCall7f416cc2015-09-08 08:05:57 +00005205 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005206
John McCall7f416cc2015-09-08 08:05:57 +00005207 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5208 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005209}
5210
Chris Lattner0cf24192010-06-28 20:05:43 +00005211//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005212// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005213//===----------------------------------------------------------------------===//
5214
5215namespace {
5216
Justin Holewinski83e96682012-05-24 17:43:12 +00005217class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005218public:
Justin Holewinski36837432013-03-30 14:38:24 +00005219 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005220
5221 ABIArgInfo classifyReturnType(QualType RetTy) const;
5222 ABIArgInfo classifyArgumentType(QualType Ty) const;
5223
Craig Topper4f12f102014-03-12 06:41:41 +00005224 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005225 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5226 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005227};
5228
Justin Holewinski83e96682012-05-24 17:43:12 +00005229class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005230public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005231 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5232 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005233
Eric Christopher162c91c2015-06-05 22:03:00 +00005234 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005235 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005236private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005237 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5238 // resulting MDNode to the nvvm.annotations MDNode.
5239 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005240};
5241
Justin Holewinski83e96682012-05-24 17:43:12 +00005242ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005243 if (RetTy->isVoidType())
5244 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005245
5246 // note: this is different from default ABI
5247 if (!RetTy->isScalarType())
5248 return ABIArgInfo::getDirect();
5249
5250 // Treat an enum type as its underlying type.
5251 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5252 RetTy = EnumTy->getDecl()->getIntegerType();
5253
5254 return (RetTy->isPromotableIntegerType() ?
5255 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005256}
5257
Justin Holewinski83e96682012-05-24 17:43:12 +00005258ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005259 // Treat an enum type as its underlying type.
5260 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5261 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005262
Eli Bendersky95338a02014-10-29 13:43:21 +00005263 // Return aggregates type as indirect by value
5264 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005265 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005266
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005267 return (Ty->isPromotableIntegerType() ?
5268 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005269}
5270
Justin Holewinski83e96682012-05-24 17:43:12 +00005271void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005272 if (!getCXXABI().classifyReturnType(FI))
5273 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005274 for (auto &I : FI.arguments())
5275 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005276
5277 // Always honor user-specified calling convention.
5278 if (FI.getCallingConvention() != llvm::CallingConv::C)
5279 return;
5280
John McCall882987f2013-02-28 19:01:20 +00005281 FI.setEffectiveCallingConvention(getRuntimeCC());
5282}
5283
John McCall7f416cc2015-09-08 08:05:57 +00005284Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5285 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005286 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005287}
5288
Justin Holewinski83e96682012-05-24 17:43:12 +00005289void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005290setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005291 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005292 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5293 if (!FD) return;
5294
5295 llvm::Function *F = cast<llvm::Function>(GV);
5296
5297 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005298 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005299 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005300 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005301 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005302 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005303 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5304 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005305 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005306 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005307 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005308 }
Justin Holewinski38031972011-10-05 17:58:44 +00005309
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005310 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005311 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005312 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005313 // __global__ functions cannot be called from the device, we do not
5314 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005315 if (FD->hasAttr<CUDAGlobalAttr>()) {
5316 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5317 addNVVMMetadata(F, "kernel", 1);
5318 }
Artem Belevich7093e402015-04-21 22:55:54 +00005319 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005320 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005321 llvm::APSInt MaxThreads(32);
5322 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5323 if (MaxThreads > 0)
5324 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5325
5326 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5327 // not specified in __launch_bounds__ or if the user specified a 0 value,
5328 // we don't have to add a PTX directive.
5329 if (Attr->getMinBlocks()) {
5330 llvm::APSInt MinBlocks(32);
5331 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5332 if (MinBlocks > 0)
5333 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5334 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005335 }
5336 }
Justin Holewinski38031972011-10-05 17:58:44 +00005337 }
5338}
5339
Eli Benderskye06a2c42014-04-15 16:57:05 +00005340void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5341 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005342 llvm::Module *M = F->getParent();
5343 llvm::LLVMContext &Ctx = M->getContext();
5344
5345 // Get "nvvm.annotations" metadata node
5346 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5347
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005348 llvm::Metadata *MDVals[] = {
5349 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5350 llvm::ConstantAsMetadata::get(
5351 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005352 // Append metadata to nvvm.annotations
5353 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5354}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005355}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005356
5357//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005358// SystemZ ABI Implementation
5359//===----------------------------------------------------------------------===//
5360
5361namespace {
5362
5363class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005364 bool HasVector;
5365
Ulrich Weigand47445072013-05-06 16:26:41 +00005366public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005367 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5368 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005369
5370 bool isPromotableIntegerType(QualType Ty) const;
5371 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005372 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005373 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005374 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005375
5376 ABIArgInfo classifyReturnType(QualType RetTy) const;
5377 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5378
Craig Topper4f12f102014-03-12 06:41:41 +00005379 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005380 if (!getCXXABI().classifyReturnType(FI))
5381 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005382 for (auto &I : FI.arguments())
5383 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005384 }
5385
John McCall7f416cc2015-09-08 08:05:57 +00005386 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5387 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005388};
5389
5390class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5391public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005392 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5393 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005394};
5395
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005396}
Ulrich Weigand47445072013-05-06 16:26:41 +00005397
5398bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5399 // Treat an enum type as its underlying type.
5400 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5401 Ty = EnumTy->getDecl()->getIntegerType();
5402
5403 // Promotable integer types are required to be promoted by the ABI.
5404 if (Ty->isPromotableIntegerType())
5405 return true;
5406
5407 // 32-bit values must also be promoted.
5408 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5409 switch (BT->getKind()) {
5410 case BuiltinType::Int:
5411 case BuiltinType::UInt:
5412 return true;
5413 default:
5414 return false;
5415 }
5416 return false;
5417}
5418
5419bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005420 return (Ty->isAnyComplexType() ||
5421 Ty->isVectorType() ||
5422 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005423}
5424
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005425bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5426 return (HasVector &&
5427 Ty->isVectorType() &&
5428 getContext().getTypeSize(Ty) <= 128);
5429}
5430
Ulrich Weigand47445072013-05-06 16:26:41 +00005431bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5432 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5433 switch (BT->getKind()) {
5434 case BuiltinType::Float:
5435 case BuiltinType::Double:
5436 return true;
5437 default:
5438 return false;
5439 }
5440
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005441 return false;
5442}
5443
5444QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005445 if (const RecordType *RT = Ty->getAsStructureType()) {
5446 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005447 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005448
5449 // If this is a C++ record, check the bases first.
5450 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005451 for (const auto &I : CXXRD->bases()) {
5452 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005453
5454 // Empty bases don't affect things either way.
5455 if (isEmptyRecord(getContext(), Base, true))
5456 continue;
5457
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005458 if (!Found.isNull())
5459 return Ty;
5460 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005461 }
5462
5463 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005464 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005465 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005466 // Unlike isSingleElementStruct(), empty structure and array fields
5467 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005468 if (getContext().getLangOpts().CPlusPlus &&
5469 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5470 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005471
5472 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005473 // Nested structures still do though.
5474 if (!Found.isNull())
5475 return Ty;
5476 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005477 }
5478
5479 // Unlike isSingleElementStruct(), trailing padding is allowed.
5480 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005481 if (!Found.isNull())
5482 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005483 }
5484
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005485 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005486}
5487
John McCall7f416cc2015-09-08 08:05:57 +00005488Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5489 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005490 // Assume that va_list type is correct; should be pointer to LLVM type:
5491 // struct {
5492 // i64 __gpr;
5493 // i64 __fpr;
5494 // i8 *__overflow_arg_area;
5495 // i8 *__reg_save_area;
5496 // };
5497
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005498 // Every non-vector argument occupies 8 bytes and is passed by preference
5499 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5500 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005501 Ty = getContext().getCanonicalType(Ty);
5502 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005503 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005504 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005505 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005506 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005507 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005508 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005509 CharUnits UnpaddedSize;
5510 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005511 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005512 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5513 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005514 } else {
5515 if (AI.getCoerceToType())
5516 ArgTy = AI.getCoerceToType();
5517 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005518 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005519 UnpaddedSize = TyInfo.first;
5520 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005521 }
John McCall7f416cc2015-09-08 08:05:57 +00005522 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5523 if (IsVector && UnpaddedSize > PaddedSize)
5524 PaddedSize = CharUnits::fromQuantity(16);
5525 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005526
John McCall7f416cc2015-09-08 08:05:57 +00005527 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005528
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005529 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005530 llvm::Value *PaddedSizeV =
5531 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005532
5533 if (IsVector) {
5534 // Work out the address of a vector argument on the stack.
5535 // Vector arguments are always passed in the high bits of a
5536 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005537 Address OverflowArgAreaPtr =
5538 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005539 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005540 Address OverflowArgArea =
5541 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5542 TyInfo.second);
5543 Address MemAddr =
5544 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005545
5546 // Update overflow_arg_area_ptr pointer
5547 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005548 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5549 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005550 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5551
5552 return MemAddr;
5553 }
5554
John McCall7f416cc2015-09-08 08:05:57 +00005555 assert(PaddedSize.getQuantity() == 8);
5556
5557 unsigned MaxRegs, RegCountField, RegSaveIndex;
5558 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005559 if (InFPRs) {
5560 MaxRegs = 4; // Maximum of 4 FPR arguments
5561 RegCountField = 1; // __fpr
5562 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005563 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005564 } else {
5565 MaxRegs = 5; // Maximum of 5 GPR arguments
5566 RegCountField = 0; // __gpr
5567 RegSaveIndex = 2; // save offset for r2
5568 RegPadding = Padding; // values are passed in the low bits of a GPR
5569 }
5570
John McCall7f416cc2015-09-08 08:05:57 +00005571 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5572 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5573 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005574 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005575 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5576 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005577 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005578
5579 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5580 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5581 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5582 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5583
5584 // Emit code to load the value if it was passed in registers.
5585 CGF.EmitBlock(InRegBlock);
5586
5587 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005588 llvm::Value *ScaledRegCount =
5589 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5590 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005591 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5592 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005593 llvm::Value *RegOffset =
5594 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005595 Address RegSaveAreaPtr =
5596 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5597 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005598 llvm::Value *RegSaveArea =
5599 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005600 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5601 "raw_reg_addr"),
5602 PaddedSize);
5603 Address RegAddr =
5604 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005605
5606 // Update the register count
5607 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5608 llvm::Value *NewRegCount =
5609 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5610 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5611 CGF.EmitBranch(ContBlock);
5612
5613 // Emit code to load the value if it was passed in memory.
5614 CGF.EmitBlock(InMemBlock);
5615
5616 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005617 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5618 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5619 Address OverflowArgArea =
5620 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5621 PaddedSize);
5622 Address RawMemAddr =
5623 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5624 Address MemAddr =
5625 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005626
5627 // Update overflow_arg_area_ptr pointer
5628 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005629 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5630 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005631 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5632 CGF.EmitBranch(ContBlock);
5633
5634 // Return the appropriate result.
5635 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005636 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5637 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005638
5639 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005640 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5641 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005642
5643 return ResAddr;
5644}
5645
Ulrich Weigand47445072013-05-06 16:26:41 +00005646ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5647 if (RetTy->isVoidType())
5648 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005649 if (isVectorArgumentType(RetTy))
5650 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005651 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00005652 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005653 return (isPromotableIntegerType(RetTy) ?
5654 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5655}
5656
5657ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5658 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005659 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00005660 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00005661
5662 // Integers and enums are extended to full register width.
5663 if (isPromotableIntegerType(Ty))
5664 return ABIArgInfo::getExtend();
5665
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005666 // Handle vector types and vector-like structure types. Note that
5667 // as opposed to float-like structure types, we do not allow any
5668 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005669 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005670 QualType SingleElementTy = GetSingleElementType(Ty);
5671 if (isVectorArgumentType(SingleElementTy) &&
5672 getContext().getTypeSize(SingleElementTy) == Size)
5673 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5674
5675 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005676 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00005677 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005678
5679 // Handle small structures.
5680 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5681 // Structures with flexible arrays have variable length, so really
5682 // fail the size test above.
5683 const RecordDecl *RD = RT->getDecl();
5684 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00005685 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005686
5687 // The structure is passed as an unextended integer, a float, or a double.
5688 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005689 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005690 assert(Size == 32 || Size == 64);
5691 if (Size == 32)
5692 PassTy = llvm::Type::getFloatTy(getVMContext());
5693 else
5694 PassTy = llvm::Type::getDoubleTy(getVMContext());
5695 } else
5696 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5697 return ABIArgInfo::getDirect(PassTy);
5698 }
5699
5700 // Non-structure compounds are passed indirectly.
5701 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005702 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005703
Craig Topper8a13c412014-05-21 05:09:00 +00005704 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005705}
5706
5707//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005708// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005709//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005710
5711namespace {
5712
5713class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5714public:
Chris Lattner2b037972010-07-29 02:01:43 +00005715 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5716 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005717 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005718 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005719};
5720
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005721}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005722
Eric Christopher162c91c2015-06-05 22:03:00 +00005723void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005724 llvm::GlobalValue *GV,
5725 CodeGen::CodeGenModule &M) const {
5726 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5727 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5728 // Handle 'interrupt' attribute:
5729 llvm::Function *F = cast<llvm::Function>(GV);
5730
5731 // Step 1: Set ISR calling convention.
5732 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5733
5734 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005735 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005736
5737 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005738 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005739 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5740 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005741 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005742 }
5743}
5744
Chris Lattner0cf24192010-06-28 20:05:43 +00005745//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005746// MIPS ABI Implementation. This works for both little-endian and
5747// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005748//===----------------------------------------------------------------------===//
5749
John McCall943fae92010-05-27 06:19:26 +00005750namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005751class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005752 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005753 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5754 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005755 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005756 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005757 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005758 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005759public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005760 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005761 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005762 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005763
5764 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005765 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005766 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005767 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5768 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005769 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005770};
5771
John McCall943fae92010-05-27 06:19:26 +00005772class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005773 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005774public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005775 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5776 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005777 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005778
Craig Topper4f12f102014-03-12 06:41:41 +00005779 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005780 return 29;
5781 }
5782
Eric Christopher162c91c2015-06-05 22:03:00 +00005783 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005784 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005785 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5786 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005787 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005788 if (FD->hasAttr<Mips16Attr>()) {
5789 Fn->addFnAttr("mips16");
5790 }
5791 else if (FD->hasAttr<NoMips16Attr>()) {
5792 Fn->addFnAttr("nomips16");
5793 }
Reed Kotler373feca2013-01-16 17:10:28 +00005794 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005795
John McCall943fae92010-05-27 06:19:26 +00005796 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005797 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005798
Craig Topper4f12f102014-03-12 06:41:41 +00005799 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005800 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005801 }
John McCall943fae92010-05-27 06:19:26 +00005802};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005803}
John McCall943fae92010-05-27 06:19:26 +00005804
Eric Christopher7565e0d2015-05-29 23:09:49 +00005805void MipsABIInfo::CoerceToIntArgs(
5806 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005807 llvm::IntegerType *IntTy =
5808 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005809
5810 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5811 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5812 ArgList.push_back(IntTy);
5813
5814 // If necessary, add one more integer type to ArgList.
5815 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5816
5817 if (R)
5818 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005819}
5820
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005821// In N32/64, an aligned double precision floating point field is passed in
5822// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005823llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005824 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5825
5826 if (IsO32) {
5827 CoerceToIntArgs(TySize, ArgList);
5828 return llvm::StructType::get(getVMContext(), ArgList);
5829 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005830
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005831 if (Ty->isComplexType())
5832 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005833
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005834 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005835
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005836 // Unions/vectors are passed in integer registers.
5837 if (!RT || !RT->isStructureOrClassType()) {
5838 CoerceToIntArgs(TySize, ArgList);
5839 return llvm::StructType::get(getVMContext(), ArgList);
5840 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005841
5842 const RecordDecl *RD = RT->getDecl();
5843 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005844 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00005845
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005846 uint64_t LastOffset = 0;
5847 unsigned idx = 0;
5848 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5849
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005850 // Iterate over fields in the struct/class and check if there are any aligned
5851 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005852 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5853 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005854 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005855 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5856
5857 if (!BT || BT->getKind() != BuiltinType::Double)
5858 continue;
5859
5860 uint64_t Offset = Layout.getFieldOffset(idx);
5861 if (Offset % 64) // Ignore doubles that are not aligned.
5862 continue;
5863
5864 // Add ((Offset - LastOffset) / 64) args of type i64.
5865 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5866 ArgList.push_back(I64);
5867
5868 // Add double type.
5869 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5870 LastOffset = Offset + 64;
5871 }
5872
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005873 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5874 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005875
5876 return llvm::StructType::get(getVMContext(), ArgList);
5877}
5878
Akira Hatanakaddd66342013-10-29 18:41:15 +00005879llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5880 uint64_t Offset) const {
5881 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005882 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005883
Akira Hatanakaddd66342013-10-29 18:41:15 +00005884 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005885}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005886
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005887ABIArgInfo
5888MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005889 Ty = useFirstFieldIfTransparentUnion(Ty);
5890
Akira Hatanaka1632af62012-01-09 19:31:25 +00005891 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005892 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005893 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005894
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005895 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5896 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005897 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5898 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005899
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005900 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005901 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005902 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005903 return ABIArgInfo::getIgnore();
5904
Mark Lacey3825e832013-10-06 01:33:34 +00005905 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005906 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00005907 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005908 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005909
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005910 // If we have reached here, aggregates are passed directly by coercing to
5911 // another structure type. Padding is inserted if the offset of the
5912 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005913 ABIArgInfo ArgInfo =
5914 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5915 getPaddingType(OrigOffset, CurrOffset));
5916 ArgInfo.setInReg(true);
5917 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005918 }
5919
5920 // Treat an enum type as its underlying type.
5921 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5922 Ty = EnumTy->getDecl()->getIntegerType();
5923
Daniel Sanders5b445b32014-10-24 14:42:42 +00005924 // All integral types are promoted to the GPR width.
5925 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005926 return ABIArgInfo::getExtend();
5927
Akira Hatanakaddd66342013-10-29 18:41:15 +00005928 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005929 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005930}
5931
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005932llvm::Type*
5933MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005934 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005935 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005936
Akira Hatanakab6f74432012-02-09 18:49:26 +00005937 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005938 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005939 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5940 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005941
Akira Hatanakab6f74432012-02-09 18:49:26 +00005942 // N32/64 returns struct/classes in floating point registers if the
5943 // following conditions are met:
5944 // 1. The size of the struct/class is no larger than 128-bit.
5945 // 2. The struct/class has one or two fields all of which are floating
5946 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005947 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00005948 //
5949 // Any other composite results are returned in integer registers.
5950 //
5951 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5952 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5953 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005954 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005955
Akira Hatanakab6f74432012-02-09 18:49:26 +00005956 if (!BT || !BT->isFloatingPoint())
5957 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005958
David Blaikie2d7c57e2012-04-30 02:36:29 +00005959 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005960 }
5961
5962 if (b == e)
5963 return llvm::StructType::get(getVMContext(), RTList,
5964 RD->hasAttr<PackedAttr>());
5965
5966 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005967 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005968 }
5969
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005970 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005971 return llvm::StructType::get(getVMContext(), RTList);
5972}
5973
Akira Hatanakab579fe52011-06-02 00:09:17 +00005974ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005975 uint64_t Size = getContext().getTypeSize(RetTy);
5976
Daniel Sandersed39f582014-09-04 13:28:14 +00005977 if (RetTy->isVoidType())
5978 return ABIArgInfo::getIgnore();
5979
5980 // O32 doesn't treat zero-sized structs differently from other structs.
5981 // However, N32/N64 ignores zero sized return values.
5982 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005983 return ABIArgInfo::getIgnore();
5984
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005985 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005986 if (Size <= 128) {
5987 if (RetTy->isAnyComplexType())
5988 return ABIArgInfo::getDirect();
5989
Daniel Sanderse5018b62014-09-04 15:05:39 +00005990 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005991 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005992 if (!IsO32 ||
5993 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5994 ABIArgInfo ArgInfo =
5995 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5996 ArgInfo.setInReg(true);
5997 return ArgInfo;
5998 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005999 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006000
John McCall7f416cc2015-09-08 08:05:57 +00006001 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006002 }
6003
6004 // Treat an enum type as its underlying type.
6005 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6006 RetTy = EnumTy->getDecl()->getIntegerType();
6007
6008 return (RetTy->isPromotableIntegerType() ?
6009 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6010}
6011
6012void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006013 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006014 if (!getCXXABI().classifyReturnType(FI))
6015 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006016
Eric Christopher7565e0d2015-05-29 23:09:49 +00006017 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006018 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006019
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006020 for (auto &I : FI.arguments())
6021 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006022}
6023
John McCall7f416cc2015-09-08 08:05:57 +00006024Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6025 QualType OrigTy) const {
6026 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006027
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006028 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6029 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006030 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006031 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006032 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006033 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006034 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006035 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006036 DidPromote = true;
6037 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6038 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006039 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006040
John McCall7f416cc2015-09-08 08:05:57 +00006041 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006042
John McCall7f416cc2015-09-08 08:05:57 +00006043 // The alignment of things in the argument area is never larger than
6044 // StackAlignInBytes.
6045 TyInfo.second =
6046 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6047
6048 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6049 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6050
6051 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6052 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6053
6054
6055 // If there was a promotion, "unpromote" into a temporary.
6056 // TODO: can we just use a pointer into a subset of the original slot?
6057 if (DidPromote) {
6058 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6059 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6060
6061 // Truncate down to the right width.
6062 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6063 : CGF.IntPtrTy);
6064 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6065 if (OrigTy->isPointerType())
6066 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6067
6068 CGF.Builder.CreateStore(V, Temp);
6069 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006070 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006071
John McCall7f416cc2015-09-08 08:05:57 +00006072 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006073}
6074
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006075bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6076 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006077
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006078 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6079 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6080 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006081
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006082 return false;
6083}
6084
John McCall943fae92010-05-27 06:19:26 +00006085bool
6086MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6087 llvm::Value *Address) const {
6088 // This information comes from gcc's implementation, which seems to
6089 // as canonical as it gets.
6090
John McCall943fae92010-05-27 06:19:26 +00006091 // Everything on MIPS is 4 bytes. Double-precision FP registers
6092 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006093 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006094
6095 // 0-31 are the general purpose registers, $0 - $31.
6096 // 32-63 are the floating-point registers, $f0 - $f31.
6097 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6098 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006099 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006100
6101 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6102 // They are one bit wide and ignored here.
6103
6104 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6105 // (coprocessor 1 is the FP unit)
6106 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6107 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6108 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006109 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006110 return false;
6111}
6112
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006113//===----------------------------------------------------------------------===//
6114// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006115// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006116// handling.
6117//===----------------------------------------------------------------------===//
6118
6119namespace {
6120
6121class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6122public:
6123 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6124 : DefaultTargetCodeGenInfo(CGT) {}
6125
Eric Christopher162c91c2015-06-05 22:03:00 +00006126 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006127 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006128};
6129
Eric Christopher162c91c2015-06-05 22:03:00 +00006130void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006131 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006132 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6133 if (!FD) return;
6134
6135 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006136
David Blaikiebbafb8a2012-03-11 07:00:24 +00006137 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006138 if (FD->hasAttr<OpenCLKernelAttr>()) {
6139 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006140 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006141 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6142 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006143 // Convert the reqd_work_group_size() attributes to metadata.
6144 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006145 llvm::NamedMDNode *OpenCLMetadata =
6146 M.getModule().getOrInsertNamedMetadata(
6147 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006148
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006149 SmallVector<llvm::Metadata *, 5> Operands;
6150 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006151
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006152 Operands.push_back(
6153 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6154 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6155 Operands.push_back(
6156 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6157 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6158 Operands.push_back(
6159 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6160 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006161
Eric Christopher7565e0d2015-05-29 23:09:49 +00006162 // Add a boolean constant operand for "required" (true) or "hint"
6163 // (false) for implementing the work_group_size_hint attr later.
6164 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006165 Operands.push_back(
6166 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006167 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6168 }
6169 }
6170 }
6171}
6172
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006173}
John McCall943fae92010-05-27 06:19:26 +00006174
Tony Linthicum76329bf2011-12-12 21:14:55 +00006175//===----------------------------------------------------------------------===//
6176// Hexagon ABI Implementation
6177//===----------------------------------------------------------------------===//
6178
6179namespace {
6180
6181class HexagonABIInfo : public ABIInfo {
6182
6183
6184public:
6185 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6186
6187private:
6188
6189 ABIArgInfo classifyReturnType(QualType RetTy) const;
6190 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6191
Craig Topper4f12f102014-03-12 06:41:41 +00006192 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006193
John McCall7f416cc2015-09-08 08:05:57 +00006194 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6195 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006196};
6197
6198class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6199public:
6200 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6201 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6202
Craig Topper4f12f102014-03-12 06:41:41 +00006203 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006204 return 29;
6205 }
6206};
6207
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006208}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006209
6210void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006211 if (!getCXXABI().classifyReturnType(FI))
6212 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006213 for (auto &I : FI.arguments())
6214 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006215}
6216
6217ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6218 if (!isAggregateTypeForABI(Ty)) {
6219 // Treat an enum type as its underlying type.
6220 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6221 Ty = EnumTy->getDecl()->getIntegerType();
6222
6223 return (Ty->isPromotableIntegerType() ?
6224 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6225 }
6226
6227 // Ignore empty records.
6228 if (isEmptyRecord(getContext(), Ty, true))
6229 return ABIArgInfo::getIgnore();
6230
Mark Lacey3825e832013-10-06 01:33:34 +00006231 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006232 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006233
6234 uint64_t Size = getContext().getTypeSize(Ty);
6235 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006236 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006237 // Pass in the smallest viable integer type.
6238 else if (Size > 32)
6239 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6240 else if (Size > 16)
6241 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6242 else if (Size > 8)
6243 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6244 else
6245 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6246}
6247
6248ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6249 if (RetTy->isVoidType())
6250 return ABIArgInfo::getIgnore();
6251
6252 // Large vector types should be returned via memory.
6253 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006254 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006255
6256 if (!isAggregateTypeForABI(RetTy)) {
6257 // Treat an enum type as its underlying type.
6258 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6259 RetTy = EnumTy->getDecl()->getIntegerType();
6260
6261 return (RetTy->isPromotableIntegerType() ?
6262 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6263 }
6264
Tony Linthicum76329bf2011-12-12 21:14:55 +00006265 if (isEmptyRecord(getContext(), RetTy, true))
6266 return ABIArgInfo::getIgnore();
6267
6268 // Aggregates <= 8 bytes are returned in r0; other aggregates
6269 // are returned indirectly.
6270 uint64_t Size = getContext().getTypeSize(RetTy);
6271 if (Size <= 64) {
6272 // Return in the smallest viable integer type.
6273 if (Size <= 8)
6274 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6275 if (Size <= 16)
6276 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6277 if (Size <= 32)
6278 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6279 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6280 }
6281
John McCall7f416cc2015-09-08 08:05:57 +00006282 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006283}
6284
John McCall7f416cc2015-09-08 08:05:57 +00006285Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6286 QualType Ty) const {
6287 // FIXME: Someone needs to audit that this handle alignment correctly.
6288 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6289 getContext().getTypeInfoInChars(Ty),
6290 CharUnits::fromQuantity(4),
6291 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006292}
6293
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006294//===----------------------------------------------------------------------===//
6295// AMDGPU ABI Implementation
6296//===----------------------------------------------------------------------===//
6297
6298namespace {
6299
6300class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6301public:
6302 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6303 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006304 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006305 CodeGen::CodeGenModule &M) const override;
6306};
6307
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006308}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006309
Eric Christopher162c91c2015-06-05 22:03:00 +00006310void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006311 const Decl *D,
6312 llvm::GlobalValue *GV,
6313 CodeGen::CodeGenModule &M) const {
6314 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6315 if (!FD)
6316 return;
6317
6318 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6319 llvm::Function *F = cast<llvm::Function>(GV);
6320 uint32_t NumVGPR = Attr->getNumVGPR();
6321 if (NumVGPR != 0)
6322 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6323 }
6324
6325 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6326 llvm::Function *F = cast<llvm::Function>(GV);
6327 unsigned NumSGPR = Attr->getNumSGPR();
6328 if (NumSGPR != 0)
6329 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6330 }
6331}
6332
Tony Linthicum76329bf2011-12-12 21:14:55 +00006333
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006334//===----------------------------------------------------------------------===//
6335// SPARC v9 ABI Implementation.
6336// Based on the SPARC Compliance Definition version 2.4.1.
6337//
6338// Function arguments a mapped to a nominal "parameter array" and promoted to
6339// registers depending on their type. Each argument occupies 8 or 16 bytes in
6340// the array, structs larger than 16 bytes are passed indirectly.
6341//
6342// One case requires special care:
6343//
6344// struct mixed {
6345// int i;
6346// float f;
6347// };
6348//
6349// When a struct mixed is passed by value, it only occupies 8 bytes in the
6350// parameter array, but the int is passed in an integer register, and the float
6351// is passed in a floating point register. This is represented as two arguments
6352// with the LLVM IR inreg attribute:
6353//
6354// declare void f(i32 inreg %i, float inreg %f)
6355//
6356// The code generator will only allocate 4 bytes from the parameter array for
6357// the inreg arguments. All other arguments are allocated a multiple of 8
6358// bytes.
6359//
6360namespace {
6361class SparcV9ABIInfo : public ABIInfo {
6362public:
6363 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6364
6365private:
6366 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006367 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006368 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6369 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006370
6371 // Coercion type builder for structs passed in registers. The coercion type
6372 // serves two purposes:
6373 //
6374 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6375 // in registers.
6376 // 2. Expose aligned floating point elements as first-level elements, so the
6377 // code generator knows to pass them in floating point registers.
6378 //
6379 // We also compute the InReg flag which indicates that the struct contains
6380 // aligned 32-bit floats.
6381 //
6382 struct CoerceBuilder {
6383 llvm::LLVMContext &Context;
6384 const llvm::DataLayout &DL;
6385 SmallVector<llvm::Type*, 8> Elems;
6386 uint64_t Size;
6387 bool InReg;
6388
6389 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6390 : Context(c), DL(dl), Size(0), InReg(false) {}
6391
6392 // Pad Elems with integers until Size is ToSize.
6393 void pad(uint64_t ToSize) {
6394 assert(ToSize >= Size && "Cannot remove elements");
6395 if (ToSize == Size)
6396 return;
6397
6398 // Finish the current 64-bit word.
6399 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6400 if (Aligned > Size && Aligned <= ToSize) {
6401 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6402 Size = Aligned;
6403 }
6404
6405 // Add whole 64-bit words.
6406 while (Size + 64 <= ToSize) {
6407 Elems.push_back(llvm::Type::getInt64Ty(Context));
6408 Size += 64;
6409 }
6410
6411 // Final in-word padding.
6412 if (Size < ToSize) {
6413 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6414 Size = ToSize;
6415 }
6416 }
6417
6418 // Add a floating point element at Offset.
6419 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6420 // Unaligned floats are treated as integers.
6421 if (Offset % Bits)
6422 return;
6423 // The InReg flag is only required if there are any floats < 64 bits.
6424 if (Bits < 64)
6425 InReg = true;
6426 pad(Offset);
6427 Elems.push_back(Ty);
6428 Size = Offset + Bits;
6429 }
6430
6431 // Add a struct type to the coercion type, starting at Offset (in bits).
6432 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6433 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6434 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6435 llvm::Type *ElemTy = StrTy->getElementType(i);
6436 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6437 switch (ElemTy->getTypeID()) {
6438 case llvm::Type::StructTyID:
6439 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6440 break;
6441 case llvm::Type::FloatTyID:
6442 addFloat(ElemOffset, ElemTy, 32);
6443 break;
6444 case llvm::Type::DoubleTyID:
6445 addFloat(ElemOffset, ElemTy, 64);
6446 break;
6447 case llvm::Type::FP128TyID:
6448 addFloat(ElemOffset, ElemTy, 128);
6449 break;
6450 case llvm::Type::PointerTyID:
6451 if (ElemOffset % 64 == 0) {
6452 pad(ElemOffset);
6453 Elems.push_back(ElemTy);
6454 Size += 64;
6455 }
6456 break;
6457 default:
6458 break;
6459 }
6460 }
6461 }
6462
6463 // Check if Ty is a usable substitute for the coercion type.
6464 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006465 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006466 }
6467
6468 // Get the coercion type as a literal struct type.
6469 llvm::Type *getType() const {
6470 if (Elems.size() == 1)
6471 return Elems.front();
6472 else
6473 return llvm::StructType::get(Context, Elems);
6474 }
6475 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006476};
6477} // end anonymous namespace
6478
6479ABIArgInfo
6480SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6481 if (Ty->isVoidType())
6482 return ABIArgInfo::getIgnore();
6483
6484 uint64_t Size = getContext().getTypeSize(Ty);
6485
6486 // Anything too big to fit in registers is passed with an explicit indirect
6487 // pointer / sret pointer.
6488 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006489 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006490
6491 // Treat an enum type as its underlying type.
6492 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6493 Ty = EnumTy->getDecl()->getIntegerType();
6494
6495 // Integer types smaller than a register are extended.
6496 if (Size < 64 && Ty->isIntegerType())
6497 return ABIArgInfo::getExtend();
6498
6499 // Other non-aggregates go in registers.
6500 if (!isAggregateTypeForABI(Ty))
6501 return ABIArgInfo::getDirect();
6502
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006503 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6504 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6505 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006506 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006507
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006508 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006509 // Build a coercion type from the LLVM struct type.
6510 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6511 if (!StrTy)
6512 return ABIArgInfo::getDirect();
6513
6514 CoerceBuilder CB(getVMContext(), getDataLayout());
6515 CB.addStruct(0, StrTy);
6516 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6517
6518 // Try to use the original type for coercion.
6519 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6520
6521 if (CB.InReg)
6522 return ABIArgInfo::getDirectInReg(CoerceTy);
6523 else
6524 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006525}
6526
John McCall7f416cc2015-09-08 08:05:57 +00006527Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6528 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006529 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6530 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6531 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6532 AI.setCoerceToType(ArgTy);
6533
John McCall7f416cc2015-09-08 08:05:57 +00006534 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006535
John McCall7f416cc2015-09-08 08:05:57 +00006536 CGBuilderTy &Builder = CGF.Builder;
6537 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6538 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6539
6540 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
6541
6542 Address ArgAddr = Address::invalid();
6543 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006544 switch (AI.getKind()) {
6545 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006546 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006547 llvm_unreachable("Unsupported ABI kind for va_arg");
6548
John McCall7f416cc2015-09-08 08:05:57 +00006549 case ABIArgInfo::Extend: {
6550 Stride = SlotSize;
6551 CharUnits Offset = SlotSize - TypeInfo.first;
6552 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006553 break;
John McCall7f416cc2015-09-08 08:05:57 +00006554 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006555
John McCall7f416cc2015-09-08 08:05:57 +00006556 case ABIArgInfo::Direct: {
6557 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6558 Stride = CharUnits::fromQuantity(AllocSize).RoundUpToAlignment(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006559 ArgAddr = Addr;
6560 break;
John McCall7f416cc2015-09-08 08:05:57 +00006561 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006562
6563 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006564 Stride = SlotSize;
6565 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
6566 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
6567 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006568 break;
6569
6570 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006571 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006572 }
6573
6574 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006575 llvm::Value *NextPtr =
6576 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
6577 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006578
John McCall7f416cc2015-09-08 08:05:57 +00006579 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006580}
6581
6582void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6583 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006584 for (auto &I : FI.arguments())
6585 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006586}
6587
6588namespace {
6589class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6590public:
6591 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6592 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006593
Craig Topper4f12f102014-03-12 06:41:41 +00006594 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006595 return 14;
6596 }
6597
6598 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006599 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006600};
6601} // end anonymous namespace
6602
Roman Divackyf02c9942014-02-24 18:46:27 +00006603bool
6604SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6605 llvm::Value *Address) const {
6606 // This is calculated from the LLVM and GCC tables and verified
6607 // against gcc output. AFAIK all ABIs use the same encoding.
6608
6609 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6610
6611 llvm::IntegerType *i8 = CGF.Int8Ty;
6612 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6613 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6614
6615 // 0-31: the 8-byte general-purpose registers
6616 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6617
6618 // 32-63: f0-31, the 4-byte floating-point registers
6619 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6620
6621 // Y = 64
6622 // PSR = 65
6623 // WIM = 66
6624 // TBR = 67
6625 // PC = 68
6626 // NPC = 69
6627 // FSR = 70
6628 // CSR = 71
6629 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006630
Roman Divackyf02c9942014-02-24 18:46:27 +00006631 // 72-87: d0-15, the 8-byte floating-point registers
6632 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6633
6634 return false;
6635}
6636
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006637
Robert Lytton0e076492013-08-13 09:43:10 +00006638//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006639// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006640//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006641
Robert Lytton0e076492013-08-13 09:43:10 +00006642namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006643
6644/// A SmallStringEnc instance is used to build up the TypeString by passing
6645/// it by reference between functions that append to it.
6646typedef llvm::SmallString<128> SmallStringEnc;
6647
6648/// TypeStringCache caches the meta encodings of Types.
6649///
6650/// The reason for caching TypeStrings is two fold:
6651/// 1. To cache a type's encoding for later uses;
6652/// 2. As a means to break recursive member type inclusion.
6653///
6654/// A cache Entry can have a Status of:
6655/// NonRecursive: The type encoding is not recursive;
6656/// Recursive: The type encoding is recursive;
6657/// Incomplete: An incomplete TypeString;
6658/// IncompleteUsed: An incomplete TypeString that has been used in a
6659/// Recursive type encoding.
6660///
6661/// A NonRecursive entry will have all of its sub-members expanded as fully
6662/// as possible. Whilst it may contain types which are recursive, the type
6663/// itself is not recursive and thus its encoding may be safely used whenever
6664/// the type is encountered.
6665///
6666/// A Recursive entry will have all of its sub-members expanded as fully as
6667/// possible. The type itself is recursive and it may contain other types which
6668/// are recursive. The Recursive encoding must not be used during the expansion
6669/// of a recursive type's recursive branch. For simplicity the code uses
6670/// IncompleteCount to reject all usage of Recursive encodings for member types.
6671///
6672/// An Incomplete entry is always a RecordType and only encodes its
6673/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6674/// are placed into the cache during type expansion as a means to identify and
6675/// handle recursive inclusion of types as sub-members. If there is recursion
6676/// the entry becomes IncompleteUsed.
6677///
6678/// During the expansion of a RecordType's members:
6679///
6680/// If the cache contains a NonRecursive encoding for the member type, the
6681/// cached encoding is used;
6682///
6683/// If the cache contains a Recursive encoding for the member type, the
6684/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6685///
6686/// If the member is a RecordType, an Incomplete encoding is placed into the
6687/// cache to break potential recursive inclusion of itself as a sub-member;
6688///
6689/// Once a member RecordType has been expanded, its temporary incomplete
6690/// entry is removed from the cache. If a Recursive encoding was swapped out
6691/// it is swapped back in;
6692///
6693/// If an incomplete entry is used to expand a sub-member, the incomplete
6694/// entry is marked as IncompleteUsed. The cache keeps count of how many
6695/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6696///
6697/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6698/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6699/// Else the member is part of a recursive type and thus the recursion has
6700/// been exited too soon for the encoding to be correct for the member.
6701///
6702class TypeStringCache {
6703 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6704 struct Entry {
6705 std::string Str; // The encoded TypeString for the type.
6706 enum Status State; // Information about the encoding in 'Str'.
6707 std::string Swapped; // A temporary place holder for a Recursive encoding
6708 // during the expansion of RecordType's members.
6709 };
6710 std::map<const IdentifierInfo *, struct Entry> Map;
6711 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6712 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6713public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006714 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006715 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6716 bool removeIncomplete(const IdentifierInfo *ID);
6717 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6718 bool IsRecursive);
6719 StringRef lookupStr(const IdentifierInfo *ID);
6720};
6721
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006722/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006723/// FieldEncoding is a helper for this ordering process.
6724class FieldEncoding {
6725 bool HasName;
6726 std::string Enc;
6727public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006728 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6729 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006730 bool operator<(const FieldEncoding &rhs) const {
6731 if (HasName != rhs.HasName) return HasName;
6732 return Enc < rhs.Enc;
6733 }
6734};
6735
Robert Lytton7d1db152013-08-19 09:46:39 +00006736class XCoreABIInfo : public DefaultABIInfo {
6737public:
6738 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00006739 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6740 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006741};
6742
Robert Lyttond21e2d72014-03-03 13:45:29 +00006743class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006744 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006745public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006746 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006747 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006748 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6749 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006750};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006751
Robert Lytton2d196952013-10-11 10:29:34 +00006752} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006753
John McCall7f416cc2015-09-08 08:05:57 +00006754Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6755 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006756 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006757
Robert Lytton2d196952013-10-11 10:29:34 +00006758 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006759 CharUnits SlotSize = CharUnits::fromQuantity(4);
6760 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00006761
Robert Lytton2d196952013-10-11 10:29:34 +00006762 // Handle the argument.
6763 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006764 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00006765 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6766 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6767 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006768 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00006769
6770 Address Val = Address::invalid();
6771 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00006772 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006773 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006774 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006775 llvm_unreachable("Unsupported ABI kind for va_arg");
6776 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006777 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
6778 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00006779 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006780 case ABIArgInfo::Extend:
6781 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00006782 Val = Builder.CreateBitCast(AP, ArgPtrTy);
6783 ArgSize = CharUnits::fromQuantity(
6784 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
6785 ArgSize = ArgSize.RoundUpToAlignment(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00006786 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006787 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006788 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
6789 Val = Address(Builder.CreateLoad(Val), TypeAlign);
6790 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00006791 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006792 }
Robert Lytton2d196952013-10-11 10:29:34 +00006793
6794 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006795 if (!ArgSize.isZero()) {
6796 llvm::Value *APN =
6797 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
6798 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006799 }
John McCall7f416cc2015-09-08 08:05:57 +00006800
Robert Lytton2d196952013-10-11 10:29:34 +00006801 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006802}
Robert Lytton0e076492013-08-13 09:43:10 +00006803
Robert Lytton844aeeb2014-05-02 09:33:20 +00006804/// During the expansion of a RecordType, an incomplete TypeString is placed
6805/// into the cache as a means to identify and break recursion.
6806/// If there is a Recursive encoding in the cache, it is swapped out and will
6807/// be reinserted by removeIncomplete().
6808/// All other types of encoding should have been used rather than arriving here.
6809void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6810 std::string StubEnc) {
6811 if (!ID)
6812 return;
6813 Entry &E = Map[ID];
6814 assert( (E.Str.empty() || E.State == Recursive) &&
6815 "Incorrectly use of addIncomplete");
6816 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6817 E.Swapped.swap(E.Str); // swap out the Recursive
6818 E.Str.swap(StubEnc);
6819 E.State = Incomplete;
6820 ++IncompleteCount;
6821}
6822
6823/// Once the RecordType has been expanded, the temporary incomplete TypeString
6824/// must be removed from the cache.
6825/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6826/// Returns true if the RecordType was defined recursively.
6827bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6828 if (!ID)
6829 return false;
6830 auto I = Map.find(ID);
6831 assert(I != Map.end() && "Entry not present");
6832 Entry &E = I->second;
6833 assert( (E.State == Incomplete ||
6834 E.State == IncompleteUsed) &&
6835 "Entry must be an incomplete type");
6836 bool IsRecursive = false;
6837 if (E.State == IncompleteUsed) {
6838 // We made use of our Incomplete encoding, thus we are recursive.
6839 IsRecursive = true;
6840 --IncompleteUsedCount;
6841 }
6842 if (E.Swapped.empty())
6843 Map.erase(I);
6844 else {
6845 // Swap the Recursive back.
6846 E.Swapped.swap(E.Str);
6847 E.Swapped.clear();
6848 E.State = Recursive;
6849 }
6850 --IncompleteCount;
6851 return IsRecursive;
6852}
6853
6854/// Add the encoded TypeString to the cache only if it is NonRecursive or
6855/// Recursive (viz: all sub-members were expanded as fully as possible).
6856void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6857 bool IsRecursive) {
6858 if (!ID || IncompleteUsedCount)
6859 return; // No key or it is is an incomplete sub-type so don't add.
6860 Entry &E = Map[ID];
6861 if (IsRecursive && !E.Str.empty()) {
6862 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6863 "This is not the same Recursive entry");
6864 // The parent container was not recursive after all, so we could have used
6865 // this Recursive sub-member entry after all, but we assumed the worse when
6866 // we started viz: IncompleteCount!=0.
6867 return;
6868 }
6869 assert(E.Str.empty() && "Entry already present");
6870 E.Str = Str.str();
6871 E.State = IsRecursive? Recursive : NonRecursive;
6872}
6873
6874/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6875/// are recursively expanding a type (IncompleteCount != 0) and the cached
6876/// encoding is Recursive, return an empty StringRef.
6877StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6878 if (!ID)
6879 return StringRef(); // We have no key.
6880 auto I = Map.find(ID);
6881 if (I == Map.end())
6882 return StringRef(); // We have no encoding.
6883 Entry &E = I->second;
6884 if (E.State == Recursive && IncompleteCount)
6885 return StringRef(); // We don't use Recursive encodings for member types.
6886
6887 if (E.State == Incomplete) {
6888 // The incomplete type is being used to break out of recursion.
6889 E.State = IncompleteUsed;
6890 ++IncompleteUsedCount;
6891 }
6892 return E.Str.c_str();
6893}
6894
6895/// The XCore ABI includes a type information section that communicates symbol
6896/// type information to the linker. The linker uses this information to verify
6897/// safety/correctness of things such as array bound and pointers et al.
6898/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6899/// This type information (TypeString) is emitted into meta data for all global
6900/// symbols: definitions, declarations, functions & variables.
6901///
6902/// The TypeString carries type, qualifier, name, size & value details.
6903/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00006904/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00006905/// The output is tested by test/CodeGen/xcore-stringtype.c.
6906///
6907static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6908 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6909
6910/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6911void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6912 CodeGen::CodeGenModule &CGM) const {
6913 SmallStringEnc Enc;
6914 if (getTypeString(Enc, D, CGM, TSC)) {
6915 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006916 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6917 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006918 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6919 llvm::NamedMDNode *MD =
6920 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6921 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6922 }
6923}
6924
6925static bool appendType(SmallStringEnc &Enc, QualType QType,
6926 const CodeGen::CodeGenModule &CGM,
6927 TypeStringCache &TSC);
6928
6929/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00006930/// Builds a SmallVector containing the encoded field types in declaration
6931/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006932static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6933 const RecordDecl *RD,
6934 const CodeGen::CodeGenModule &CGM,
6935 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006936 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006937 SmallStringEnc Enc;
6938 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006939 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006940 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006941 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006942 Enc += "b(";
6943 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00006944 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006945 Enc += ':';
6946 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006947 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006948 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006949 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006950 Enc += ')';
6951 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00006952 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006953 }
6954 return true;
6955}
6956
6957/// Appends structure and union types to Enc and adds encoding to cache.
6958/// Recursively calls appendType (via extractFieldType) for each field.
6959/// Union types have their fields ordered according to the ABI.
6960static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6961 const CodeGen::CodeGenModule &CGM,
6962 TypeStringCache &TSC, const IdentifierInfo *ID) {
6963 // Append the cached TypeString if we have one.
6964 StringRef TypeString = TSC.lookupStr(ID);
6965 if (!TypeString.empty()) {
6966 Enc += TypeString;
6967 return true;
6968 }
6969
6970 // Start to emit an incomplete TypeString.
6971 size_t Start = Enc.size();
6972 Enc += (RT->isUnionType()? 'u' : 's');
6973 Enc += '(';
6974 if (ID)
6975 Enc += ID->getName();
6976 Enc += "){";
6977
6978 // We collect all encoded fields and order as necessary.
6979 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006980 const RecordDecl *RD = RT->getDecl()->getDefinition();
6981 if (RD && !RD->field_empty()) {
6982 // An incomplete TypeString stub is placed in the cache for this RecordType
6983 // so that recursive calls to this RecordType will use it whilst building a
6984 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006985 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006986 std::string StubEnc(Enc.substr(Start).str());
6987 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6988 TSC.addIncomplete(ID, std::move(StubEnc));
6989 if (!extractFieldType(FE, RD, CGM, TSC)) {
6990 (void) TSC.removeIncomplete(ID);
6991 return false;
6992 }
6993 IsRecursive = TSC.removeIncomplete(ID);
6994 // The ABI requires unions to be sorted but not structures.
6995 // See FieldEncoding::operator< for sort algorithm.
6996 if (RT->isUnionType())
6997 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006998 // We can now complete the TypeString.
6999 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007000 for (unsigned I = 0; I != E; ++I) {
7001 if (I)
7002 Enc += ',';
7003 Enc += FE[I].str();
7004 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007005 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007006 Enc += '}';
7007 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7008 return true;
7009}
7010
7011/// Appends enum types to Enc and adds the encoding to the cache.
7012static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7013 TypeStringCache &TSC,
7014 const IdentifierInfo *ID) {
7015 // Append the cached TypeString if we have one.
7016 StringRef TypeString = TSC.lookupStr(ID);
7017 if (!TypeString.empty()) {
7018 Enc += TypeString;
7019 return true;
7020 }
7021
7022 size_t Start = Enc.size();
7023 Enc += "e(";
7024 if (ID)
7025 Enc += ID->getName();
7026 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007027
7028 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007029 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007030 SmallVector<FieldEncoding, 16> FE;
7031 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7032 ++I) {
7033 SmallStringEnc EnumEnc;
7034 EnumEnc += "m(";
7035 EnumEnc += I->getName();
7036 EnumEnc += "){";
7037 I->getInitVal().toString(EnumEnc);
7038 EnumEnc += '}';
7039 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7040 }
7041 std::sort(FE.begin(), FE.end());
7042 unsigned E = FE.size();
7043 for (unsigned I = 0; I != E; ++I) {
7044 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007045 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007046 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007047 }
7048 }
7049 Enc += '}';
7050 TSC.addIfComplete(ID, Enc.substr(Start), false);
7051 return true;
7052}
7053
7054/// Appends type's qualifier to Enc.
7055/// This is done prior to appending the type's encoding.
7056static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7057 // Qualifiers are emitted in alphabetical order.
7058 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
7059 int Lookup = 0;
7060 if (QT.isConstQualified())
7061 Lookup += 1<<0;
7062 if (QT.isRestrictQualified())
7063 Lookup += 1<<1;
7064 if (QT.isVolatileQualified())
7065 Lookup += 1<<2;
7066 Enc += Table[Lookup];
7067}
7068
7069/// Appends built-in types to Enc.
7070static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7071 const char *EncType;
7072 switch (BT->getKind()) {
7073 case BuiltinType::Void:
7074 EncType = "0";
7075 break;
7076 case BuiltinType::Bool:
7077 EncType = "b";
7078 break;
7079 case BuiltinType::Char_U:
7080 EncType = "uc";
7081 break;
7082 case BuiltinType::UChar:
7083 EncType = "uc";
7084 break;
7085 case BuiltinType::SChar:
7086 EncType = "sc";
7087 break;
7088 case BuiltinType::UShort:
7089 EncType = "us";
7090 break;
7091 case BuiltinType::Short:
7092 EncType = "ss";
7093 break;
7094 case BuiltinType::UInt:
7095 EncType = "ui";
7096 break;
7097 case BuiltinType::Int:
7098 EncType = "si";
7099 break;
7100 case BuiltinType::ULong:
7101 EncType = "ul";
7102 break;
7103 case BuiltinType::Long:
7104 EncType = "sl";
7105 break;
7106 case BuiltinType::ULongLong:
7107 EncType = "ull";
7108 break;
7109 case BuiltinType::LongLong:
7110 EncType = "sll";
7111 break;
7112 case BuiltinType::Float:
7113 EncType = "ft";
7114 break;
7115 case BuiltinType::Double:
7116 EncType = "d";
7117 break;
7118 case BuiltinType::LongDouble:
7119 EncType = "ld";
7120 break;
7121 default:
7122 return false;
7123 }
7124 Enc += EncType;
7125 return true;
7126}
7127
7128/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7129static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7130 const CodeGen::CodeGenModule &CGM,
7131 TypeStringCache &TSC) {
7132 Enc += "p(";
7133 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7134 return false;
7135 Enc += ')';
7136 return true;
7137}
7138
7139/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007140static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7141 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007142 const CodeGen::CodeGenModule &CGM,
7143 TypeStringCache &TSC, StringRef NoSizeEnc) {
7144 if (AT->getSizeModifier() != ArrayType::Normal)
7145 return false;
7146 Enc += "a(";
7147 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7148 CAT->getSize().toStringUnsigned(Enc);
7149 else
7150 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7151 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007152 // The Qualifiers should be attached to the type rather than the array.
7153 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007154 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7155 return false;
7156 Enc += ')';
7157 return true;
7158}
7159
7160/// Appends a function encoding to Enc, calling appendType for the return type
7161/// and the arguments.
7162static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7163 const CodeGen::CodeGenModule &CGM,
7164 TypeStringCache &TSC) {
7165 Enc += "f{";
7166 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7167 return false;
7168 Enc += "}(";
7169 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7170 // N.B. we are only interested in the adjusted param types.
7171 auto I = FPT->param_type_begin();
7172 auto E = FPT->param_type_end();
7173 if (I != E) {
7174 do {
7175 if (!appendType(Enc, *I, CGM, TSC))
7176 return false;
7177 ++I;
7178 if (I != E)
7179 Enc += ',';
7180 } while (I != E);
7181 if (FPT->isVariadic())
7182 Enc += ",va";
7183 } else {
7184 if (FPT->isVariadic())
7185 Enc += "va";
7186 else
7187 Enc += '0';
7188 }
7189 }
7190 Enc += ')';
7191 return true;
7192}
7193
7194/// Handles the type's qualifier before dispatching a call to handle specific
7195/// type encodings.
7196static bool appendType(SmallStringEnc &Enc, QualType QType,
7197 const CodeGen::CodeGenModule &CGM,
7198 TypeStringCache &TSC) {
7199
7200 QualType QT = QType.getCanonicalType();
7201
Robert Lytton6adb20f2014-06-05 09:06:21 +00007202 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7203 // The Qualifiers should be attached to the type rather than the array.
7204 // Thus we don't call appendQualifier() here.
7205 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7206
Robert Lytton844aeeb2014-05-02 09:33:20 +00007207 appendQualifier(Enc, QT);
7208
7209 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7210 return appendBuiltinType(Enc, BT);
7211
Robert Lytton844aeeb2014-05-02 09:33:20 +00007212 if (const PointerType *PT = QT->getAs<PointerType>())
7213 return appendPointerType(Enc, PT, CGM, TSC);
7214
7215 if (const EnumType *ET = QT->getAs<EnumType>())
7216 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7217
7218 if (const RecordType *RT = QT->getAsStructureType())
7219 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7220
7221 if (const RecordType *RT = QT->getAsUnionType())
7222 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7223
7224 if (const FunctionType *FT = QT->getAs<FunctionType>())
7225 return appendFunctionType(Enc, FT, CGM, TSC);
7226
7227 return false;
7228}
7229
7230static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7231 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7232 if (!D)
7233 return false;
7234
7235 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7236 if (FD->getLanguageLinkage() != CLanguageLinkage)
7237 return false;
7238 return appendType(Enc, FD->getType(), CGM, TSC);
7239 }
7240
7241 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7242 if (VD->getLanguageLinkage() != CLanguageLinkage)
7243 return false;
7244 QualType QT = VD->getType().getCanonicalType();
7245 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7246 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007247 // The Qualifiers should be attached to the type rather than the array.
7248 // Thus we don't call appendQualifier() here.
7249 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007250 }
7251 return appendType(Enc, QT, CGM, TSC);
7252 }
7253 return false;
7254}
7255
7256
Robert Lytton0e076492013-08-13 09:43:10 +00007257//===----------------------------------------------------------------------===//
7258// Driver code
7259//===----------------------------------------------------------------------===//
7260
Rafael Espindola9f834732014-09-19 01:54:22 +00007261const llvm::Triple &CodeGenModule::getTriple() const {
7262 return getTarget().getTriple();
7263}
7264
7265bool CodeGenModule::supportsCOMDAT() const {
7266 return !getTriple().isOSBinFormatMachO();
7267}
7268
Chris Lattner2b037972010-07-29 02:01:43 +00007269const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007270 if (TheTargetCodeGenInfo)
7271 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007272
John McCallc8e01702013-04-16 22:48:15 +00007273 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007274 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007275 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007276 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007277
Derek Schuff09338a22012-09-06 17:37:28 +00007278 case llvm::Triple::le32:
7279 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007280 case llvm::Triple::mips:
7281 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007282 if (Triple.getOS() == llvm::Triple::NaCl)
7283 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007284 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7285
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007286 case llvm::Triple::mips64:
7287 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007288 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7289
Tim Northover25e8a672014-05-24 12:51:25 +00007290 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007291 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007292 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007293 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007294 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007295
Tim Northover573cbee2014-05-24 12:52:07 +00007296 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007297 }
7298
Dan Gohmanc2853072015-09-03 22:51:53 +00007299 case llvm::Triple::wasm32:
7300 case llvm::Triple::wasm64:
7301 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7302
Daniel Dunbard59655c2009-09-12 00:59:49 +00007303 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007304 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007305 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007306 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007307 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007308 if (Triple.getOS() == llvm::Triple::Win32) {
7309 TheTargetCodeGenInfo =
7310 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7311 return *TheTargetCodeGenInfo;
7312 }
7313
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007314 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007315 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007316 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007317 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007318 (CodeGenOpts.FloatABI != "soft" &&
7319 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007320 Kind = ARMABIInfo::AAPCS_VFP;
7321
Derek Schuff71658bd2015-01-29 00:47:04 +00007322 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007323 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007324
John McCallea8d8bb2010-03-11 00:10:12 +00007325 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007326 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007327 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007328 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007329 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007330 if (getTarget().getABI() == "elfv2")
7331 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007332 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007333
Ulrich Weigandb7122372014-07-21 00:48:09 +00007334 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007335 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007336 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007337 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007338 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007339 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007340 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007341 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007342 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007343 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007344
Ulrich Weigandb7122372014-07-21 00:48:09 +00007345 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007346 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007347 }
John McCallea8d8bb2010-03-11 00:10:12 +00007348
Peter Collingbournec947aae2012-05-20 23:28:41 +00007349 case llvm::Triple::nvptx:
7350 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007351 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007352
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007353 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007354 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007355
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007356 case llvm::Triple::systemz: {
7357 bool HasVector = getTarget().getABI() == "vector";
7358 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7359 HasVector));
7360 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007361
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007362 case llvm::Triple::tce:
7363 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7364
Eli Friedman33465822011-07-08 23:31:17 +00007365 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007366 bool IsDarwinVectorABI = Triple.isOSDarwin();
7367 bool IsSmallStructInRegABI =
7368 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007369 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007370
John McCall1fe2a8c2013-06-18 02:46:29 +00007371 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007372 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
7373 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7374 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007375 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007376 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
7377 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7378 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007379 }
Eli Friedman33465822011-07-08 23:31:17 +00007380 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007381
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007382 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007383 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007384 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7385 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007386 X86AVXABILevel::None);
7387
Chris Lattner04dc9572010-08-31 16:44:54 +00007388 switch (Triple.getOS()) {
7389 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007390 return *(TheTargetCodeGenInfo =
7391 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007392 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007393 return *(TheTargetCodeGenInfo =
7394 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007395 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007396 return *(TheTargetCodeGenInfo =
7397 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007398 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007399 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007400 case llvm::Triple::hexagon:
7401 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007402 case llvm::Triple::r600:
7403 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007404 case llvm::Triple::amdgcn:
7405 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007406 case llvm::Triple::sparcv9:
7407 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007408 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007409 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007410 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007411}