blob: 9fd7c493e035036f5e01294fddd87a723f4cf1db [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000022#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000023#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000024#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000025#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000028#include "llvm/Support/raw_ostream.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000030
Anton Korobeynikov244360d2009-06-05 22:08:42 +000031using namespace clang;
32using namespace CodeGen;
33
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +000034// Helper for coercing an aggregate argument or return value into an integer
35// array of the same size (including padding) and alignment. This alternate
36// coercion happens only for the RenderScript ABI and can be removed after
37// runtimes that rely on it are no longer supported.
38//
39// RenderScript assumes that the size of the argument / return value in the IR
40// is the same as the size of the corresponding qualified type. This helper
41// coerces the aggregate type into an array of the same size (including
42// padding). This coercion is used in lieu of expansion of struct members or
43// other canonical coercions that return a coerced-type of larger size.
44//
45// Ty - The argument / return value type
46// Context - The associated ASTContext
47// LLVMContext - The associated LLVMContext
48static ABIArgInfo coerceToIntArray(QualType Ty,
49 ASTContext &Context,
50 llvm::LLVMContext &LLVMContext) {
51 // Alignment and Size are measured in bits.
52 const uint64_t Size = Context.getTypeSize(Ty);
53 const uint64_t Alignment = Context.getTypeAlign(Ty);
54 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
55 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
56 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
57}
58
John McCall943fae92010-05-27 06:19:26 +000059static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
60 llvm::Value *Array,
61 llvm::Value *Value,
62 unsigned FirstIndex,
63 unsigned LastIndex) {
64 // Alternatively, we could emit this as a loop in the source.
65 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000066 llvm::Value *Cell =
67 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000068 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000069 }
70}
71
John McCalla1dee5302010-08-22 10:59:02 +000072static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000073 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000074 T->isMemberFunctionPointerType();
75}
76
John McCall7f416cc2015-09-08 08:05:57 +000077ABIArgInfo
78ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
79 llvm::Type *Padding) const {
80 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
81 ByRef, Realign, Padding);
82}
83
84ABIArgInfo
85ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
86 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
87 /*ByRef*/ false, Realign);
88}
89
Charles Davisc7d5c942015-09-17 20:55:33 +000090Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
91 QualType Ty) const {
92 return Address::invalid();
93}
94
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000095ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000096
John McCall12f23522016-04-04 18:33:08 +000097/// Does the given lowering require more than the given number of
98/// registers when expanded?
99///
100/// This is intended to be the basis of a reasonable basic implementation
101/// of should{Pass,Return}IndirectlyForSwift.
102///
103/// For most targets, a limit of four total registers is reasonable; this
104/// limits the amount of code required in order to move around the value
105/// in case it wasn't produced immediately prior to the call by the caller
106/// (or wasn't produced in exactly the right registers) or isn't used
107/// immediately within the callee. But some targets may need to further
108/// limit the register count due to an inability to support that many
109/// return registers.
110static bool occupiesMoreThan(CodeGenTypes &cgt,
111 ArrayRef<llvm::Type*> scalarTypes,
112 unsigned maxAllRegisters) {
113 unsigned intCount = 0, fpCount = 0;
114 for (llvm::Type *type : scalarTypes) {
115 if (type->isPointerTy()) {
116 intCount++;
117 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
118 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
119 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
120 } else {
121 assert(type->isVectorTy() || type->isFloatingPointTy());
122 fpCount++;
123 }
124 }
125
126 return (intCount + fpCount > maxAllRegisters);
127}
128
129bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
130 llvm::Type *eltTy,
131 unsigned numElts) const {
132 // The default implementation of this assumes that the target guarantees
133 // 128-bit SIMD support but nothing more.
134 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
135}
136
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000137static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000138 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000139 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
140 if (!RD)
141 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000142 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000143}
144
145static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000146 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000147 const RecordType *RT = T->getAs<RecordType>();
148 if (!RT)
149 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000150 return getRecordArgABI(RT, CXXABI);
151}
152
Reid Klecknerb1be6832014-11-15 01:41:41 +0000153/// Pass transparent unions as if they were the type of the first element. Sema
154/// should ensure that all elements of the union have the same "machine type".
155static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
156 if (const RecordType *UT = Ty->getAsUnionType()) {
157 const RecordDecl *UD = UT->getDecl();
158 if (UD->hasAttr<TransparentUnionAttr>()) {
159 assert(!UD->field_empty() && "sema created an empty transparent union");
160 return UD->field_begin()->getType();
161 }
162 }
163 return Ty;
164}
165
Mark Lacey3825e832013-10-06 01:33:34 +0000166CGCXXABI &ABIInfo::getCXXABI() const {
167 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000168}
169
Chris Lattner2b037972010-07-29 02:01:43 +0000170ASTContext &ABIInfo::getContext() const {
171 return CGT.getContext();
172}
173
174llvm::LLVMContext &ABIInfo::getVMContext() const {
175 return CGT.getLLVMContext();
176}
177
Micah Villmowdd31ca12012-10-08 16:25:52 +0000178const llvm::DataLayout &ABIInfo::getDataLayout() const {
179 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000180}
181
John McCallc8e01702013-04-16 22:48:15 +0000182const TargetInfo &ABIInfo::getTarget() const {
183 return CGT.getTarget();
184}
Chris Lattner2b037972010-07-29 02:01:43 +0000185
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000186bool ABIInfo:: isAndroid() const { return getTarget().getTriple().isAndroid(); }
187
Reid Klecknere9f6a712014-10-31 17:10:41 +0000188bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
189 return false;
190}
191
192bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
193 uint64_t Members) const {
194 return false;
195}
196
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000197bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
198 return false;
199}
200
Yaron Kerencdae9412016-01-29 19:38:18 +0000201LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000202 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000203 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000204 switch (TheKind) {
205 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000206 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000207 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000208 Ty->print(OS);
209 else
210 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000211 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000212 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000213 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000214 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000216 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000217 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000218 case InAlloca:
219 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
220 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000221 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000222 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000223 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000224 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000225 break;
226 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000227 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000228 break;
John McCallf26e73d2016-03-11 04:30:43 +0000229 case CoerceAndExpand:
230 OS << "CoerceAndExpand Type=";
231 getCoerceAndExpandType()->print(OS);
232 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000233 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000234 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000235}
236
Petar Jovanovic402257b2015-12-04 00:26:47 +0000237// Dynamically round a pointer up to a multiple of the given alignment.
238static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
239 llvm::Value *Ptr,
240 CharUnits Align) {
241 llvm::Value *PtrAsInt = Ptr;
242 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
243 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
244 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
245 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
246 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
247 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
248 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
249 Ptr->getType(),
250 Ptr->getName() + ".aligned");
251 return PtrAsInt;
252}
253
John McCall7f416cc2015-09-08 08:05:57 +0000254/// Emit va_arg for a platform using the common void* representation,
255/// where arguments are simply emitted in an array of slots on the stack.
256///
257/// This version implements the core direct-value passing rules.
258///
259/// \param SlotSize - The size and alignment of a stack slot.
260/// Each argument will be allocated to a multiple of this number of
261/// slots, and all the slots will be aligned to this value.
262/// \param AllowHigherAlign - The slot alignment is not a cap;
263/// an argument type with an alignment greater than the slot size
264/// will be emitted on a higher-alignment address, potentially
265/// leaving one or more empty slots behind as padding. If this
266/// is false, the returned address might be less-aligned than
267/// DirectAlign.
268static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
269 Address VAListAddr,
270 llvm::Type *DirectTy,
271 CharUnits DirectSize,
272 CharUnits DirectAlign,
273 CharUnits SlotSize,
274 bool AllowHigherAlign) {
275 // Cast the element type to i8* if necessary. Some platforms define
276 // va_list as a struct containing an i8* instead of just an i8*.
277 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
278 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
279
280 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
281
282 // If the CC aligns values higher than the slot size, do so if needed.
283 Address Addr = Address::invalid();
284 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000285 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
286 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000287 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000288 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000289 }
290
291 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000292 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000293 llvm::Value *NextPtr =
294 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
295 "argp.next");
296 CGF.Builder.CreateStore(NextPtr, VAListAddr);
297
298 // If the argument is smaller than a slot, and this is a big-endian
299 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000300 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
301 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000302 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
303 }
304
305 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
306 return Addr;
307}
308
309/// Emit va_arg for a platform using the common void* representation,
310/// where arguments are simply emitted in an array of slots on the stack.
311///
312/// \param IsIndirect - Values of this type are passed indirectly.
313/// \param ValueInfo - The size and alignment of this type, generally
314/// computed with getContext().getTypeInfoInChars(ValueTy).
315/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
316/// Each argument will be allocated to a multiple of this number of
317/// slots, and all the slots will be aligned to this value.
318/// \param AllowHigherAlign - The slot alignment is not a cap;
319/// an argument type with an alignment greater than the slot size
320/// will be emitted on a higher-alignment address, potentially
321/// leaving one or more empty slots behind as padding.
322static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
323 QualType ValueTy, bool IsIndirect,
324 std::pair<CharUnits, CharUnits> ValueInfo,
325 CharUnits SlotSizeAndAlign,
326 bool AllowHigherAlign) {
327 // The size and alignment of the value that was passed directly.
328 CharUnits DirectSize, DirectAlign;
329 if (IsIndirect) {
330 DirectSize = CGF.getPointerSize();
331 DirectAlign = CGF.getPointerAlign();
332 } else {
333 DirectSize = ValueInfo.first;
334 DirectAlign = ValueInfo.second;
335 }
336
337 // Cast the address we've calculated to the right type.
338 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
339 if (IsIndirect)
340 DirectTy = DirectTy->getPointerTo(0);
341
342 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
343 DirectSize, DirectAlign,
344 SlotSizeAndAlign,
345 AllowHigherAlign);
346
347 if (IsIndirect) {
348 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
349 }
350
351 return Addr;
352
353}
354
355static Address emitMergePHI(CodeGenFunction &CGF,
356 Address Addr1, llvm::BasicBlock *Block1,
357 Address Addr2, llvm::BasicBlock *Block2,
358 const llvm::Twine &Name = "") {
359 assert(Addr1.getType() == Addr2.getType());
360 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
361 PHI->addIncoming(Addr1.getPointer(), Block1);
362 PHI->addIncoming(Addr2.getPointer(), Block2);
363 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
364 return Address(PHI, Align);
365}
366
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000367TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
368
John McCall3480ef22011-08-30 01:42:09 +0000369// If someone can figure out a general rule for this, that would be great.
370// It's probably just doomed to be platform-dependent, though.
371unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
372 // Verified for:
373 // x86-64 FreeBSD, Linux, Darwin
374 // x86-32 FreeBSD, Linux, Darwin
375 // PowerPC Linux, Darwin
376 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000377 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000378 return 32;
379}
380
John McCalla729c622012-02-17 03:33:10 +0000381bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
382 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000383 // The following conventions are known to require this to be false:
384 // x86_stdcall
385 // MIPS
386 // For everything else, we just prefer false unless we opt out.
387 return false;
388}
389
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000390void
391TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
392 llvm::SmallString<24> &Opt) const {
393 // This assumes the user is passing a library name like "rt" instead of a
394 // filename like "librt.a/so", and that they don't care whether it's static or
395 // dynamic.
396 Opt = "-l";
397 Opt += Lib;
398}
399
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000400unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
401 return llvm::CallingConv::C;
402}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000403
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000404static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000405
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000406/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000407/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000408static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
409 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000410 if (FD->isUnnamedBitfield())
411 return true;
412
413 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000414
Eli Friedman0b3f2012011-11-18 03:47:20 +0000415 // Constant arrays of empty records count as empty, strip them off.
416 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000417 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000418 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
419 if (AT->getSize() == 0)
420 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000421 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000422 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000423
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000424 const RecordType *RT = FT->getAs<RecordType>();
425 if (!RT)
426 return false;
427
428 // C++ record fields are never empty, at least in the Itanium ABI.
429 //
430 // FIXME: We should use a predicate for whether this behavior is true in the
431 // current ABI.
432 if (isa<CXXRecordDecl>(RT->getDecl()))
433 return false;
434
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000435 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000436}
437
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000438/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000439/// fields. Note that a structure with a flexible array member is not
440/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000441static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000442 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000443 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000444 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000445 const RecordDecl *RD = RT->getDecl();
446 if (RD->hasFlexibleArrayMember())
447 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000448
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000449 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000450 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000451 for (const auto &I : CXXRD->bases())
452 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000453 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000454
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000455 for (const auto *I : RD->fields())
456 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000457 return false;
458 return true;
459}
460
461/// isSingleElementStruct - Determine if a structure is a "single
462/// element struct", i.e. it has exactly one non-empty field or
463/// exactly one field which is itself a single element
464/// struct. Structures with flexible array members are never
465/// considered single element structs.
466///
467/// \return The field declaration for the single non-empty field, if
468/// it exists.
469static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000470 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000471 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000472 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000473
474 const RecordDecl *RD = RT->getDecl();
475 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000476 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000477
Craig Topper8a13c412014-05-21 05:09:00 +0000478 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000479
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000480 // If this is a C++ record, check the bases first.
481 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000482 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000483 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000484 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000485 continue;
486
487 // If we already found an element then this isn't a single-element struct.
488 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000489 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000490
491 // If this is non-empty and not a single element struct, the composite
492 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000493 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000494 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000495 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000496 }
497 }
498
499 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000500 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000501 QualType FT = FD->getType();
502
503 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000504 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000505 continue;
506
507 // If we already found an element then this isn't a single-element
508 // struct.
509 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000510 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000511
512 // Treat single element arrays as the element.
513 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
514 if (AT->getSize().getZExtValue() != 1)
515 break;
516 FT = AT->getElementType();
517 }
518
John McCalla1dee5302010-08-22 10:59:02 +0000519 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000520 Found = FT.getTypePtr();
521 } else {
522 Found = isSingleElementStruct(FT, Context);
523 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000524 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000525 }
526 }
527
Eli Friedmanee945342011-11-18 01:25:50 +0000528 // We don't consider a struct a single-element struct if it has
529 // padding beyond the element type.
530 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000531 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000532
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000533 return Found;
534}
535
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000536namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000537Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
538 const ABIArgInfo &AI) {
539 // This default implementation defers to the llvm backend's va_arg
540 // instruction. It can handle only passing arguments directly
541 // (typically only handled in the backend for primitive types), or
542 // aggregates passed indirectly by pointer (NOTE: if the "byval"
543 // flag has ABI impact in the callee, this implementation cannot
544 // work.)
545
546 // Only a few cases are covered here at the moment -- those needed
547 // by the default abi.
548 llvm::Value *Val;
549
550 if (AI.isIndirect()) {
551 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000552 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000553 assert(
554 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000555 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000556
557 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
558 CharUnits TyAlignForABI = TyInfo.second;
559
560 llvm::Type *BaseTy =
561 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
562 llvm::Value *Addr =
563 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
564 return Address(Addr, TyAlignForABI);
565 } else {
566 assert((AI.isDirect() || AI.isExtend()) &&
567 "Unexpected ArgInfo Kind in generic VAArg emitter!");
568
569 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000570 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000571 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000572 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000573 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000574 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000575 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000576 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000577
578 Address Temp = CGF.CreateMemTemp(Ty, "varet");
579 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
580 CGF.Builder.CreateStore(Val, Temp);
581 return Temp;
582 }
583}
584
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000585/// DefaultABIInfo - The default implementation for ABI specific
586/// details. This implementation provides information which results in
587/// self-consistent and sensible LLVM IR generation, but does not
588/// conform to any particular ABI.
589class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000590public:
591 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000592
Chris Lattner458b2aa2010-07-29 02:16:43 +0000593 ABIArgInfo classifyReturnType(QualType RetTy) const;
594 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000595
Craig Topper4f12f102014-03-12 06:41:41 +0000596 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000597 if (!getCXXABI().classifyReturnType(FI))
598 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000599 for (auto &I : FI.arguments())
600 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000601 }
602
John McCall7f416cc2015-09-08 08:05:57 +0000603 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000604 QualType Ty) const override {
605 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
606 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000607};
608
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000609class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
610public:
Chris Lattner2b037972010-07-29 02:01:43 +0000611 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
612 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000613};
614
Chris Lattner458b2aa2010-07-29 02:16:43 +0000615ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000616 Ty = useFirstFieldIfTransparentUnion(Ty);
617
618 if (isAggregateTypeForABI(Ty)) {
619 // Records with non-trivial destructors/copy-constructors should not be
620 // passed by value.
621 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000622 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000623
John McCall7f416cc2015-09-08 08:05:57 +0000624 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000625 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000626
Chris Lattner9723d6c2010-03-11 18:19:55 +0000627 // Treat an enum type as its underlying type.
628 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
629 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000630
Chris Lattner9723d6c2010-03-11 18:19:55 +0000631 return (Ty->isPromotableIntegerType() ?
632 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000633}
634
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000635ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
636 if (RetTy->isVoidType())
637 return ABIArgInfo::getIgnore();
638
639 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000640 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000641
642 // Treat an enum type as its underlying type.
643 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
644 RetTy = EnumTy->getDecl()->getIntegerType();
645
646 return (RetTy->isPromotableIntegerType() ?
647 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
648}
649
Derek Schuff09338a22012-09-06 17:37:28 +0000650//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000651// WebAssembly ABI Implementation
652//
653// This is a very simple ABI that relies a lot on DefaultABIInfo.
654//===----------------------------------------------------------------------===//
655
656class WebAssemblyABIInfo final : public DefaultABIInfo {
657public:
658 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
659 : DefaultABIInfo(CGT) {}
660
661private:
662 ABIArgInfo classifyReturnType(QualType RetTy) const;
663 ABIArgInfo classifyArgumentType(QualType Ty) const;
664
665 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000666 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000667 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000668 void computeInfo(CGFunctionInfo &FI) const override {
669 if (!getCXXABI().classifyReturnType(FI))
670 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
671 for (auto &Arg : FI.arguments())
672 Arg.info = classifyArgumentType(Arg.type);
673 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000674
675 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
676 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000677};
678
679class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
680public:
681 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
682 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
683};
684
685/// \brief Classify argument of given type \p Ty.
686ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
687 Ty = useFirstFieldIfTransparentUnion(Ty);
688
689 if (isAggregateTypeForABI(Ty)) {
690 // Records with non-trivial destructors/copy-constructors should not be
691 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000692 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000693 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000694 // Ignore empty structs/unions.
695 if (isEmptyRecord(getContext(), Ty, true))
696 return ABIArgInfo::getIgnore();
697 // Lower single-element structs to just pass a regular value. TODO: We
698 // could do reasonable-size multiple-element structs too, using getExpand(),
699 // though watch out for things like bitfields.
700 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
701 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000702 }
703
704 // Otherwise just do the default thing.
705 return DefaultABIInfo::classifyArgumentType(Ty);
706}
707
708ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
709 if (isAggregateTypeForABI(RetTy)) {
710 // Records with non-trivial destructors/copy-constructors should not be
711 // returned by value.
712 if (!getRecordArgABI(RetTy, getCXXABI())) {
713 // Ignore empty structs/unions.
714 if (isEmptyRecord(getContext(), RetTy, true))
715 return ABIArgInfo::getIgnore();
716 // Lower single-element structs to just return a regular value. TODO: We
717 // could do reasonable-size multiple-element structs too, using
718 // ABIArgInfo::getDirect().
719 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
720 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
721 }
722 }
723
724 // Otherwise just do the default thing.
725 return DefaultABIInfo::classifyReturnType(RetTy);
726}
727
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000728Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
729 QualType Ty) const {
730 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
731 getContext().getTypeInfoInChars(Ty),
732 CharUnits::fromQuantity(4),
733 /*AllowHigherAlign=*/ true);
734}
735
Dan Gohmanc2853072015-09-03 22:51:53 +0000736//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000737// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000738//
739// This is a simplified version of the x86_32 ABI. Arguments and return values
740// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000741//===----------------------------------------------------------------------===//
742
743class PNaClABIInfo : public ABIInfo {
744 public:
745 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
746
747 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000748 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000749
Craig Topper4f12f102014-03-12 06:41:41 +0000750 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000751 Address EmitVAArg(CodeGenFunction &CGF,
752 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000753};
754
755class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
756 public:
757 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
758 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
759};
760
761void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000762 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000763 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
764
Reid Kleckner40ca9132014-05-13 22:05:45 +0000765 for (auto &I : FI.arguments())
766 I.info = classifyArgumentType(I.type);
767}
Derek Schuff09338a22012-09-06 17:37:28 +0000768
John McCall7f416cc2015-09-08 08:05:57 +0000769Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
770 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000771 // The PNaCL ABI is a bit odd, in that varargs don't use normal
772 // function classification. Structs get passed directly for varargs
773 // functions, through a rewriting transform in
774 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
775 // this target to actually support a va_arg instructions with an
776 // aggregate type, unlike other targets.
777 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000778}
779
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000780/// \brief Classify argument of given type \p Ty.
781ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000782 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000783 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000784 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
785 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000786 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
787 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000788 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000789 } else if (Ty->isFloatingType()) {
790 // Floating-point types don't go inreg.
791 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000792 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000793
794 return (Ty->isPromotableIntegerType() ?
795 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000796}
797
798ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
799 if (RetTy->isVoidType())
800 return ABIArgInfo::getIgnore();
801
Eli Benderskye20dad62013-04-04 22:49:35 +0000802 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000803 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000804 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000805
806 // Treat an enum type as its underlying type.
807 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
808 RetTy = EnumTy->getDecl()->getIntegerType();
809
810 return (RetTy->isPromotableIntegerType() ?
811 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
812}
813
Chad Rosier651c1832013-03-25 21:00:27 +0000814/// IsX86_MMXType - Return true if this is an MMX type.
815bool IsX86_MMXType(llvm::Type *IRType) {
816 // 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 +0000817 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
818 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
819 IRType->getScalarSizeInBits() != 64;
820}
821
Jay Foad7c57be32011-07-11 09:56:20 +0000822static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000823 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000824 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000825 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
826 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
827 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000828 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000829 }
830
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000831 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000832 }
833
834 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000835 return Ty;
836}
837
Reid Kleckner80944df2014-10-31 22:00:51 +0000838/// Returns true if this type can be passed in SSE registers with the
839/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
840static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
841 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
842 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
843 return true;
844 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
845 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
846 // registers specially.
847 unsigned VecSize = Context.getTypeSize(VT);
848 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
849 return true;
850 }
851 return false;
852}
853
854/// Returns true if this aggregate is small enough to be passed in SSE registers
855/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
856static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
857 return NumMembers <= 4;
858}
859
Chris Lattner0cf24192010-06-28 20:05:43 +0000860//===----------------------------------------------------------------------===//
861// X86-32 ABI Implementation
862//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000863
Reid Kleckner661f35b2014-01-18 01:12:41 +0000864/// \brief Similar to llvm::CCState, but for Clang.
865struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000866 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000867
868 unsigned CC;
869 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000870 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000871};
872
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000873/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000874class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000875 enum Class {
876 Integer,
877 Float
878 };
879
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000880 static const unsigned MinABIStackAlignInBytes = 4;
881
David Chisnallde3a0692009-08-17 23:08:21 +0000882 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000883 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000884 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000885 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000886 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000887 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000888
889 static bool isRegisterSize(unsigned Size) {
890 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
891 }
892
Reid Kleckner80944df2014-10-31 22:00:51 +0000893 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
894 // FIXME: Assumes vectorcall is in use.
895 return isX86VectorTypeForVectorCall(getContext(), Ty);
896 }
897
898 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
899 uint64_t NumMembers) const override {
900 // FIXME: Assumes vectorcall is in use.
901 return isX86VectorCallAggregateSmallEnough(NumMembers);
902 }
903
Reid Kleckner40ca9132014-05-13 22:05:45 +0000904 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000905
Daniel Dunbar557893d2010-04-21 19:10:51 +0000906 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
907 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000908 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
909
John McCall7f416cc2015-09-08 08:05:57 +0000910 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000911
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000912 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000913 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000914
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000915 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000916 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000917 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000918 /// \brief Updates the number of available free registers, returns
919 /// true if any registers were allocated.
920 bool updateFreeRegs(QualType Ty, CCState &State) const;
921
922 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
923 bool &NeedsPadding) const;
924 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000925
Reid Kleckner04046052016-05-02 17:41:07 +0000926 bool canExpandIndirectArgument(QualType Ty) const;
927
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000928 /// \brief Rewrite the function info so that all memory arguments use
929 /// inalloca.
930 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
931
932 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000933 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000934 QualType Type) const;
935
Rafael Espindola75419dc2012-07-23 23:30:29 +0000936public:
937
Craig Topper4f12f102014-03-12 06:41:41 +0000938 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000939 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
940 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000941
Michael Kupersteindc745202015-10-19 07:52:25 +0000942 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
943 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000944 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000945 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000946 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
947 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000948 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000949 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000950 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000951
952 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
953 ArrayRef<llvm::Type*> scalars,
954 bool asReturnValue) const override {
955 // LLVM's x86-32 lowering currently only assigns up to three
956 // integer registers and three fp registers. Oddly, it'll use up to
957 // four vector registers for vectors, but those can overlap with the
958 // scalar registers.
959 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
960 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000961};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000962
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000963class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
964public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000965 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
966 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000967 unsigned NumRegisterParameters, bool SoftFloatABI)
968 : TargetCodeGenInfo(new X86_32ABIInfo(
969 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
970 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000971
John McCall1fe2a8c2013-06-18 02:46:29 +0000972 static bool isStructReturnInRegABI(
973 const llvm::Triple &Triple, const CodeGenOptions &Opts);
974
Eric Christopher162c91c2015-06-05 22:03:00 +0000975 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000976 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000977
Craig Topper4f12f102014-03-12 06:41:41 +0000978 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000979 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000980 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000981 return 4;
982 }
983
984 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000985 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000986
Jay Foad7c57be32011-07-11 09:56:20 +0000987 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000988 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000989 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000990 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
991 }
992
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000993 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
994 std::string &Constraints,
995 std::vector<llvm::Type *> &ResultRegTypes,
996 std::vector<llvm::Type *> &ResultTruncRegTypes,
997 std::vector<LValue> &ResultRegDests,
998 std::string &AsmString,
999 unsigned NumOutputs) const override;
1000
Craig Topper4f12f102014-03-12 06:41:41 +00001001 llvm::Constant *
1002 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001003 unsigned Sig = (0xeb << 0) | // jmp rel8
1004 (0x06 << 8) | // .+0x08
1005 ('F' << 16) |
1006 ('T' << 24);
1007 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1008 }
John McCall01391782016-02-05 21:37:38 +00001009
1010 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1011 return "movl\t%ebp, %ebp"
1012 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1013 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001014};
1015
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001016}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001017
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001018/// Rewrite input constraint references after adding some output constraints.
1019/// In the case where there is one output and one input and we add one output,
1020/// we need to replace all operand references greater than or equal to 1:
1021/// mov $0, $1
1022/// mov eax, $1
1023/// The result will be:
1024/// mov $0, $2
1025/// mov eax, $2
1026static void rewriteInputConstraintReferences(unsigned FirstIn,
1027 unsigned NumNewOuts,
1028 std::string &AsmString) {
1029 std::string Buf;
1030 llvm::raw_string_ostream OS(Buf);
1031 size_t Pos = 0;
1032 while (Pos < AsmString.size()) {
1033 size_t DollarStart = AsmString.find('$', Pos);
1034 if (DollarStart == std::string::npos)
1035 DollarStart = AsmString.size();
1036 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1037 if (DollarEnd == std::string::npos)
1038 DollarEnd = AsmString.size();
1039 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1040 Pos = DollarEnd;
1041 size_t NumDollars = DollarEnd - DollarStart;
1042 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1043 // We have an operand reference.
1044 size_t DigitStart = Pos;
1045 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1046 if (DigitEnd == std::string::npos)
1047 DigitEnd = AsmString.size();
1048 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1049 unsigned OperandIndex;
1050 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1051 if (OperandIndex >= FirstIn)
1052 OperandIndex += NumNewOuts;
1053 OS << OperandIndex;
1054 } else {
1055 OS << OperandStr;
1056 }
1057 Pos = DigitEnd;
1058 }
1059 }
1060 AsmString = std::move(OS.str());
1061}
1062
1063/// Add output constraints for EAX:EDX because they are return registers.
1064void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1065 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1066 std::vector<llvm::Type *> &ResultRegTypes,
1067 std::vector<llvm::Type *> &ResultTruncRegTypes,
1068 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1069 unsigned NumOutputs) const {
1070 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1071
1072 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1073 // larger.
1074 if (!Constraints.empty())
1075 Constraints += ',';
1076 if (RetWidth <= 32) {
1077 Constraints += "={eax}";
1078 ResultRegTypes.push_back(CGF.Int32Ty);
1079 } else {
1080 // Use the 'A' constraint for EAX:EDX.
1081 Constraints += "=A";
1082 ResultRegTypes.push_back(CGF.Int64Ty);
1083 }
1084
1085 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1086 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1087 ResultTruncRegTypes.push_back(CoerceTy);
1088
1089 // Coerce the integer by bitcasting the return slot pointer.
1090 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1091 CoerceTy->getPointerTo()));
1092 ResultRegDests.push_back(ReturnSlot);
1093
1094 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1095}
1096
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001097/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001098/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001099bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1100 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101 uint64_t Size = Context.getTypeSize(Ty);
1102
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001103 // For i386, type must be register sized.
1104 // For the MCU ABI, it only needs to be <= 8-byte
1105 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1106 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001107
1108 if (Ty->isVectorType()) {
1109 // 64- and 128- bit vectors inside structures are not returned in
1110 // registers.
1111 if (Size == 64 || Size == 128)
1112 return false;
1113
1114 return true;
1115 }
1116
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001117 // If this is a builtin, pointer, enum, complex type, member pointer, or
1118 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001119 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001120 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001121 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001122 return true;
1123
1124 // Arrays are treated like records.
1125 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001126 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001127
1128 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001129 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001130 if (!RT) return false;
1131
Anders Carlsson40446e82010-01-27 03:25:19 +00001132 // FIXME: Traverse bases here too.
1133
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001134 // Structure types are passed in register if all fields would be
1135 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001136 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001137 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001138 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001139 continue;
1140
1141 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001142 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001143 return false;
1144 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001145 return true;
1146}
1147
Reid Kleckner04046052016-05-02 17:41:07 +00001148static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1149 // Treat complex types as the element type.
1150 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1151 Ty = CTy->getElementType();
1152
1153 // Check for a type which we know has a simple scalar argument-passing
1154 // convention without any padding. (We're specifically looking for 32
1155 // and 64-bit integer and integer-equivalents, float, and double.)
1156 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1157 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1158 return false;
1159
1160 uint64_t Size = Context.getTypeSize(Ty);
1161 return Size == 32 || Size == 64;
1162}
1163
1164/// Test whether an argument type which is to be passed indirectly (on the
1165/// stack) would have the equivalent layout if it was expanded into separate
1166/// arguments. If so, we prefer to do the latter to avoid inhibiting
1167/// optimizations.
1168bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1169 // We can only expand structure types.
1170 const RecordType *RT = Ty->getAs<RecordType>();
1171 if (!RT)
1172 return false;
1173 const RecordDecl *RD = RT->getDecl();
1174 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1175 if (!IsWin32StructABI ) {
1176 // On non-Windows, we have to conservatively match our old bitcode
1177 // prototypes in order to be ABI-compatible at the bitcode level.
1178 if (!CXXRD->isCLike())
1179 return false;
1180 } else {
1181 // Don't do this for dynamic classes.
1182 if (CXXRD->isDynamicClass())
1183 return false;
1184 // Don't do this if there are any non-empty bases.
1185 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
1186 if (!isEmptyRecord(getContext(), Base.getType(), /*AllowArrays=*/true))
1187 return false;
1188 }
1189 }
1190 }
1191
1192 uint64_t Size = 0;
1193
1194 for (const auto *FD : RD->fields()) {
1195 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1196 // argument is smaller than 32-bits, expanding the struct will create
1197 // alignment padding.
1198 if (!is32Or64BitBasicType(FD->getType(), getContext()))
1199 return false;
1200
1201 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1202 // how to expand them yet, and the predicate for telling if a bitfield still
1203 // counts as "basic" is more complicated than what we were doing previously.
1204 if (FD->isBitField())
1205 return false;
1206
1207 Size += getContext().getTypeSize(FD->getType());
1208 }
1209
1210 // We can do this if there was no alignment padding.
1211 return Size == getContext().getTypeSize(Ty);
1212}
1213
John McCall7f416cc2015-09-08 08:05:57 +00001214ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001215 // If the return value is indirect, then the hidden argument is consuming one
1216 // integer register.
1217 if (State.FreeRegs) {
1218 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001219 if (!IsMCUABI)
1220 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001221 }
John McCall7f416cc2015-09-08 08:05:57 +00001222 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001223}
1224
Eric Christopher7565e0d2015-05-29 23:09:49 +00001225ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1226 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001227 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001228 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001229
Reid Kleckner80944df2014-10-31 22:00:51 +00001230 const Type *Base = nullptr;
1231 uint64_t NumElts = 0;
1232 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1233 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1234 // The LLVM struct type for such an aggregate should lower properly.
1235 return ABIArgInfo::getDirect();
1236 }
1237
Chris Lattner458b2aa2010-07-29 02:16:43 +00001238 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001239 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001240 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001241 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001242
1243 // 128-bit vectors are a special case; they are returned in
1244 // registers and we need to make sure to pick a type the LLVM
1245 // backend will like.
1246 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001247 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001248 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001249
1250 // Always return in register if it fits in a general purpose
1251 // register, or if it is 64 bits and has a single element.
1252 if ((Size == 8 || Size == 16 || Size == 32) ||
1253 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001254 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001255 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001256
John McCall7f416cc2015-09-08 08:05:57 +00001257 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001258 }
1259
1260 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001261 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001262
John McCalla1dee5302010-08-22 10:59:02 +00001263 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001264 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001265 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001266 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001267 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001268 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001269
David Chisnallde3a0692009-08-17 23:08:21 +00001270 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001271 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001272 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001273
Denis Zobnin380b2242016-02-11 11:26:03 +00001274 // Ignore empty structs/unions.
1275 if (isEmptyRecord(getContext(), RetTy, true))
1276 return ABIArgInfo::getIgnore();
1277
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001278 // Small structures which are register sized are generally returned
1279 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001280 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001281 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001282
1283 // As a special-case, if the struct is a "single-element" struct, and
1284 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001285 // floating-point register. (MSVC does not apply this special case.)
1286 // We apply a similar transformation for pointer types to improve the
1287 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001288 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001289 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001290 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001291 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1292
1293 // FIXME: We should be able to narrow this integer in cases with dead
1294 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001295 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001296 }
1297
John McCall7f416cc2015-09-08 08:05:57 +00001298 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001299 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001300
Chris Lattner458b2aa2010-07-29 02:16:43 +00001301 // Treat an enum type as its underlying type.
1302 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1303 RetTy = EnumTy->getDecl()->getIntegerType();
1304
1305 return (RetTy->isPromotableIntegerType() ?
1306 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001307}
1308
Eli Friedman7919bea2012-06-05 19:40:46 +00001309static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1310 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1311}
1312
Daniel Dunbared23de32010-09-16 20:42:00 +00001313static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1314 const RecordType *RT = Ty->getAs<RecordType>();
1315 if (!RT)
1316 return 0;
1317 const RecordDecl *RD = RT->getDecl();
1318
1319 // If this is a C++ record, check the bases first.
1320 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001321 for (const auto &I : CXXRD->bases())
1322 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001323 return false;
1324
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001325 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001326 QualType FT = i->getType();
1327
Eli Friedman7919bea2012-06-05 19:40:46 +00001328 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001329 return true;
1330
1331 if (isRecordWithSSEVectorType(Context, FT))
1332 return true;
1333 }
1334
1335 return false;
1336}
1337
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001338unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1339 unsigned Align) const {
1340 // Otherwise, if the alignment is less than or equal to the minimum ABI
1341 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001342 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001343 return 0; // Use default alignment.
1344
1345 // On non-Darwin, the stack type alignment is always 4.
1346 if (!IsDarwinVectorABI) {
1347 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001348 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001349 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001350
Daniel Dunbared23de32010-09-16 20:42:00 +00001351 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001352 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1353 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001354 return 16;
1355
1356 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001357}
1358
Rafael Espindola703c47f2012-10-19 05:04:37 +00001359ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001360 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001361 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001362 if (State.FreeRegs) {
1363 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001364 if (!IsMCUABI)
1365 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001366 }
John McCall7f416cc2015-09-08 08:05:57 +00001367 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001368 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001369
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001370 // Compute the byval alignment.
1371 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1372 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1373 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001374 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001375
1376 // If the stack alignment is less than the type alignment, realign the
1377 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001378 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001379 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1380 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001381}
1382
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001383X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1384 const Type *T = isSingleElementStruct(Ty, getContext());
1385 if (!T)
1386 T = Ty.getTypePtr();
1387
1388 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1389 BuiltinType::Kind K = BT->getKind();
1390 if (K == BuiltinType::Float || K == BuiltinType::Double)
1391 return Float;
1392 }
1393 return Integer;
1394}
1395
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001396bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001397 if (!IsSoftFloatABI) {
1398 Class C = classify(Ty);
1399 if (C == Float)
1400 return false;
1401 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001402
Rafael Espindola077dd592012-10-24 01:58:58 +00001403 unsigned Size = getContext().getTypeSize(Ty);
1404 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001405
1406 if (SizeInRegs == 0)
1407 return false;
1408
Michael Kuperstein68901882015-10-25 08:18:20 +00001409 if (!IsMCUABI) {
1410 if (SizeInRegs > State.FreeRegs) {
1411 State.FreeRegs = 0;
1412 return false;
1413 }
1414 } else {
1415 // The MCU psABI allows passing parameters in-reg even if there are
1416 // earlier parameters that are passed on the stack. Also,
1417 // it does not allow passing >8-byte structs in-register,
1418 // even if there are 3 free registers available.
1419 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1420 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001421 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001422
Reid Kleckner661f35b2014-01-18 01:12:41 +00001423 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001424 return true;
1425}
1426
1427bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1428 bool &InReg,
1429 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001430 // On Windows, aggregates other than HFAs are never passed in registers, and
1431 // they do not consume register slots. Homogenous floating-point aggregates
1432 // (HFAs) have already been dealt with at this point.
1433 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1434 return false;
1435
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001436 NeedsPadding = false;
1437 InReg = !IsMCUABI;
1438
1439 if (!updateFreeRegs(Ty, State))
1440 return false;
1441
1442 if (IsMCUABI)
1443 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001444
Reid Kleckner80944df2014-10-31 22:00:51 +00001445 if (State.CC == llvm::CallingConv::X86_FastCall ||
1446 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001447 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001448 NeedsPadding = true;
1449
Rafael Espindola077dd592012-10-24 01:58:58 +00001450 return false;
1451 }
1452
Rafael Espindola703c47f2012-10-19 05:04:37 +00001453 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001454}
1455
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001456bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1457 if (!updateFreeRegs(Ty, State))
1458 return false;
1459
1460 if (IsMCUABI)
1461 return false;
1462
1463 if (State.CC == llvm::CallingConv::X86_FastCall ||
1464 State.CC == llvm::CallingConv::X86_VectorCall) {
1465 if (getContext().getTypeSize(Ty) > 32)
1466 return false;
1467
1468 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1469 Ty->isReferenceType());
1470 }
1471
1472 return true;
1473}
1474
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001475ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1476 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001477 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001478
Reid Klecknerb1be6832014-11-15 01:41:41 +00001479 Ty = useFirstFieldIfTransparentUnion(Ty);
1480
Reid Kleckner80944df2014-10-31 22:00:51 +00001481 // Check with the C++ ABI first.
1482 const RecordType *RT = Ty->getAs<RecordType>();
1483 if (RT) {
1484 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1485 if (RAA == CGCXXABI::RAA_Indirect) {
1486 return getIndirectResult(Ty, false, State);
1487 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1488 // The field index doesn't matter, we'll fix it up later.
1489 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1490 }
1491 }
1492
1493 // vectorcall adds the concept of a homogenous vector aggregate, similar
1494 // to other targets.
1495 const Type *Base = nullptr;
1496 uint64_t NumElts = 0;
1497 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1498 isHomogeneousAggregate(Ty, Base, NumElts)) {
1499 if (State.FreeSSERegs >= NumElts) {
1500 State.FreeSSERegs -= NumElts;
1501 if (Ty->isBuiltinType() || Ty->isVectorType())
1502 return ABIArgInfo::getDirect();
1503 return ABIArgInfo::getExpand();
1504 }
1505 return getIndirectResult(Ty, /*ByVal=*/false, State);
1506 }
1507
1508 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001509 // Structures with flexible arrays are always indirect.
1510 // FIXME: This should not be byval!
1511 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1512 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001513
Reid Kleckner04046052016-05-02 17:41:07 +00001514 // Ignore empty structs/unions on non-Windows.
1515 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001516 return ABIArgInfo::getIgnore();
1517
Rafael Espindolafad28de2012-10-24 01:59:00 +00001518 llvm::LLVMContext &LLVMContext = getVMContext();
1519 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001520 bool NeedsPadding = false;
1521 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001522 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001523 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001524 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001525 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001526 if (InReg)
1527 return ABIArgInfo::getDirectInReg(Result);
1528 else
1529 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001530 }
Craig Topper8a13c412014-05-21 05:09:00 +00001531 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001532
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001533 // Expand small (<= 128-bit) record types when we know that the stack layout
1534 // of those arguments will match the struct. This is important because the
1535 // LLVM backend isn't smart enough to remove byval, which inhibits many
1536 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001537 // Don't do this for the MCU if there are still free integer registers
1538 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001539 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1540 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001541 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001542 State.CC == llvm::CallingConv::X86_FastCall ||
1543 State.CC == llvm::CallingConv::X86_VectorCall,
1544 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001545
Reid Kleckner661f35b2014-01-18 01:12:41 +00001546 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001547 }
1548
Chris Lattnerd774ae92010-08-26 20:05:13 +00001549 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001550 // On Darwin, some vectors are passed in memory, we handle this by passing
1551 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001552 if (IsDarwinVectorABI) {
1553 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001554 if ((Size == 8 || Size == 16 || Size == 32) ||
1555 (Size == 64 && VT->getNumElements() == 1))
1556 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1557 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001558 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001559
Chad Rosier651c1832013-03-25 21:00:27 +00001560 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1561 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001562
Chris Lattnerd774ae92010-08-26 20:05:13 +00001563 return ABIArgInfo::getDirect();
1564 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001565
1566
Chris Lattner458b2aa2010-07-29 02:16:43 +00001567 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1568 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001569
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001570 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001571
1572 if (Ty->isPromotableIntegerType()) {
1573 if (InReg)
1574 return ABIArgInfo::getExtendInReg();
1575 return ABIArgInfo::getExtend();
1576 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001577
Rafael Espindola703c47f2012-10-19 05:04:37 +00001578 if (InReg)
1579 return ABIArgInfo::getDirectInReg();
1580 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001581}
1582
Rafael Espindolaa6472962012-07-24 00:01:07 +00001583void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001584 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001585 if (IsMCUABI)
1586 State.FreeRegs = 3;
1587 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001588 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001589 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1590 State.FreeRegs = 2;
1591 State.FreeSSERegs = 6;
1592 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001593 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001594 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001595 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001596
Reid Kleckner677539d2014-07-10 01:58:55 +00001597 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001598 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001599 } else if (FI.getReturnInfo().isIndirect()) {
1600 // The C++ ABI is not aware of register usage, so we have to check if the
1601 // return value was sret and put it in a register ourselves if appropriate.
1602 if (State.FreeRegs) {
1603 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001604 if (!IsMCUABI)
1605 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001606 }
1607 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001608
Peter Collingbournef7706832014-12-12 23:41:25 +00001609 // The chain argument effectively gives us another free register.
1610 if (FI.isChainCall())
1611 ++State.FreeRegs;
1612
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001613 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001614 for (auto &I : FI.arguments()) {
1615 I.info = classifyArgumentType(I.type, State);
1616 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001617 }
1618
1619 // If we needed to use inalloca for any argument, do a second pass and rewrite
1620 // all the memory arguments to use inalloca.
1621 if (UsedInAlloca)
1622 rewriteWithInAlloca(FI);
1623}
1624
1625void
1626X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001627 CharUnits &StackOffset, ABIArgInfo &Info,
1628 QualType Type) const {
1629 // Arguments are always 4-byte-aligned.
1630 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1631
1632 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001633 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1634 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001635 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001636
John McCall7f416cc2015-09-08 08:05:57 +00001637 // Insert padding bytes to respect alignment.
1638 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001639 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001640 if (StackOffset != FieldEnd) {
1641 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001642 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001643 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001644 FrameFields.push_back(Ty);
1645 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001646}
1647
Reid Kleckner852361d2014-07-26 00:12:26 +00001648static bool isArgInAlloca(const ABIArgInfo &Info) {
1649 // Leave ignored and inreg arguments alone.
1650 switch (Info.getKind()) {
1651 case ABIArgInfo::InAlloca:
1652 return true;
1653 case ABIArgInfo::Indirect:
1654 assert(Info.getIndirectByVal());
1655 return true;
1656 case ABIArgInfo::Ignore:
1657 return false;
1658 case ABIArgInfo::Direct:
1659 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001660 if (Info.getInReg())
1661 return false;
1662 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001663 case ABIArgInfo::Expand:
1664 case ABIArgInfo::CoerceAndExpand:
1665 // These are aggregate types which are never passed in registers when
1666 // inalloca is involved.
1667 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001668 }
1669 llvm_unreachable("invalid enum");
1670}
1671
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001672void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1673 assert(IsWin32StructABI && "inalloca only supported on win32");
1674
1675 // Build a packed struct type for all of the arguments in memory.
1676 SmallVector<llvm::Type *, 6> FrameFields;
1677
John McCall7f416cc2015-09-08 08:05:57 +00001678 // The stack alignment is always 4.
1679 CharUnits StackAlign = CharUnits::fromQuantity(4);
1680
1681 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001682 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1683
1684 // Put 'this' into the struct before 'sret', if necessary.
1685 bool IsThisCall =
1686 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1687 ABIArgInfo &Ret = FI.getReturnInfo();
1688 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1689 isArgInAlloca(I->info)) {
1690 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1691 ++I;
1692 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001693
1694 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001695 if (Ret.isIndirect() && !Ret.getInReg()) {
1696 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1697 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001698 // On Windows, the hidden sret parameter is always returned in eax.
1699 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001700 }
1701
1702 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001703 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001704 ++I;
1705
1706 // Put arguments passed in memory into the struct.
1707 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001708 if (isArgInAlloca(I->info))
1709 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001710 }
1711
1712 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001713 /*isPacked=*/true),
1714 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001715}
1716
John McCall7f416cc2015-09-08 08:05:57 +00001717Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1718 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001719
John McCall7f416cc2015-09-08 08:05:57 +00001720 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001721
John McCall7f416cc2015-09-08 08:05:57 +00001722 // x86-32 changes the alignment of certain arguments on the stack.
1723 //
1724 // Just messing with TypeInfo like this works because we never pass
1725 // anything indirectly.
1726 TypeInfo.second = CharUnits::fromQuantity(
1727 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001728
John McCall7f416cc2015-09-08 08:05:57 +00001729 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1730 TypeInfo, CharUnits::fromQuantity(4),
1731 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001732}
1733
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001734bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1735 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1736 assert(Triple.getArch() == llvm::Triple::x86);
1737
1738 switch (Opts.getStructReturnConvention()) {
1739 case CodeGenOptions::SRCK_Default:
1740 break;
1741 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1742 return false;
1743 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1744 return true;
1745 }
1746
Michael Kupersteind749f232015-10-27 07:46:22 +00001747 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001748 return true;
1749
1750 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001751 case llvm::Triple::DragonFly:
1752 case llvm::Triple::FreeBSD:
1753 case llvm::Triple::OpenBSD:
1754 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001755 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001756 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001757 default:
1758 return false;
1759 }
1760}
1761
Eric Christopher162c91c2015-06-05 22:03:00 +00001762void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001763 llvm::GlobalValue *GV,
1764 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001765 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001766 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1767 // Get the LLVM function.
1768 llvm::Function *Fn = cast<llvm::Function>(GV);
1769
1770 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001771 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001772 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001773 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1774 llvm::AttributeSet::get(CGM.getLLVMContext(),
1775 llvm::AttributeSet::FunctionIndex,
1776 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001777 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001778 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1779 llvm::Function *Fn = cast<llvm::Function>(GV);
1780 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1781 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001782 }
1783}
1784
John McCallbeec5a02010-03-06 00:35:14 +00001785bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1786 CodeGen::CodeGenFunction &CGF,
1787 llvm::Value *Address) const {
1788 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001789
Chris Lattnerece04092012-02-07 00:39:47 +00001790 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001791
John McCallbeec5a02010-03-06 00:35:14 +00001792 // 0-7 are the eight integer registers; the order is different
1793 // on Darwin (for EH), but the range is the same.
1794 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001795 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001796
John McCallc8e01702013-04-16 22:48:15 +00001797 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001798 // 12-16 are st(0..4). Not sure why we stop at 4.
1799 // These have size 16, which is sizeof(long double) on
1800 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001801 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001802 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001803
John McCallbeec5a02010-03-06 00:35:14 +00001804 } else {
1805 // 9 is %eflags, which doesn't get a size on Darwin for some
1806 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001807 Builder.CreateAlignedStore(
1808 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1809 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001810
1811 // 11-16 are st(0..5). Not sure why we stop at 5.
1812 // These have size 12, which is sizeof(long double) on
1813 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001814 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001815 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1816 }
John McCallbeec5a02010-03-06 00:35:14 +00001817
1818 return false;
1819}
1820
Chris Lattner0cf24192010-06-28 20:05:43 +00001821//===----------------------------------------------------------------------===//
1822// X86-64 ABI Implementation
1823//===----------------------------------------------------------------------===//
1824
1825
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001826namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001827/// The AVX ABI level for X86 targets.
1828enum class X86AVXABILevel {
1829 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001830 AVX,
1831 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001832};
1833
1834/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1835static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1836 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001837 case X86AVXABILevel::AVX512:
1838 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001839 case X86AVXABILevel::AVX:
1840 return 256;
1841 case X86AVXABILevel::None:
1842 return 128;
1843 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001844 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001845}
1846
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001847/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001848class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001849 enum Class {
1850 Integer = 0,
1851 SSE,
1852 SSEUp,
1853 X87,
1854 X87Up,
1855 ComplexX87,
1856 NoClass,
1857 Memory
1858 };
1859
1860 /// merge - Implement the X86_64 ABI merging algorithm.
1861 ///
1862 /// Merge an accumulating classification \arg Accum with a field
1863 /// classification \arg Field.
1864 ///
1865 /// \param Accum - The accumulating classification. This should
1866 /// always be either NoClass or the result of a previous merge
1867 /// call. In addition, this should never be Memory (the caller
1868 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001869 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001870
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001871 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1872 ///
1873 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1874 /// final MEMORY or SSE classes when necessary.
1875 ///
1876 /// \param AggregateSize - The size of the current aggregate in
1877 /// the classification process.
1878 ///
1879 /// \param Lo - The classification for the parts of the type
1880 /// residing in the low word of the containing object.
1881 ///
1882 /// \param Hi - The classification for the parts of the type
1883 /// residing in the higher words of the containing object.
1884 ///
1885 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1886
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001887 /// classify - Determine the x86_64 register classes in which the
1888 /// given type T should be passed.
1889 ///
1890 /// \param Lo - The classification for the parts of the type
1891 /// residing in the low word of the containing object.
1892 ///
1893 /// \param Hi - The classification for the parts of the type
1894 /// residing in the high word of the containing object.
1895 ///
1896 /// \param OffsetBase - The bit offset of this type in the
1897 /// containing object. Some parameters are classified different
1898 /// depending on whether they straddle an eightbyte boundary.
1899 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001900 /// \param isNamedArg - Whether the argument in question is a "named"
1901 /// argument, as used in AMD64-ABI 3.5.7.
1902 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001903 /// If a word is unused its result will be NoClass; if a type should
1904 /// be passed in Memory then at least the classification of \arg Lo
1905 /// will be Memory.
1906 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001907 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001908 ///
1909 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1910 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001911 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1912 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001913
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001914 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001915 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1916 unsigned IROffset, QualType SourceTy,
1917 unsigned SourceOffset) const;
1918 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1919 unsigned IROffset, QualType SourceTy,
1920 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001921
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001922 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001923 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001924 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001925
1926 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001927 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001928 ///
1929 /// \param freeIntRegs - The number of free integer registers remaining
1930 /// available.
1931 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001932
Chris Lattner458b2aa2010-07-29 02:16:43 +00001933 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001934
Bill Wendling5cd41c42010-10-18 03:41:31 +00001935 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001936 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001937 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001938 unsigned &neededSSE,
1939 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001940
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001941 bool IsIllegalVectorType(QualType Ty) const;
1942
John McCalle0fda732011-04-21 01:20:55 +00001943 /// The 0.98 ABI revision clarified a lot of ambiguities,
1944 /// unfortunately in ways that were not always consistent with
1945 /// certain previous compilers. In particular, platforms which
1946 /// required strict binary compatibility with older versions of GCC
1947 /// may need to exempt themselves.
1948 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001949 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001950 }
1951
David Majnemere2ae2282016-03-04 05:26:16 +00001952 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1953 // compilers require us to classify it as INTEGER.
1954 bool classifyIntegerMMXAsSSE() const {
1955 const llvm::Triple &Triple = getTarget().getTriple();
1956 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1957 return false;
1958 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1959 return false;
1960 return true;
1961 }
1962
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001963 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001964 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1965 // 64-bit hardware.
1966 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001967
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001968public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001969 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00001970 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001971 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001972 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001973
John McCalla729c622012-02-17 03:33:10 +00001974 bool isPassedUsingAVXType(QualType type) const {
1975 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001976 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001977 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1978 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001979 if (info.isDirect()) {
1980 llvm::Type *ty = info.getCoerceToType();
1981 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1982 return (vectorTy->getBitWidth() > 128);
1983 }
1984 return false;
1985 }
1986
Craig Topper4f12f102014-03-12 06:41:41 +00001987 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001988
John McCall7f416cc2015-09-08 08:05:57 +00001989 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1990 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001991 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1992 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001993
1994 bool has64BitPointers() const {
1995 return Has64BitPointers;
1996 }
John McCall12f23522016-04-04 18:33:08 +00001997
1998 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1999 ArrayRef<llvm::Type*> scalars,
2000 bool asReturnValue) const override {
2001 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2002 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002003};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002004
Chris Lattner04dc9572010-08-31 16:44:54 +00002005/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002006class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002007public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002008 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
2009 : ABIInfo(CGT),
2010 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002011
Craig Topper4f12f102014-03-12 06:41:41 +00002012 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002013
John McCall7f416cc2015-09-08 08:05:57 +00002014 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2015 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002016
2017 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2018 // FIXME: Assumes vectorcall is in use.
2019 return isX86VectorTypeForVectorCall(getContext(), Ty);
2020 }
2021
2022 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2023 uint64_t NumMembers) const override {
2024 // FIXME: Assumes vectorcall is in use.
2025 return isX86VectorCallAggregateSmallEnough(NumMembers);
2026 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002027
2028private:
2029 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
2030 bool IsReturnType) const;
2031
2032 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002033};
2034
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002035class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2036public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002037 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002038 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002039
John McCalla729c622012-02-17 03:33:10 +00002040 const X86_64ABIInfo &getABIInfo() const {
2041 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2042 }
2043
Craig Topper4f12f102014-03-12 06:41:41 +00002044 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002045 return 7;
2046 }
2047
2048 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002049 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002050 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002051
John McCall943fae92010-05-27 06:19:26 +00002052 // 0-15 are the 16 integer registers.
2053 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002054 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002055 return false;
2056 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002057
Jay Foad7c57be32011-07-11 09:56:20 +00002058 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002059 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002060 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002061 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2062 }
2063
John McCalla729c622012-02-17 03:33:10 +00002064 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002065 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002066 // The default CC on x86-64 sets %al to the number of SSA
2067 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002068 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002069 // that when AVX types are involved: the ABI explicitly states it is
2070 // undefined, and it doesn't work in practice because of how the ABI
2071 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002072 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002073 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002074 for (CallArgList::const_iterator
2075 it = args.begin(), ie = args.end(); it != ie; ++it) {
2076 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2077 HasAVXType = true;
2078 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002079 }
2080 }
John McCalla729c622012-02-17 03:33:10 +00002081
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002082 if (!HasAVXType)
2083 return true;
2084 }
John McCallcbc038a2011-09-21 08:08:30 +00002085
John McCalla729c622012-02-17 03:33:10 +00002086 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002087 }
2088
Craig Topper4f12f102014-03-12 06:41:41 +00002089 llvm::Constant *
2090 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002091 unsigned Sig;
2092 if (getABIInfo().has64BitPointers())
2093 Sig = (0xeb << 0) | // jmp rel8
2094 (0x0a << 8) | // .+0x0c
2095 ('F' << 16) |
2096 ('T' << 24);
2097 else
2098 Sig = (0xeb << 0) | // jmp rel8
2099 (0x06 << 8) | // .+0x08
2100 ('F' << 16) |
2101 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002102 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2103 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002104
2105 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2106 CodeGen::CodeGenModule &CGM) const override {
2107 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2108 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2109 llvm::Function *Fn = cast<llvm::Function>(GV);
2110 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2111 }
2112 }
2113 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002114};
2115
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002116class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2117public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002118 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2119 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002120
2121 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002122 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002123 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002124 // If the argument contains a space, enclose it in quotes.
2125 if (Lib.find(" ") != StringRef::npos)
2126 Opt += "\"" + Lib.str() + "\"";
2127 else
2128 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002129 }
2130};
2131
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002132static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002133 // If the argument does not end in .lib, automatically add the suffix.
2134 // If the argument contains a space, enclose it in quotes.
2135 // This matches the behavior of MSVC.
2136 bool Quote = (Lib.find(" ") != StringRef::npos);
2137 std::string ArgStr = Quote ? "\"" : "";
2138 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002139 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002140 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002141 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002142 return ArgStr;
2143}
2144
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002145class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2146public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002147 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002148 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2149 unsigned NumRegisterParameters)
2150 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002151 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002152
Eric Christopher162c91c2015-06-05 22:03:00 +00002153 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002154 CodeGen::CodeGenModule &CGM) const override;
2155
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002156 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002157 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002158 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002159 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002160 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002161
2162 void getDetectMismatchOption(llvm::StringRef Name,
2163 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002164 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002165 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002166 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002167};
2168
Hans Wennborg77dc2362015-01-20 19:45:50 +00002169static void addStackProbeSizeTargetAttribute(const Decl *D,
2170 llvm::GlobalValue *GV,
2171 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002172 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002173 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2174 llvm::Function *Fn = cast<llvm::Function>(GV);
2175
Eric Christopher7565e0d2015-05-29 23:09:49 +00002176 Fn->addFnAttr("stack-probe-size",
2177 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002178 }
2179 }
2180}
2181
Eric Christopher162c91c2015-06-05 22:03:00 +00002182void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002183 llvm::GlobalValue *GV,
2184 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002185 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002186
2187 addStackProbeSizeTargetAttribute(D, GV, CGM);
2188}
2189
Chris Lattner04dc9572010-08-31 16:44:54 +00002190class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2191public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002192 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2193 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002194 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002195
Eric Christopher162c91c2015-06-05 22:03:00 +00002196 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002197 CodeGen::CodeGenModule &CGM) const override;
2198
Craig Topper4f12f102014-03-12 06:41:41 +00002199 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002200 return 7;
2201 }
2202
2203 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002204 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002205 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002206
Chris Lattner04dc9572010-08-31 16:44:54 +00002207 // 0-15 are the 16 integer registers.
2208 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002209 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002210 return false;
2211 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002212
2213 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002214 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002215 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002216 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002217 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002218
2219 void getDetectMismatchOption(llvm::StringRef Name,
2220 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002221 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002222 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002223 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002224};
2225
Eric Christopher162c91c2015-06-05 22:03:00 +00002226void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002227 llvm::GlobalValue *GV,
2228 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002229 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002230
Alexey Bataevd51e9932016-01-15 04:06:31 +00002231 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2232 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2233 llvm::Function *Fn = cast<llvm::Function>(GV);
2234 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2235 }
2236 }
2237
Hans Wennborg77dc2362015-01-20 19:45:50 +00002238 addStackProbeSizeTargetAttribute(D, GV, CGM);
2239}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002240}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002241
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002242void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2243 Class &Hi) const {
2244 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2245 //
2246 // (a) If one of the classes is Memory, the whole argument is passed in
2247 // memory.
2248 //
2249 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2250 // memory.
2251 //
2252 // (c) If the size of the aggregate exceeds two eightbytes and the first
2253 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2254 // argument is passed in memory. NOTE: This is necessary to keep the
2255 // ABI working for processors that don't support the __m256 type.
2256 //
2257 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2258 //
2259 // Some of these are enforced by the merging logic. Others can arise
2260 // only with unions; for example:
2261 // union { _Complex double; unsigned; }
2262 //
2263 // Note that clauses (b) and (c) were added in 0.98.
2264 //
2265 if (Hi == Memory)
2266 Lo = Memory;
2267 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2268 Lo = Memory;
2269 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2270 Lo = Memory;
2271 if (Hi == SSEUp && Lo != SSE)
2272 Hi = SSE;
2273}
2274
Chris Lattnerd776fb12010-06-28 21:43:59 +00002275X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002276 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2277 // classified recursively so that always two fields are
2278 // considered. The resulting class is calculated according to
2279 // the classes of the fields in the eightbyte:
2280 //
2281 // (a) If both classes are equal, this is the resulting class.
2282 //
2283 // (b) If one of the classes is NO_CLASS, the resulting class is
2284 // the other class.
2285 //
2286 // (c) If one of the classes is MEMORY, the result is the MEMORY
2287 // class.
2288 //
2289 // (d) If one of the classes is INTEGER, the result is the
2290 // INTEGER.
2291 //
2292 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2293 // MEMORY is used as class.
2294 //
2295 // (f) Otherwise class SSE is used.
2296
2297 // Accum should never be memory (we should have returned) or
2298 // ComplexX87 (because this cannot be passed in a structure).
2299 assert((Accum != Memory && Accum != ComplexX87) &&
2300 "Invalid accumulated classification during merge.");
2301 if (Accum == Field || Field == NoClass)
2302 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002303 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002304 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002305 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002306 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002307 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002308 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002309 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2310 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002311 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002312 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002313}
2314
Chris Lattner5c740f12010-06-30 19:14:05 +00002315void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002316 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002317 // FIXME: This code can be simplified by introducing a simple value class for
2318 // Class pairs with appropriate constructor methods for the various
2319 // situations.
2320
2321 // FIXME: Some of the split computations are wrong; unaligned vectors
2322 // shouldn't be passed in registers for example, so there is no chance they
2323 // can straddle an eightbyte. Verify & simplify.
2324
2325 Lo = Hi = NoClass;
2326
2327 Class &Current = OffsetBase < 64 ? Lo : Hi;
2328 Current = Memory;
2329
John McCall9dd450b2009-09-21 23:43:11 +00002330 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002331 BuiltinType::Kind k = BT->getKind();
2332
2333 if (k == BuiltinType::Void) {
2334 Current = NoClass;
2335 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2336 Lo = Integer;
2337 Hi = Integer;
2338 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2339 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002340 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002341 Current = SSE;
2342 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002343 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2344 if (LDF == &llvm::APFloat::IEEEquad) {
2345 Lo = SSE;
2346 Hi = SSEUp;
2347 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2348 Lo = X87;
2349 Hi = X87Up;
2350 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2351 Current = SSE;
2352 } else
2353 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002354 }
2355 // FIXME: _Decimal32 and _Decimal64 are SSE.
2356 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002357 return;
2358 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002359
Chris Lattnerd776fb12010-06-28 21:43:59 +00002360 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002361 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002362 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002363 return;
2364 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002365
Chris Lattnerd776fb12010-06-28 21:43:59 +00002366 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002367 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002368 return;
2369 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002370
Chris Lattnerd776fb12010-06-28 21:43:59 +00002371 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002372 if (Ty->isMemberFunctionPointerType()) {
2373 if (Has64BitPointers) {
2374 // If Has64BitPointers, this is an {i64, i64}, so classify both
2375 // Lo and Hi now.
2376 Lo = Hi = Integer;
2377 } else {
2378 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2379 // straddles an eightbyte boundary, Hi should be classified as well.
2380 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2381 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2382 if (EB_FuncPtr != EB_ThisAdj) {
2383 Lo = Hi = Integer;
2384 } else {
2385 Current = Integer;
2386 }
2387 }
2388 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002389 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002390 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002391 return;
2392 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002393
Chris Lattnerd776fb12010-06-28 21:43:59 +00002394 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002395 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002396 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2397 // gcc passes the following as integer:
2398 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2399 // 2 bytes - <2 x char>, <1 x short>
2400 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002401 Current = Integer;
2402
2403 // If this type crosses an eightbyte boundary, it should be
2404 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002405 uint64_t EB_Lo = (OffsetBase) / 64;
2406 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2407 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002408 Hi = Lo;
2409 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002410 QualType ElementType = VT->getElementType();
2411
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002412 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002413 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002414 return;
2415
David Majnemere2ae2282016-03-04 05:26:16 +00002416 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2417 // pass them as integer. For platforms where clang is the de facto
2418 // platform compiler, we must continue to use integer.
2419 if (!classifyIntegerMMXAsSSE() &&
2420 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2421 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2422 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2423 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002424 Current = Integer;
2425 else
2426 Current = SSE;
2427
2428 // If this type crosses an eightbyte boundary, it should be
2429 // split.
2430 if (OffsetBase && OffsetBase != 64)
2431 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002432 } else if (Size == 128 ||
2433 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002434 // Arguments of 256-bits are split into four eightbyte chunks. The
2435 // least significant one belongs to class SSE and all the others to class
2436 // SSEUP. The original Lo and Hi design considers that types can't be
2437 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2438 // This design isn't correct for 256-bits, but since there're no cases
2439 // where the upper parts would need to be inspected, avoid adding
2440 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002441 //
2442 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2443 // registers if they are "named", i.e. not part of the "..." of a
2444 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002445 //
2446 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2447 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002448 Lo = SSE;
2449 Hi = SSEUp;
2450 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002451 return;
2452 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002453
Chris Lattnerd776fb12010-06-28 21:43:59 +00002454 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002455 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002456
Chris Lattner2b037972010-07-29 02:01:43 +00002457 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002458 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002459 if (Size <= 64)
2460 Current = Integer;
2461 else if (Size <= 128)
2462 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002463 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002464 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002465 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002466 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002467 } else if (ET == getContext().LongDoubleTy) {
2468 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2469 if (LDF == &llvm::APFloat::IEEEquad)
2470 Current = Memory;
2471 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2472 Current = ComplexX87;
2473 else if (LDF == &llvm::APFloat::IEEEdouble)
2474 Lo = Hi = SSE;
2475 else
2476 llvm_unreachable("unexpected long double representation!");
2477 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002478
2479 // If this complex type crosses an eightbyte boundary then it
2480 // should be split.
2481 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002482 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002483 if (Hi == NoClass && EB_Real != EB_Imag)
2484 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002485
Chris Lattnerd776fb12010-06-28 21:43:59 +00002486 return;
2487 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002488
Chris Lattner2b037972010-07-29 02:01:43 +00002489 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002490 // Arrays are treated like structures.
2491
Chris Lattner2b037972010-07-29 02:01:43 +00002492 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002493
2494 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002495 // than eight eightbytes, ..., it has class MEMORY.
2496 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002497 return;
2498
2499 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2500 // fields, it has class MEMORY.
2501 //
2502 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002503 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002504 return;
2505
2506 // Otherwise implement simplified merge. We could be smarter about
2507 // this, but it isn't worth it and would be harder to verify.
2508 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002509 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002510 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002511
2512 // The only case a 256-bit wide vector could be used is when the array
2513 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2514 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002515 //
2516 if (Size > 128 &&
2517 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002518 return;
2519
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002520 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2521 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002522 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002523 Lo = merge(Lo, FieldLo);
2524 Hi = merge(Hi, FieldHi);
2525 if (Lo == Memory || Hi == Memory)
2526 break;
2527 }
2528
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002529 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002530 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002531 return;
2532 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002533
Chris Lattnerd776fb12010-06-28 21:43:59 +00002534 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002535 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002536
2537 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002538 // than eight eightbytes, ..., it has class MEMORY.
2539 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002540 return;
2541
Anders Carlsson20759ad2009-09-16 15:53:40 +00002542 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2543 // copy constructor or a non-trivial destructor, it is passed by invisible
2544 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002545 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002546 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002547
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002548 const RecordDecl *RD = RT->getDecl();
2549
2550 // Assume variable sized types are passed in memory.
2551 if (RD->hasFlexibleArrayMember())
2552 return;
2553
Chris Lattner2b037972010-07-29 02:01:43 +00002554 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555
2556 // Reset Lo class, this will be recomputed.
2557 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002558
2559 // If this is a C++ record, classify the bases first.
2560 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002561 for (const auto &I : CXXRD->bases()) {
2562 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002563 "Unexpected base class!");
2564 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002565 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002566
2567 // Classify this field.
2568 //
2569 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2570 // single eightbyte, each is classified separately. Each eightbyte gets
2571 // initialized to class NO_CLASS.
2572 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002573 uint64_t Offset =
2574 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002575 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002576 Lo = merge(Lo, FieldLo);
2577 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002578 if (Lo == Memory || Hi == Memory) {
2579 postMerge(Size, Lo, Hi);
2580 return;
2581 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002582 }
2583 }
2584
2585 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002586 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002587 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002588 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002589 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2590 bool BitField = i->isBitField();
2591
David Majnemerb439dfe2016-08-15 07:20:40 +00002592 // Ignore padding bit-fields.
2593 if (BitField && i->isUnnamedBitfield())
2594 continue;
2595
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002596 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2597 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002598 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002599 // The only case a 256-bit wide vector could be used is when the struct
2600 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2601 // to work for sizes wider than 128, early check and fallback to memory.
2602 //
David Majnemerb229cb02016-08-15 06:39:18 +00002603 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2604 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002605 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002606 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002607 return;
2608 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002609 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002610 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002611 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002612 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002613 return;
2614 }
2615
2616 // Classify this field.
2617 //
2618 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2619 // exceeds a single eightbyte, each is classified
2620 // separately. Each eightbyte gets initialized to class
2621 // NO_CLASS.
2622 Class FieldLo, FieldHi;
2623
2624 // Bit-fields require special handling, they do not force the
2625 // structure to be passed in memory even if unaligned, and
2626 // therefore they can straddle an eightbyte.
2627 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002628 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002629 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002630 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002631
2632 uint64_t EB_Lo = Offset / 64;
2633 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002634
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002635 if (EB_Lo) {
2636 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2637 FieldLo = NoClass;
2638 FieldHi = Integer;
2639 } else {
2640 FieldLo = Integer;
2641 FieldHi = EB_Hi ? Integer : NoClass;
2642 }
2643 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002644 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002645 Lo = merge(Lo, FieldLo);
2646 Hi = merge(Hi, FieldHi);
2647 if (Lo == Memory || Hi == Memory)
2648 break;
2649 }
2650
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002651 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002652 }
2653}
2654
Chris Lattner22a931e2010-06-29 06:01:59 +00002655ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002656 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2657 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002658 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002659 // Treat an enum type as its underlying type.
2660 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2661 Ty = EnumTy->getDecl()->getIntegerType();
2662
2663 return (Ty->isPromotableIntegerType() ?
2664 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2665 }
2666
John McCall7f416cc2015-09-08 08:05:57 +00002667 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002668}
2669
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002670bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2671 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2672 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002673 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002674 if (Size <= 64 || Size > LargestVector)
2675 return true;
2676 }
2677
2678 return false;
2679}
2680
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002681ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2682 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002683 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2684 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002685 //
2686 // This assumption is optimistic, as there could be free registers available
2687 // when we need to pass this argument in memory, and LLVM could try to pass
2688 // the argument in the free register. This does not seem to happen currently,
2689 // but this code would be much safer if we could mark the argument with
2690 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002691 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002692 // Treat an enum type as its underlying type.
2693 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2694 Ty = EnumTy->getDecl()->getIntegerType();
2695
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002696 return (Ty->isPromotableIntegerType() ?
2697 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002698 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002699
Mark Lacey3825e832013-10-06 01:33:34 +00002700 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002701 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002702
Chris Lattner44c2b902011-05-22 23:21:23 +00002703 // Compute the byval alignment. We specify the alignment of the byval in all
2704 // cases so that the mid-level optimizer knows the alignment of the byval.
2705 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002706
2707 // Attempt to avoid passing indirect results using byval when possible. This
2708 // is important for good codegen.
2709 //
2710 // We do this by coercing the value into a scalar type which the backend can
2711 // handle naturally (i.e., without using byval).
2712 //
2713 // For simplicity, we currently only do this when we have exhausted all of the
2714 // free integer registers. Doing this when there are free integer registers
2715 // would require more care, as we would have to ensure that the coerced value
2716 // did not claim the unused register. That would require either reording the
2717 // arguments to the function (so that any subsequent inreg values came first),
2718 // or only doing this optimization when there were no following arguments that
2719 // might be inreg.
2720 //
2721 // We currently expect it to be rare (particularly in well written code) for
2722 // arguments to be passed on the stack when there are still free integer
2723 // registers available (this would typically imply large structs being passed
2724 // by value), so this seems like a fair tradeoff for now.
2725 //
2726 // We can revisit this if the backend grows support for 'onstack' parameter
2727 // attributes. See PR12193.
2728 if (freeIntRegs == 0) {
2729 uint64_t Size = getContext().getTypeSize(Ty);
2730
2731 // If this type fits in an eightbyte, coerce it into the matching integral
2732 // type, which will end up on the stack (with alignment 8).
2733 if (Align == 8 && Size <= 64)
2734 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2735 Size));
2736 }
2737
John McCall7f416cc2015-09-08 08:05:57 +00002738 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002739}
2740
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002741/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2742/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002743llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002744 // Wrapper structs/arrays that only contain vectors are passed just like
2745 // vectors; strip them off if present.
2746 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2747 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002748
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002749 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002750 if (isa<llvm::VectorType>(IRType) ||
2751 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002752 return IRType;
2753
2754 // We couldn't find the preferred IR vector type for 'Ty'.
2755 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002756 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002757
2758 // Return a LLVM IR vector type based on the size of 'Ty'.
2759 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2760 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002761}
2762
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002763/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2764/// is known to either be off the end of the specified type or being in
2765/// alignment padding. The user type specified is known to be at most 128 bits
2766/// in size, and have passed through X86_64ABIInfo::classify with a successful
2767/// classification that put one of the two halves in the INTEGER class.
2768///
2769/// It is conservatively correct to return false.
2770static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2771 unsigned EndBit, ASTContext &Context) {
2772 // If the bytes being queried are off the end of the type, there is no user
2773 // data hiding here. This handles analysis of builtins, vectors and other
2774 // types that don't contain interesting padding.
2775 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2776 if (TySize <= StartBit)
2777 return true;
2778
Chris Lattner98076a22010-07-29 07:43:55 +00002779 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2780 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2781 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2782
2783 // Check each element to see if the element overlaps with the queried range.
2784 for (unsigned i = 0; i != NumElts; ++i) {
2785 // If the element is after the span we care about, then we're done..
2786 unsigned EltOffset = i*EltSize;
2787 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002788
Chris Lattner98076a22010-07-29 07:43:55 +00002789 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2790 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2791 EndBit-EltOffset, Context))
2792 return false;
2793 }
2794 // If it overlaps no elements, then it is safe to process as padding.
2795 return true;
2796 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002797
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002798 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2799 const RecordDecl *RD = RT->getDecl();
2800 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002801
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002802 // If this is a C++ record, check the bases first.
2803 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002804 for (const auto &I : CXXRD->bases()) {
2805 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002806 "Unexpected base class!");
2807 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002808 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002809
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002810 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002811 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002812 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002813
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002814 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002815 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002816 EndBit-BaseOffset, Context))
2817 return false;
2818 }
2819 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002820
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002821 // Verify that no field has data that overlaps the region of interest. Yes
2822 // this could be sped up a lot by being smarter about queried fields,
2823 // however we're only looking at structs up to 16 bytes, so we don't care
2824 // much.
2825 unsigned idx = 0;
2826 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2827 i != e; ++i, ++idx) {
2828 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002829
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002830 // If we found a field after the region we care about, then we're done.
2831 if (FieldOffset >= EndBit) break;
2832
2833 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2834 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2835 Context))
2836 return false;
2837 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002838
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002839 // If nothing in this record overlapped the area of interest, then we're
2840 // clean.
2841 return true;
2842 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002843
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002844 return false;
2845}
2846
Chris Lattnere556a712010-07-29 18:39:32 +00002847/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2848/// float member at the specified offset. For example, {int,{float}} has a
2849/// float at offset 4. It is conservatively correct for this routine to return
2850/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002851static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002852 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002853 // Base case if we find a float.
2854 if (IROffset == 0 && IRType->isFloatTy())
2855 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002856
Chris Lattnere556a712010-07-29 18:39:32 +00002857 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002858 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002859 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2860 unsigned Elt = SL->getElementContainingOffset(IROffset);
2861 IROffset -= SL->getElementOffset(Elt);
2862 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2863 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002864
Chris Lattnere556a712010-07-29 18:39:32 +00002865 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002866 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2867 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002868 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2869 IROffset -= IROffset/EltSize*EltSize;
2870 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2871 }
2872
2873 return false;
2874}
2875
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002876
2877/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2878/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002879llvm::Type *X86_64ABIInfo::
2880GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002881 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002882 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002883 // pass as float if the last 4 bytes is just padding. This happens for
2884 // structs that contain 3 floats.
2885 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2886 SourceOffset*8+64, getContext()))
2887 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002888
Chris Lattnere556a712010-07-29 18:39:32 +00002889 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2890 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2891 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002892 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2893 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002894 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002895
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002896 return llvm::Type::getDoubleTy(getVMContext());
2897}
2898
2899
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002900/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2901/// an 8-byte GPR. This means that we either have a scalar or we are talking
2902/// about the high or low part of an up-to-16-byte struct. This routine picks
2903/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002904/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2905/// etc).
2906///
2907/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2908/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2909/// the 8-byte value references. PrefType may be null.
2910///
Alp Toker9907f082014-07-09 14:06:35 +00002911/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002912/// an offset into this that we're processing (which is always either 0 or 8).
2913///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002914llvm::Type *X86_64ABIInfo::
2915GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002916 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002917 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2918 // returning an 8-byte unit starting with it. See if we can safely use it.
2919 if (IROffset == 0) {
2920 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002921 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2922 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002923 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002924
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002925 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2926 // goodness in the source type is just tail padding. This is allowed to
2927 // kick in for struct {double,int} on the int, but not on
2928 // struct{double,int,int} because we wouldn't return the second int. We
2929 // have to do this analysis on the source type because we can't depend on
2930 // unions being lowered a specific way etc.
2931 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002932 IRType->isIntegerTy(32) ||
2933 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2934 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2935 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002936
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002937 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2938 SourceOffset*8+64, getContext()))
2939 return IRType;
2940 }
2941 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002942
Chris Lattner2192fe52011-07-18 04:24:23 +00002943 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002944 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002945 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002946 if (IROffset < SL->getSizeInBytes()) {
2947 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2948 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002949
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002950 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2951 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002952 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002953 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002954
Chris Lattner2192fe52011-07-18 04:24:23 +00002955 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002956 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002957 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002958 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002959 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2960 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002961 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002962
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002963 // Okay, we don't have any better idea of what to pass, so we pass this in an
2964 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002965 unsigned TySizeInBytes =
2966 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002967
Chris Lattner3f763422010-07-29 17:34:39 +00002968 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002969
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002970 // It is always safe to classify this as an integer type up to i64 that
2971 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002972 return llvm::IntegerType::get(getVMContext(),
2973 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002974}
2975
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002976
2977/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2978/// be used as elements of a two register pair to pass or return, return a
2979/// first class aggregate to represent them. For example, if the low part of
2980/// a by-value argument should be passed as i32* and the high part as float,
2981/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002982static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002983GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002984 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002985 // In order to correctly satisfy the ABI, we need to the high part to start
2986 // at offset 8. If the high and low parts we inferred are both 4-byte types
2987 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2988 // the second element at offset 8. Check for this:
2989 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2990 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002991 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002992 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002993
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002994 // To handle this, we have to increase the size of the low part so that the
2995 // second element will start at an 8 byte offset. We can't increase the size
2996 // of the second element because it might make us access off the end of the
2997 // struct.
2998 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002999 // There are usually two sorts of types the ABI generation code can produce
3000 // for the low part of a pair that aren't 8 bytes in size: float or
3001 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3002 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003003 // Promote these to a larger type.
3004 if (Lo->isFloatTy())
3005 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3006 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003007 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3008 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003009 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3010 }
3011 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003012
Reid Kleckneree7cf842014-12-01 22:02:27 +00003013 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003014
3015
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003016 // Verify that the second element is at an 8-byte offset.
3017 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3018 "Invalid x86-64 argument pair!");
3019 return Result;
3020}
3021
Chris Lattner31faff52010-07-28 23:06:14 +00003022ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003023classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003024 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3025 // classification algorithm.
3026 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003027 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003028
3029 // Check some invariants.
3030 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003031 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3032
Craig Topper8a13c412014-05-21 05:09:00 +00003033 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003034 switch (Lo) {
3035 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003036 if (Hi == NoClass)
3037 return ABIArgInfo::getIgnore();
3038 // If the low part is just padding, it takes no register, leave ResType
3039 // null.
3040 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3041 "Unknown missing lo part");
3042 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003043
3044 case SSEUp:
3045 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003046 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003047
3048 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3049 // hidden argument.
3050 case Memory:
3051 return getIndirectReturnResult(RetTy);
3052
3053 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3054 // available register of the sequence %rax, %rdx is used.
3055 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003056 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003057
Chris Lattner1f3a0632010-07-29 21:42:50 +00003058 // If we have a sign or zero extended integer, make sure to return Extend
3059 // so that the parameter gets the right LLVM IR attributes.
3060 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3061 // Treat an enum type as its underlying type.
3062 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3063 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003064
Chris Lattner1f3a0632010-07-29 21:42:50 +00003065 if (RetTy->isIntegralOrEnumerationType() &&
3066 RetTy->isPromotableIntegerType())
3067 return ABIArgInfo::getExtend();
3068 }
Chris Lattner31faff52010-07-28 23:06:14 +00003069 break;
3070
3071 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3072 // available SSE register of the sequence %xmm0, %xmm1 is used.
3073 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003074 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003075 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003076
3077 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3078 // returned on the X87 stack in %st0 as 80-bit x87 number.
3079 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003080 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003081 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003082
3083 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3084 // part of the value is returned in %st0 and the imaginary part in
3085 // %st1.
3086 case ComplexX87:
3087 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003088 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003089 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003090 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003091 break;
3092 }
3093
Craig Topper8a13c412014-05-21 05:09:00 +00003094 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003095 switch (Hi) {
3096 // Memory was handled previously and X87 should
3097 // never occur as a hi class.
3098 case Memory:
3099 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003100 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003101
3102 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003103 case NoClass:
3104 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003105
Chris Lattner52b3c132010-09-01 00:20:33 +00003106 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003107 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003108 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3109 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003110 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003111 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003112 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003113 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3114 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003115 break;
3116
3117 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003118 // is passed in the next available eightbyte chunk if the last used
3119 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003120 //
Chris Lattner57540c52011-04-15 05:22:18 +00003121 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003122 case SSEUp:
3123 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003124 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003125 break;
3126
3127 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3128 // returned together with the previous X87 value in %st0.
3129 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003130 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003131 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003132 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003133 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003134 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003135 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003136 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3137 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003138 }
Chris Lattner31faff52010-07-28 23:06:14 +00003139 break;
3140 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003141
Chris Lattner52b3c132010-09-01 00:20:33 +00003142 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003143 // known to pass in the high eightbyte of the result. We do this by forming a
3144 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003145 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003146 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003147
Chris Lattner1f3a0632010-07-29 21:42:50 +00003148 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003149}
3150
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003151ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003152 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3153 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003154 const
3155{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003156 Ty = useFirstFieldIfTransparentUnion(Ty);
3157
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003158 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003159 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003160
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003161 // Check some invariants.
3162 // FIXME: Enforce these by construction.
3163 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003164 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3165
3166 neededInt = 0;
3167 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003168 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003169 switch (Lo) {
3170 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003171 if (Hi == NoClass)
3172 return ABIArgInfo::getIgnore();
3173 // If the low part is just padding, it takes no register, leave ResType
3174 // null.
3175 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3176 "Unknown missing lo part");
3177 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003178
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003179 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3180 // on the stack.
3181 case Memory:
3182
3183 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3184 // COMPLEX_X87, it is passed in memory.
3185 case X87:
3186 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003187 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003188 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003189 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003190
3191 case SSEUp:
3192 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003193 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003194
3195 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3196 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3197 // and %r9 is used.
3198 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003199 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003200
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003201 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003202 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003203
3204 // If we have a sign or zero extended integer, make sure to return Extend
3205 // so that the parameter gets the right LLVM IR attributes.
3206 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3207 // Treat an enum type as its underlying type.
3208 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3209 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003210
Chris Lattner1f3a0632010-07-29 21:42:50 +00003211 if (Ty->isIntegralOrEnumerationType() &&
3212 Ty->isPromotableIntegerType())
3213 return ABIArgInfo::getExtend();
3214 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003215
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003216 break;
3217
3218 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3219 // available SSE register is used, the registers are taken in the
3220 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003221 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003222 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003223 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003224 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003225 break;
3226 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003227 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003228
Craig Topper8a13c412014-05-21 05:09:00 +00003229 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003230 switch (Hi) {
3231 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003232 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003233 // which is passed in memory.
3234 case Memory:
3235 case X87:
3236 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003237 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003238
3239 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003240
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003241 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003242 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003243 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003244 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003245
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003246 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3247 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003248 break;
3249
3250 // X87Up generally doesn't occur here (long double is passed in
3251 // memory), except in situations involving unions.
3252 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003253 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003254 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003255
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003256 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3257 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003258
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003259 ++neededSSE;
3260 break;
3261
3262 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3263 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003264 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003265 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003266 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003267 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003268 break;
3269 }
3270
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003271 // If a high part was specified, merge it together with the low part. It is
3272 // known to pass in the high eightbyte of the result. We do this by forming a
3273 // first class struct aggregate with the high and low part: {low, high}
3274 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003275 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003276
Chris Lattner1f3a0632010-07-29 21:42:50 +00003277 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003278}
3279
Chris Lattner22326a12010-07-29 02:31:05 +00003280void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003281
Reid Kleckner40ca9132014-05-13 22:05:45 +00003282 if (!getCXXABI().classifyReturnType(FI))
3283 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003284
3285 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003286 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003287
3288 // If the return value is indirect, then the hidden argument is consuming one
3289 // integer register.
3290 if (FI.getReturnInfo().isIndirect())
3291 --freeIntRegs;
3292
Peter Collingbournef7706832014-12-12 23:41:25 +00003293 // The chain argument effectively gives us another free register.
3294 if (FI.isChainCall())
3295 ++freeIntRegs;
3296
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003297 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003298 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3299 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003300 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003301 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003302 it != ie; ++it, ++ArgNo) {
3303 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003304
Bill Wendling9987c0e2010-10-18 23:51:38 +00003305 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003306 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003307 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003308
3309 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3310 // eightbyte of an argument, the whole argument is passed on the
3311 // stack. If registers have already been assigned for some
3312 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003313 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003314 freeIntRegs -= neededInt;
3315 freeSSERegs -= neededSSE;
3316 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003317 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003318 }
3319 }
3320}
3321
John McCall7f416cc2015-09-08 08:05:57 +00003322static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3323 Address VAListAddr, QualType Ty) {
3324 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3325 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003326 llvm::Value *overflow_arg_area =
3327 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3328
3329 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3330 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003331 // It isn't stated explicitly in the standard, but in practice we use
3332 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003333 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3334 if (Align > CharUnits::fromQuantity(8)) {
3335 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3336 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003337 }
3338
3339 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003340 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003341 llvm::Value *Res =
3342 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003343 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003344
3345 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3346 // l->overflow_arg_area + sizeof(type).
3347 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3348 // an 8 byte boundary.
3349
3350 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003351 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003352 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003353 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3354 "overflow_arg_area.next");
3355 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3356
3357 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003358 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003359}
3360
John McCall7f416cc2015-09-08 08:05:57 +00003361Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3362 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003363 // Assume that va_list type is correct; should be pointer to LLVM type:
3364 // struct {
3365 // i32 gp_offset;
3366 // i32 fp_offset;
3367 // i8* overflow_arg_area;
3368 // i8* reg_save_area;
3369 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003370 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003371
John McCall7f416cc2015-09-08 08:05:57 +00003372 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003373 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003374 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003375
3376 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3377 // in the registers. If not go to step 7.
3378 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003379 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003380
3381 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3382 // general purpose registers needed to pass type and num_fp to hold
3383 // the number of floating point registers needed.
3384
3385 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3386 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3387 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3388 //
3389 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3390 // register save space).
3391
Craig Topper8a13c412014-05-21 05:09:00 +00003392 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003393 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3394 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003395 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003396 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003397 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3398 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003399 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003400 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3401 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003402 }
3403
3404 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003405 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003406 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3407 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003408 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3409 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003410 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3411 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003412 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3413 }
3414
3415 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3416 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3417 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3418 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3419
3420 // Emit code to load the value if it was passed in registers.
3421
3422 CGF.EmitBlock(InRegBlock);
3423
3424 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3425 // an offset of l->gp_offset and/or l->fp_offset. This may require
3426 // copying to a temporary location in case the parameter is passed
3427 // in different register classes or requires an alignment greater
3428 // than 8 for general purpose registers and 16 for XMM registers.
3429 //
3430 // FIXME: This really results in shameful code when we end up needing to
3431 // collect arguments from different places; often what should result in a
3432 // simple assembling of a structure from scattered addresses has many more
3433 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003434 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003435 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3436 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3437 "reg_save_area");
3438
3439 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003440 if (neededInt && neededSSE) {
3441 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003442 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003443 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003444 Address Tmp = CGF.CreateMemTemp(Ty);
3445 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003446 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003447 llvm::Type *TyLo = ST->getElementType(0);
3448 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003449 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003450 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003451 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3452 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003453 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3454 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003455 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3456 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003457
John McCall7f416cc2015-09-08 08:05:57 +00003458 // Copy the first element.
3459 llvm::Value *V =
3460 CGF.Builder.CreateDefaultAlignedLoad(
3461 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3462 CGF.Builder.CreateStore(V,
3463 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3464
3465 // Copy the second element.
3466 V = CGF.Builder.CreateDefaultAlignedLoad(
3467 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3468 CharUnits Offset = CharUnits::fromQuantity(
3469 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3470 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3471
3472 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003473 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003474 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3475 CharUnits::fromQuantity(8));
3476 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003477
3478 // Copy to a temporary if necessary to ensure the appropriate alignment.
3479 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003480 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003481 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003482 CharUnits TyAlign = SizeAlign.second;
3483
3484 // Copy into a temporary if the type is more aligned than the
3485 // register save area.
3486 if (TyAlign.getQuantity() > 8) {
3487 Address Tmp = CGF.CreateMemTemp(Ty);
3488 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003489 RegAddr = Tmp;
3490 }
John McCall7f416cc2015-09-08 08:05:57 +00003491
Chris Lattner0cf24192010-06-28 20:05:43 +00003492 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003493 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3494 CharUnits::fromQuantity(16));
3495 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003496 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003497 assert(neededSSE == 2 && "Invalid number of needed registers!");
3498 // SSE registers are spaced 16 bytes apart in the register save
3499 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003500 // The ABI isn't explicit about this, but it seems reasonable
3501 // to assume that the slots are 16-byte aligned, since the stack is
3502 // naturally 16-byte aligned and the prologue is expected to store
3503 // all the SSE registers to the RSA.
3504 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3505 CharUnits::fromQuantity(16));
3506 Address RegAddrHi =
3507 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3508 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003509 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003510 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003511 llvm::Value *V;
3512 Address Tmp = CGF.CreateMemTemp(Ty);
3513 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3514 V = CGF.Builder.CreateLoad(
3515 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3516 CGF.Builder.CreateStore(V,
3517 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3518 V = CGF.Builder.CreateLoad(
3519 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3520 CGF.Builder.CreateStore(V,
3521 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3522
3523 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003524 }
3525
3526 // AMD64-ABI 3.5.7p5: Step 5. Set:
3527 // l->gp_offset = l->gp_offset + num_gp * 8
3528 // l->fp_offset = l->fp_offset + num_fp * 16.
3529 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003530 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003531 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3532 gp_offset_p);
3533 }
3534 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003535 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003536 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3537 fp_offset_p);
3538 }
3539 CGF.EmitBranch(ContBlock);
3540
3541 // Emit code to load the value if it was passed in memory.
3542
3543 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003544 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003545
3546 // Return the appropriate result.
3547
3548 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003549 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3550 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003551 return ResAddr;
3552}
3553
Charles Davisc7d5c942015-09-17 20:55:33 +00003554Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3555 QualType Ty) const {
3556 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3557 CGF.getContext().getTypeInfoInChars(Ty),
3558 CharUnits::fromQuantity(8),
3559 /*allowHigherAlign*/ false);
3560}
3561
Reid Kleckner80944df2014-10-31 22:00:51 +00003562ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3563 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003564
3565 if (Ty->isVoidType())
3566 return ABIArgInfo::getIgnore();
3567
3568 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3569 Ty = EnumTy->getDecl()->getIntegerType();
3570
Reid Kleckner80944df2014-10-31 22:00:51 +00003571 TypeInfo Info = getContext().getTypeInfo(Ty);
3572 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003573 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003574
Reid Kleckner9005f412014-05-02 00:51:20 +00003575 const RecordType *RT = Ty->getAs<RecordType>();
3576 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003577 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003578 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003579 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003580 }
3581
3582 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003583 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003584
Reid Kleckner9005f412014-05-02 00:51:20 +00003585 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003586
Reid Kleckner80944df2014-10-31 22:00:51 +00003587 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3588 // other targets.
3589 const Type *Base = nullptr;
3590 uint64_t NumElts = 0;
3591 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3592 if (FreeSSERegs >= NumElts) {
3593 FreeSSERegs -= NumElts;
3594 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3595 return ABIArgInfo::getDirect();
3596 return ABIArgInfo::getExpand();
3597 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003598 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003599 }
3600
3601
Reid Klecknerec87fec2014-05-02 01:17:12 +00003602 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003603 // If the member pointer is represented by an LLVM int or ptr, pass it
3604 // directly.
3605 llvm::Type *LLTy = CGT.ConvertType(Ty);
3606 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3607 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003608 }
3609
Michael Kuperstein4f818702015-02-24 09:35:58 +00003610 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003611 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3612 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003613 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003614 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003615
Reid Kleckner9005f412014-05-02 00:51:20 +00003616 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003617 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003618 }
3619
Julien Lerouge10dcff82014-08-27 00:36:55 +00003620 // Bool type is always extended to the ABI, other builtin types are not
3621 // extended.
3622 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3623 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003624 return ABIArgInfo::getExtend();
3625
Reid Kleckner11a17192015-10-28 22:29:52 +00003626 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3627 // passes them indirectly through memory.
3628 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3629 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3630 if (LDF == &llvm::APFloat::x87DoubleExtended)
3631 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3632 }
3633
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003634 return ABIArgInfo::getDirect();
3635}
3636
3637void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003638 bool IsVectorCall =
3639 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003640
Reid Kleckner80944df2014-10-31 22:00:51 +00003641 // We can use up to 4 SSE return registers with vectorcall.
3642 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3643 if (!getCXXABI().classifyReturnType(FI))
3644 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3645
3646 // We can use up to 6 SSE register parameters with vectorcall.
3647 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003648 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003649 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003650}
3651
John McCall7f416cc2015-09-08 08:05:57 +00003652Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3653 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00003654
3655 bool IsIndirect = false;
3656
3657 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3658 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3659 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3660 uint64_t Width = getContext().getTypeSize(Ty);
3661 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3662 }
3663
3664 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00003665 CGF.getContext().getTypeInfoInChars(Ty),
3666 CharUnits::fromQuantity(8),
3667 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003668}
Chris Lattner0cf24192010-06-28 20:05:43 +00003669
John McCallea8d8bb2010-03-11 00:10:12 +00003670// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003671namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003672/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3673class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003674bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003675public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003676 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3677 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003678
John McCall7f416cc2015-09-08 08:05:57 +00003679 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3680 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003681};
3682
3683class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3684public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003685 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3686 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003687
Craig Topper4f12f102014-03-12 06:41:41 +00003688 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003689 // This is recovered from gcc output.
3690 return 1; // r1 is the dedicated stack pointer
3691 }
3692
3693 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003694 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003695};
3696
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003697}
John McCallea8d8bb2010-03-11 00:10:12 +00003698
James Y Knight29b5f082016-02-24 02:59:33 +00003699// TODO: this implementation is now likely redundant with
3700// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003701Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3702 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003703 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003704 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3705 // TODO: Implement this. For now ignore.
3706 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003707 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003708 }
3709
John McCall7f416cc2015-09-08 08:05:57 +00003710 // struct __va_list_tag {
3711 // unsigned char gpr;
3712 // unsigned char fpr;
3713 // unsigned short reserved;
3714 // void *overflow_arg_area;
3715 // void *reg_save_area;
3716 // };
3717
Roman Divacky8a12d842014-11-03 18:32:54 +00003718 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003719 bool isInt =
3720 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003721 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003722
3723 // All aggregates are passed indirectly? That doesn't seem consistent
3724 // with the argument-lowering code.
3725 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003726
3727 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003728
3729 // The calling convention either uses 1-2 GPRs or 1 FPR.
3730 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003731 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003732 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3733 } else {
3734 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003735 }
John McCall7f416cc2015-09-08 08:05:57 +00003736
3737 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3738
3739 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003740 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003741 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3742 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3743 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003744
Eric Christopher7565e0d2015-05-29 23:09:49 +00003745 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003746 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003747
3748 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3749 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3750 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3751
3752 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3753
John McCall7f416cc2015-09-08 08:05:57 +00003754 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3755 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003756
John McCall7f416cc2015-09-08 08:05:57 +00003757 // Case 1: consume registers.
3758 Address RegAddr = Address::invalid();
3759 {
3760 CGF.EmitBlock(UsingRegs);
3761
3762 Address RegSaveAreaPtr =
3763 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3764 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3765 CharUnits::fromQuantity(8));
3766 assert(RegAddr.getElementType() == CGF.Int8Ty);
3767
3768 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003769 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003770 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3771 CharUnits::fromQuantity(32));
3772 }
3773
3774 // Get the address of the saved value by scaling the number of
3775 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003776 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003777 llvm::Value *RegOffset =
3778 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3779 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3780 RegAddr.getPointer(), RegOffset),
3781 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3782 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3783
3784 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003785 NumRegs =
3786 Builder.CreateAdd(NumRegs,
3787 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003788 Builder.CreateStore(NumRegs, NumRegsAddr);
3789
3790 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003791 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003792
John McCall7f416cc2015-09-08 08:05:57 +00003793 // Case 2: consume space in the overflow area.
3794 Address MemAddr = Address::invalid();
3795 {
3796 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003797
Roman Divacky039b9702016-02-20 08:31:24 +00003798 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3799
John McCall7f416cc2015-09-08 08:05:57 +00003800 // Everything in the overflow area is rounded up to a size of at least 4.
3801 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3802
3803 CharUnits Size;
3804 if (!isIndirect) {
3805 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003806 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003807 } else {
3808 Size = CGF.getPointerSize();
3809 }
3810
3811 Address OverflowAreaAddr =
3812 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003813 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003814 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003815 // Round up address of argument to alignment
3816 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3817 if (Align > OverflowAreaAlign) {
3818 llvm::Value *Ptr = OverflowArea.getPointer();
3819 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3820 Align);
3821 }
3822
John McCall7f416cc2015-09-08 08:05:57 +00003823 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3824
3825 // Increase the overflow area.
3826 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3827 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3828 CGF.EmitBranch(Cont);
3829 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003830
3831 CGF.EmitBlock(Cont);
3832
John McCall7f416cc2015-09-08 08:05:57 +00003833 // Merge the cases with a phi.
3834 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3835 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003836
John McCall7f416cc2015-09-08 08:05:57 +00003837 // Load the pointer if the argument was passed indirectly.
3838 if (isIndirect) {
3839 Result = Address(Builder.CreateLoad(Result, "aggr"),
3840 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003841 }
3842
3843 return Result;
3844}
3845
John McCallea8d8bb2010-03-11 00:10:12 +00003846bool
3847PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3848 llvm::Value *Address) const {
3849 // This is calculated from the LLVM and GCC tables and verified
3850 // against gcc output. AFAIK all ABIs use the same encoding.
3851
3852 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003853
Chris Lattnerece04092012-02-07 00:39:47 +00003854 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003855 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3856 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3857 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3858
3859 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003860 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003861
3862 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003863 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003864
3865 // 64-76 are various 4-byte special-purpose registers:
3866 // 64: mq
3867 // 65: lr
3868 // 66: ctr
3869 // 67: ap
3870 // 68-75 cr0-7
3871 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003872 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003873
3874 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003875 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003876
3877 // 109: vrsave
3878 // 110: vscr
3879 // 111: spe_acc
3880 // 112: spefscr
3881 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003882 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003883
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003884 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003885}
3886
Roman Divackyd966e722012-05-09 18:22:46 +00003887// PowerPC-64
3888
3889namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003890/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00003891class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003892public:
3893 enum ABIKind {
3894 ELFv1 = 0,
3895 ELFv2
3896 };
3897
3898private:
3899 static const unsigned GPRBits = 64;
3900 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003901 bool HasQPX;
3902
3903 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3904 // will be passed in a QPX register.
3905 bool IsQPXVectorTy(const Type *Ty) const {
3906 if (!HasQPX)
3907 return false;
3908
3909 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3910 unsigned NumElements = VT->getNumElements();
3911 if (NumElements == 1)
3912 return false;
3913
3914 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3915 if (getContext().getTypeSize(Ty) <= 256)
3916 return true;
3917 } else if (VT->getElementType()->
3918 isSpecificBuiltinType(BuiltinType::Float)) {
3919 if (getContext().getTypeSize(Ty) <= 128)
3920 return true;
3921 }
3922 }
3923
3924 return false;
3925 }
3926
3927 bool IsQPXVectorTy(QualType Ty) const {
3928 return IsQPXVectorTy(Ty.getTypePtr());
3929 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003930
3931public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003932 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
James Y Knight29b5f082016-02-24 02:59:33 +00003933 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003934
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003935 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003936 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003937
3938 ABIArgInfo classifyReturnType(QualType RetTy) const;
3939 ABIArgInfo classifyArgumentType(QualType Ty) const;
3940
Reid Klecknere9f6a712014-10-31 17:10:41 +00003941 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3942 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3943 uint64_t Members) const override;
3944
Bill Schmidt84d37792012-10-12 19:26:17 +00003945 // TODO: We can add more logic to computeInfo to improve performance.
3946 // Example: For aggregate arguments that fit in a register, we could
3947 // use getDirectInReg (as is done below for structs containing a single
3948 // floating-point value) to avoid pushing them to memory on function
3949 // entry. This would require changing the logic in PPCISelLowering
3950 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003951 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003952 if (!getCXXABI().classifyReturnType(FI))
3953 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003954 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003955 // We rely on the default argument classification for the most part.
3956 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003957 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003958 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003959 if (T) {
3960 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003961 if (IsQPXVectorTy(T) ||
3962 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003963 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003964 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003965 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003966 continue;
3967 }
3968 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003969 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003970 }
3971 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003972
John McCall7f416cc2015-09-08 08:05:57 +00003973 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3974 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003975};
3976
3977class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003978
Bill Schmidt25cb3492012-10-03 19:18:57 +00003979public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003980 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003981 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003982 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003983
Craig Topper4f12f102014-03-12 06:41:41 +00003984 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003985 // This is recovered from gcc output.
3986 return 1; // r1 is the dedicated stack pointer
3987 }
3988
3989 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003990 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003991};
3992
Roman Divackyd966e722012-05-09 18:22:46 +00003993class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3994public:
3995 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3996
Craig Topper4f12f102014-03-12 06:41:41 +00003997 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003998 // This is recovered from gcc output.
3999 return 1; // r1 is the dedicated stack pointer
4000 }
4001
4002 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004003 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004004};
4005
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004006}
Roman Divackyd966e722012-05-09 18:22:46 +00004007
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004008// Return true if the ABI requires Ty to be passed sign- or zero-
4009// extended to 64 bits.
4010bool
4011PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4012 // Treat an enum type as its underlying type.
4013 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4014 Ty = EnumTy->getDecl()->getIntegerType();
4015
4016 // Promotable integer types are required to be promoted by the ABI.
4017 if (Ty->isPromotableIntegerType())
4018 return true;
4019
4020 // In addition to the usual promotable integer types, we also need to
4021 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4022 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4023 switch (BT->getKind()) {
4024 case BuiltinType::Int:
4025 case BuiltinType::UInt:
4026 return true;
4027 default:
4028 break;
4029 }
4030
4031 return false;
4032}
4033
John McCall7f416cc2015-09-08 08:05:57 +00004034/// isAlignedParamType - Determine whether a type requires 16-byte or
4035/// higher alignment in the parameter area. Always returns at least 8.
4036CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004037 // Complex types are passed just like their elements.
4038 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4039 Ty = CTy->getElementType();
4040
4041 // Only vector types of size 16 bytes need alignment (larger types are
4042 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004043 if (IsQPXVectorTy(Ty)) {
4044 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004045 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004046
John McCall7f416cc2015-09-08 08:05:57 +00004047 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004048 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004049 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004050 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004051
4052 // For single-element float/vector structs, we consider the whole type
4053 // to have the same alignment requirements as its single element.
4054 const Type *AlignAsType = nullptr;
4055 const Type *EltType = isSingleElementStruct(Ty, getContext());
4056 if (EltType) {
4057 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004058 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004059 getContext().getTypeSize(EltType) == 128) ||
4060 (BT && BT->isFloatingPoint()))
4061 AlignAsType = EltType;
4062 }
4063
Ulrich Weigandb7122372014-07-21 00:48:09 +00004064 // Likewise for ELFv2 homogeneous aggregates.
4065 const Type *Base = nullptr;
4066 uint64_t Members = 0;
4067 if (!AlignAsType && Kind == ELFv2 &&
4068 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4069 AlignAsType = Base;
4070
Ulrich Weigand581badc2014-07-10 17:20:07 +00004071 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004072 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4073 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004074 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004075
John McCall7f416cc2015-09-08 08:05:57 +00004076 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004077 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004078 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004079 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004080
4081 // Otherwise, we only need alignment for any aggregate type that
4082 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004083 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4084 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004085 return CharUnits::fromQuantity(32);
4086 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004087 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004088
John McCall7f416cc2015-09-08 08:05:57 +00004089 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004090}
4091
Ulrich Weigandb7122372014-07-21 00:48:09 +00004092/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4093/// aggregate. Base is set to the base element type, and Members is set
4094/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004095bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4096 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004097 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4098 uint64_t NElements = AT->getSize().getZExtValue();
4099 if (NElements == 0)
4100 return false;
4101 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4102 return false;
4103 Members *= NElements;
4104 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4105 const RecordDecl *RD = RT->getDecl();
4106 if (RD->hasFlexibleArrayMember())
4107 return false;
4108
4109 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004110
4111 // If this is a C++ record, check the bases first.
4112 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4113 for (const auto &I : CXXRD->bases()) {
4114 // Ignore empty records.
4115 if (isEmptyRecord(getContext(), I.getType(), true))
4116 continue;
4117
4118 uint64_t FldMembers;
4119 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4120 return false;
4121
4122 Members += FldMembers;
4123 }
4124 }
4125
Ulrich Weigandb7122372014-07-21 00:48:09 +00004126 for (const auto *FD : RD->fields()) {
4127 // Ignore (non-zero arrays of) empty records.
4128 QualType FT = FD->getType();
4129 while (const ConstantArrayType *AT =
4130 getContext().getAsConstantArrayType(FT)) {
4131 if (AT->getSize().getZExtValue() == 0)
4132 return false;
4133 FT = AT->getElementType();
4134 }
4135 if (isEmptyRecord(getContext(), FT, true))
4136 continue;
4137
4138 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4139 if (getContext().getLangOpts().CPlusPlus &&
4140 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4141 continue;
4142
4143 uint64_t FldMembers;
4144 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4145 return false;
4146
4147 Members = (RD->isUnion() ?
4148 std::max(Members, FldMembers) : Members + FldMembers);
4149 }
4150
4151 if (!Base)
4152 return false;
4153
4154 // Ensure there is no padding.
4155 if (getContext().getTypeSize(Base) * Members !=
4156 getContext().getTypeSize(Ty))
4157 return false;
4158 } else {
4159 Members = 1;
4160 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4161 Members = 2;
4162 Ty = CT->getElementType();
4163 }
4164
Reid Klecknere9f6a712014-10-31 17:10:41 +00004165 // Most ABIs only support float, double, and some vector type widths.
4166 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004167 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004168
4169 // The base type must be the same for all members. Types that
4170 // agree in both total size and mode (float vs. vector) are
4171 // treated as being equivalent here.
4172 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004173 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004174 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004175 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4176 // so make sure to widen it explicitly.
4177 if (const VectorType *VT = Base->getAs<VectorType>()) {
4178 QualType EltTy = VT->getElementType();
4179 unsigned NumElements =
4180 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4181 Base = getContext()
4182 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4183 .getTypePtr();
4184 }
4185 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004186
4187 if (Base->isVectorType() != TyPtr->isVectorType() ||
4188 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4189 return false;
4190 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004191 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4192}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004193
Reid Klecknere9f6a712014-10-31 17:10:41 +00004194bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4195 // Homogeneous aggregates for ELFv2 must have base types of float,
4196 // double, long double, or 128-bit vectors.
4197 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4198 if (BT->getKind() == BuiltinType::Float ||
4199 BT->getKind() == BuiltinType::Double ||
4200 BT->getKind() == BuiltinType::LongDouble)
4201 return true;
4202 }
4203 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004204 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004205 return true;
4206 }
4207 return false;
4208}
4209
4210bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4211 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004212 // Vector types require one register, floating point types require one
4213 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004214 uint32_t NumRegs =
4215 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004216
4217 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004218 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004219}
4220
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004221ABIArgInfo
4222PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004223 Ty = useFirstFieldIfTransparentUnion(Ty);
4224
Bill Schmidt90b22c92012-11-27 02:46:43 +00004225 if (Ty->isAnyComplexType())
4226 return ABIArgInfo::getDirect();
4227
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004228 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4229 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004230 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004231 uint64_t Size = getContext().getTypeSize(Ty);
4232 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004233 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004234 else if (Size < 128) {
4235 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4236 return ABIArgInfo::getDirect(CoerceTy);
4237 }
4238 }
4239
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004240 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004241 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004242 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004243
John McCall7f416cc2015-09-08 08:05:57 +00004244 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4245 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004246
4247 // ELFv2 homogeneous aggregates are passed as array types.
4248 const Type *Base = nullptr;
4249 uint64_t Members = 0;
4250 if (Kind == ELFv2 &&
4251 isHomogeneousAggregate(Ty, Base, Members)) {
4252 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4253 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4254 return ABIArgInfo::getDirect(CoerceTy);
4255 }
4256
Ulrich Weigand601957f2014-07-21 00:56:36 +00004257 // If an aggregate may end up fully in registers, we do not
4258 // use the ByVal method, but pass the aggregate as array.
4259 // This is usually beneficial since we avoid forcing the
4260 // back-end to store the argument to memory.
4261 uint64_t Bits = getContext().getTypeSize(Ty);
4262 if (Bits > 0 && Bits <= 8 * GPRBits) {
4263 llvm::Type *CoerceTy;
4264
4265 // Types up to 8 bytes are passed as integer type (which will be
4266 // properly aligned in the argument save area doubleword).
4267 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004268 CoerceTy =
4269 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004270 // Larger types are passed as arrays, with the base type selected
4271 // according to the required alignment in the save area.
4272 else {
4273 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004274 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004275 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4276 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4277 }
4278
4279 return ABIArgInfo::getDirect(CoerceTy);
4280 }
4281
Ulrich Weigandb7122372014-07-21 00:48:09 +00004282 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004283 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4284 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004285 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004286 }
4287
4288 return (isPromotableTypeForABI(Ty) ?
4289 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4290}
4291
4292ABIArgInfo
4293PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4294 if (RetTy->isVoidType())
4295 return ABIArgInfo::getIgnore();
4296
Bill Schmidta3d121c2012-12-17 04:20:17 +00004297 if (RetTy->isAnyComplexType())
4298 return ABIArgInfo::getDirect();
4299
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004300 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4301 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004302 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004303 uint64_t Size = getContext().getTypeSize(RetTy);
4304 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004305 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004306 else if (Size < 128) {
4307 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4308 return ABIArgInfo::getDirect(CoerceTy);
4309 }
4310 }
4311
Ulrich Weigandb7122372014-07-21 00:48:09 +00004312 if (isAggregateTypeForABI(RetTy)) {
4313 // ELFv2 homogeneous aggregates are returned as array types.
4314 const Type *Base = nullptr;
4315 uint64_t Members = 0;
4316 if (Kind == ELFv2 &&
4317 isHomogeneousAggregate(RetTy, Base, Members)) {
4318 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4319 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4320 return ABIArgInfo::getDirect(CoerceTy);
4321 }
4322
4323 // ELFv2 small aggregates are returned in up to two registers.
4324 uint64_t Bits = getContext().getTypeSize(RetTy);
4325 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4326 if (Bits == 0)
4327 return ABIArgInfo::getIgnore();
4328
4329 llvm::Type *CoerceTy;
4330 if (Bits > GPRBits) {
4331 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004332 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004333 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004334 CoerceTy =
4335 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004336 return ABIArgInfo::getDirect(CoerceTy);
4337 }
4338
4339 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004340 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004341 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004342
4343 return (isPromotableTypeForABI(RetTy) ?
4344 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4345}
4346
Bill Schmidt25cb3492012-10-03 19:18:57 +00004347// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004348Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4349 QualType Ty) const {
4350 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4351 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004352
John McCall7f416cc2015-09-08 08:05:57 +00004353 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004354
Bill Schmidt924c4782013-01-14 17:45:36 +00004355 // If we have a complex type and the base type is smaller than 8 bytes,
4356 // the ABI calls for the real and imaginary parts to be right-adjusted
4357 // in separate doublewords. However, Clang expects us to produce a
4358 // pointer to a structure with the two parts packed tightly. So generate
4359 // loads of the real and imaginary parts relative to the va_list pointer,
4360 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004361 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4362 CharUnits EltSize = TypeInfo.first / 2;
4363 if (EltSize < SlotSize) {
4364 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4365 SlotSize * 2, SlotSize,
4366 SlotSize, /*AllowHigher*/ true);
4367
4368 Address RealAddr = Addr;
4369 Address ImagAddr = RealAddr;
4370 if (CGF.CGM.getDataLayout().isBigEndian()) {
4371 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4372 SlotSize - EltSize);
4373 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4374 2 * SlotSize - EltSize);
4375 } else {
4376 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4377 }
4378
4379 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4380 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4381 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4382 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4383 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4384
4385 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4386 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4387 /*init*/ true);
4388 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004389 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004390 }
4391
John McCall7f416cc2015-09-08 08:05:57 +00004392 // Otherwise, just use the general rule.
4393 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4394 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004395}
4396
4397static bool
4398PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4399 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004400 // This is calculated from the LLVM and GCC tables and verified
4401 // against gcc output. AFAIK all ABIs use the same encoding.
4402
4403 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4404
4405 llvm::IntegerType *i8 = CGF.Int8Ty;
4406 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4407 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4408 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4409
4410 // 0-31: r0-31, the 8-byte general-purpose registers
4411 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4412
4413 // 32-63: fp0-31, the 8-byte floating-point registers
4414 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4415
4416 // 64-76 are various 4-byte special-purpose registers:
4417 // 64: mq
4418 // 65: lr
4419 // 66: ctr
4420 // 67: ap
4421 // 68-75 cr0-7
4422 // 76: xer
4423 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4424
4425 // 77-108: v0-31, the 16-byte vector registers
4426 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4427
4428 // 109: vrsave
4429 // 110: vscr
4430 // 111: spe_acc
4431 // 112: spefscr
4432 // 113: sfp
4433 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4434
4435 return false;
4436}
John McCallea8d8bb2010-03-11 00:10:12 +00004437
Bill Schmidt25cb3492012-10-03 19:18:57 +00004438bool
4439PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4440 CodeGen::CodeGenFunction &CGF,
4441 llvm::Value *Address) const {
4442
4443 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4444}
4445
4446bool
4447PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4448 llvm::Value *Address) const {
4449
4450 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4451}
4452
Chris Lattner0cf24192010-06-28 20:05:43 +00004453//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004454// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004455//===----------------------------------------------------------------------===//
4456
4457namespace {
4458
John McCall12f23522016-04-04 18:33:08 +00004459class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004460public:
4461 enum ABIKind {
4462 AAPCS = 0,
4463 DarwinPCS
4464 };
4465
4466private:
4467 ABIKind Kind;
4468
4469public:
John McCall12f23522016-04-04 18:33:08 +00004470 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4471 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004472
4473private:
4474 ABIKind getABIKind() const { return Kind; }
4475 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4476
4477 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004478 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004479 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4480 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4481 uint64_t Members) const override;
4482
Tim Northovera2ee4332014-03-29 15:09:45 +00004483 bool isIllegalVectorType(QualType Ty) const;
4484
David Blaikie1cbb9712014-11-14 19:09:44 +00004485 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004486 if (!getCXXABI().classifyReturnType(FI))
4487 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004488
Tim Northoverb047bfa2014-11-27 21:02:49 +00004489 for (auto &it : FI.arguments())
4490 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004491 }
4492
John McCall7f416cc2015-09-08 08:05:57 +00004493 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4494 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004495
John McCall7f416cc2015-09-08 08:05:57 +00004496 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4497 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004498
John McCall7f416cc2015-09-08 08:05:57 +00004499 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4500 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004501 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4502 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4503 }
John McCall12f23522016-04-04 18:33:08 +00004504
4505 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4506 ArrayRef<llvm::Type*> scalars,
4507 bool asReturnValue) const override {
4508 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4509 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004510};
4511
Tim Northover573cbee2014-05-24 12:52:07 +00004512class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004513public:
Tim Northover573cbee2014-05-24 12:52:07 +00004514 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4515 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004516
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004517 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004518 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4519 }
4520
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004521 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4522 return 31;
4523 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004524
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004525 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004526};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004527}
Tim Northovera2ee4332014-03-29 15:09:45 +00004528
Tim Northoverb047bfa2014-11-27 21:02:49 +00004529ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004530 Ty = useFirstFieldIfTransparentUnion(Ty);
4531
Tim Northovera2ee4332014-03-29 15:09:45 +00004532 // Handle illegal vector types here.
4533 if (isIllegalVectorType(Ty)) {
4534 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004535 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004536 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004537 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4538 return ABIArgInfo::getDirect(ResType);
4539 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004540 if (Size <= 32) {
4541 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004542 return ABIArgInfo::getDirect(ResType);
4543 }
4544 if (Size == 64) {
4545 llvm::Type *ResType =
4546 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004547 return ABIArgInfo::getDirect(ResType);
4548 }
4549 if (Size == 128) {
4550 llvm::Type *ResType =
4551 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004552 return ABIArgInfo::getDirect(ResType);
4553 }
John McCall7f416cc2015-09-08 08:05:57 +00004554 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004555 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004556
4557 if (!isAggregateTypeForABI(Ty)) {
4558 // Treat an enum type as its underlying type.
4559 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4560 Ty = EnumTy->getDecl()->getIntegerType();
4561
Tim Northovera2ee4332014-03-29 15:09:45 +00004562 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4563 ? ABIArgInfo::getExtend()
4564 : ABIArgInfo::getDirect());
4565 }
4566
4567 // Structures with either a non-trivial destructor or a non-trivial
4568 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004569 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004570 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4571 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004572 }
4573
4574 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4575 // elsewhere for GNU compatibility.
4576 if (isEmptyRecord(getContext(), Ty, true)) {
4577 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4578 return ABIArgInfo::getIgnore();
4579
Tim Northovera2ee4332014-03-29 15:09:45 +00004580 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4581 }
4582
4583 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004584 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004585 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004586 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004587 return ABIArgInfo::getDirect(
4588 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004589 }
4590
4591 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4592 uint64_t Size = getContext().getTypeSize(Ty);
4593 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004594 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4595 // same size and alignment.
4596 if (getTarget().isRenderScriptTarget()) {
4597 return coerceToIntArray(Ty, getContext(), getVMContext());
4598 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00004599 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004600 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004601
Tim Northovera2ee4332014-03-29 15:09:45 +00004602 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4603 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004604 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004605 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4606 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4607 }
4608 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4609 }
4610
John McCall7f416cc2015-09-08 08:05:57 +00004611 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004612}
4613
Tim Northover573cbee2014-05-24 12:52:07 +00004614ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004615 if (RetTy->isVoidType())
4616 return ABIArgInfo::getIgnore();
4617
4618 // Large vector types should be returned via memory.
4619 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004620 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004621
4622 if (!isAggregateTypeForABI(RetTy)) {
4623 // Treat an enum type as its underlying type.
4624 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4625 RetTy = EnumTy->getDecl()->getIntegerType();
4626
Tim Northover4dab6982014-04-18 13:46:08 +00004627 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4628 ? ABIArgInfo::getExtend()
4629 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004630 }
4631
Tim Northovera2ee4332014-03-29 15:09:45 +00004632 if (isEmptyRecord(getContext(), RetTy, true))
4633 return ABIArgInfo::getIgnore();
4634
Craig Topper8a13c412014-05-21 05:09:00 +00004635 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004636 uint64_t Members = 0;
4637 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004638 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4639 return ABIArgInfo::getDirect();
4640
4641 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4642 uint64_t Size = getContext().getTypeSize(RetTy);
4643 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004644 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4645 // same size and alignment.
4646 if (getTarget().isRenderScriptTarget()) {
4647 return coerceToIntArray(RetTy, getContext(), getVMContext());
4648 }
Pete Cooper635b5092015-04-17 22:16:24 +00004649 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004650 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004651
4652 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4653 // For aggregates with 16-byte alignment, we use i128.
4654 if (Alignment < 128 && Size == 128) {
4655 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4656 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4657 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004658 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4659 }
4660
John McCall7f416cc2015-09-08 08:05:57 +00004661 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004662}
4663
Tim Northover573cbee2014-05-24 12:52:07 +00004664/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4665bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004666 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4667 // Check whether VT is legal.
4668 unsigned NumElements = VT->getNumElements();
4669 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004670 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004671 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004672 return true;
4673 return Size != 64 && (Size != 128 || NumElements == 1);
4674 }
4675 return false;
4676}
4677
Reid Klecknere9f6a712014-10-31 17:10:41 +00004678bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4679 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4680 // point type or a short-vector type. This is the same as the 32-bit ABI,
4681 // but with the difference that any floating-point type is allowed,
4682 // including __fp16.
4683 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4684 if (BT->isFloatingPoint())
4685 return true;
4686 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4687 unsigned VecSize = getContext().getTypeSize(VT);
4688 if (VecSize == 64 || VecSize == 128)
4689 return true;
4690 }
4691 return false;
4692}
4693
4694bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4695 uint64_t Members) const {
4696 return Members <= 4;
4697}
4698
John McCall7f416cc2015-09-08 08:05:57 +00004699Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004700 QualType Ty,
4701 CodeGenFunction &CGF) const {
4702 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004703 bool IsIndirect = AI.isIndirect();
4704
Tim Northoverb047bfa2014-11-27 21:02:49 +00004705 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4706 if (IsIndirect)
4707 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4708 else if (AI.getCoerceToType())
4709 BaseTy = AI.getCoerceToType();
4710
4711 unsigned NumRegs = 1;
4712 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4713 BaseTy = ArrTy->getElementType();
4714 NumRegs = ArrTy->getNumElements();
4715 }
4716 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4717
Tim Northovera2ee4332014-03-29 15:09:45 +00004718 // The AArch64 va_list type and handling is specified in the Procedure Call
4719 // Standard, section B.4:
4720 //
4721 // struct {
4722 // void *__stack;
4723 // void *__gr_top;
4724 // void *__vr_top;
4725 // int __gr_offs;
4726 // int __vr_offs;
4727 // };
4728
4729 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4730 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4731 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4732 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004733
John McCall7f416cc2015-09-08 08:05:57 +00004734 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4735 CharUnits TyAlign = TyInfo.second;
4736
4737 Address reg_offs_p = Address::invalid();
4738 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004739 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004740 CharUnits reg_top_offset;
4741 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004742 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004743 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004744 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004745 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4746 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004747 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4748 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004749 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004750 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004751 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004752 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004753 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004754 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4755 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004756 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4757 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004758 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004759 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004760 }
4761
4762 //=======================================
4763 // Find out where argument was passed
4764 //=======================================
4765
4766 // If reg_offs >= 0 we're already using the stack for this type of
4767 // argument. We don't want to keep updating reg_offs (in case it overflows,
4768 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4769 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004770 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004771 UsingStack = CGF.Builder.CreateICmpSGE(
4772 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4773
4774 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4775
4776 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004777 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004778 CGF.EmitBlock(MaybeRegBlock);
4779
4780 // Integer arguments may need to correct register alignment (for example a
4781 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4782 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004783 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4784 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004785
4786 reg_offs = CGF.Builder.CreateAdd(
4787 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4788 "align_regoffs");
4789 reg_offs = CGF.Builder.CreateAnd(
4790 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4791 "aligned_regoffs");
4792 }
4793
4794 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004795 // The fact that this is done unconditionally reflects the fact that
4796 // allocating an argument to the stack also uses up all the remaining
4797 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004798 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004799 NewOffset = CGF.Builder.CreateAdd(
4800 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4801 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4802
4803 // Now we're in a position to decide whether this argument really was in
4804 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004805 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004806 InRegs = CGF.Builder.CreateICmpSLE(
4807 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4808
4809 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4810
4811 //=======================================
4812 // Argument was in registers
4813 //=======================================
4814
4815 // Now we emit the code for if the argument was originally passed in
4816 // registers. First start the appropriate block:
4817 CGF.EmitBlock(InRegBlock);
4818
John McCall7f416cc2015-09-08 08:05:57 +00004819 llvm::Value *reg_top = nullptr;
4820 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4821 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004822 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004823 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4824 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4825 Address RegAddr = Address::invalid();
4826 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004827
4828 if (IsIndirect) {
4829 // If it's been passed indirectly (actually a struct), whatever we find from
4830 // stored registers or on the stack will actually be a struct **.
4831 MemTy = llvm::PointerType::getUnqual(MemTy);
4832 }
4833
Craig Topper8a13c412014-05-21 05:09:00 +00004834 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004835 uint64_t NumMembers = 0;
4836 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004837 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004838 // Homogeneous aggregates passed in registers will have their elements split
4839 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4840 // qN+1, ...). We reload and store into a temporary local variable
4841 // contiguously.
4842 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004843 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004844 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4845 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004846 Address Tmp = CGF.CreateTempAlloca(HFATy,
4847 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004848
John McCall7f416cc2015-09-08 08:05:57 +00004849 // On big-endian platforms, the value will be right-aligned in its slot.
4850 int Offset = 0;
4851 if (CGF.CGM.getDataLayout().isBigEndian() &&
4852 BaseTyInfo.first.getQuantity() < 16)
4853 Offset = 16 - BaseTyInfo.first.getQuantity();
4854
Tim Northovera2ee4332014-03-29 15:09:45 +00004855 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004856 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4857 Address LoadAddr =
4858 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4859 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4860
4861 Address StoreAddr =
4862 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004863
4864 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4865 CGF.Builder.CreateStore(Elem, StoreAddr);
4866 }
4867
John McCall7f416cc2015-09-08 08:05:57 +00004868 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004869 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004870 // Otherwise the object is contiguous in memory.
4871
4872 // It might be right-aligned in its slot.
4873 CharUnits SlotSize = BaseAddr.getAlignment();
4874 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004875 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004876 TyInfo.first < SlotSize) {
4877 CharUnits Offset = SlotSize - TyInfo.first;
4878 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004879 }
4880
John McCall7f416cc2015-09-08 08:05:57 +00004881 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004882 }
4883
4884 CGF.EmitBranch(ContBlock);
4885
4886 //=======================================
4887 // Argument was on the stack
4888 //=======================================
4889 CGF.EmitBlock(OnStackBlock);
4890
John McCall7f416cc2015-09-08 08:05:57 +00004891 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4892 CharUnits::Zero(), "stack_p");
4893 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004894
John McCall7f416cc2015-09-08 08:05:57 +00004895 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004896 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004897 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4898 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004899
John McCall7f416cc2015-09-08 08:05:57 +00004900 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004901
John McCall7f416cc2015-09-08 08:05:57 +00004902 OnStackPtr = CGF.Builder.CreateAdd(
4903 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004904 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004905 OnStackPtr = CGF.Builder.CreateAnd(
4906 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004907 "align_stack");
4908
John McCall7f416cc2015-09-08 08:05:57 +00004909 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004910 }
John McCall7f416cc2015-09-08 08:05:57 +00004911 Address OnStackAddr(OnStackPtr,
4912 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004913
John McCall7f416cc2015-09-08 08:05:57 +00004914 // All stack slots are multiples of 8 bytes.
4915 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4916 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004917 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004918 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004919 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004920 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004921
John McCall7f416cc2015-09-08 08:05:57 +00004922 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004923 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004924 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004925
4926 // Write the new value of __stack for the next call to va_arg
4927 CGF.Builder.CreateStore(NewStack, stack_p);
4928
4929 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004930 TyInfo.first < StackSlotSize) {
4931 CharUnits Offset = StackSlotSize - TyInfo.first;
4932 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004933 }
4934
John McCall7f416cc2015-09-08 08:05:57 +00004935 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004936
4937 CGF.EmitBranch(ContBlock);
4938
4939 //=======================================
4940 // Tidy up
4941 //=======================================
4942 CGF.EmitBlock(ContBlock);
4943
John McCall7f416cc2015-09-08 08:05:57 +00004944 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4945 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004946
4947 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004948 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4949 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004950
4951 return ResAddr;
4952}
4953
John McCall7f416cc2015-09-08 08:05:57 +00004954Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4955 CodeGenFunction &CGF) const {
4956 // The backend's lowering doesn't support va_arg for aggregates or
4957 // illegal vector types. Lower VAArg here for these cases and use
4958 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004959 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00004960 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004961
John McCall7f416cc2015-09-08 08:05:57 +00004962 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004963
John McCall7f416cc2015-09-08 08:05:57 +00004964 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004965 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004966 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4967 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4968 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004969 }
4970
John McCall7f416cc2015-09-08 08:05:57 +00004971 // The size of the actual thing passed, which might end up just
4972 // being a pointer for indirect types.
4973 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4974
4975 // Arguments bigger than 16 bytes which aren't homogeneous
4976 // aggregates should be passed indirectly.
4977 bool IsIndirect = false;
4978 if (TyInfo.first.getQuantity() > 16) {
4979 const Type *Base = nullptr;
4980 uint64_t Members = 0;
4981 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004982 }
4983
John McCall7f416cc2015-09-08 08:05:57 +00004984 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4985 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004986}
4987
4988//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004989// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004990//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004991
4992namespace {
4993
John McCall12f23522016-04-04 18:33:08 +00004994class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004995public:
4996 enum ABIKind {
4997 APCS = 0,
4998 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004999 AAPCS_VFP = 2,
5000 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005001 };
5002
5003private:
5004 ABIKind Kind;
5005
5006public:
John McCall12f23522016-04-04 18:33:08 +00005007 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5008 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005009 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005010 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005011
John McCall3480ef22011-08-30 01:42:09 +00005012 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005013 switch (getTarget().getTriple().getEnvironment()) {
5014 case llvm::Triple::Android:
5015 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005016 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005017 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005018 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005019 case llvm::Triple::MuslEABI:
5020 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005021 return true;
5022 default:
5023 return false;
5024 }
John McCall3480ef22011-08-30 01:42:09 +00005025 }
5026
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005027 bool isEABIHF() const {
5028 switch (getTarget().getTriple().getEnvironment()) {
5029 case llvm::Triple::EABIHF:
5030 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005031 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005032 return true;
5033 default:
5034 return false;
5035 }
5036 }
5037
Daniel Dunbar020daa92009-09-12 01:00:39 +00005038 ABIKind getABIKind() const { return Kind; }
5039
Tim Northovera484bc02013-10-01 14:34:25 +00005040private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005041 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005042 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005043 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005044
Reid Klecknere9f6a712014-10-31 17:10:41 +00005045 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5046 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5047 uint64_t Members) const override;
5048
Craig Topper4f12f102014-03-12 06:41:41 +00005049 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005050
John McCall7f416cc2015-09-08 08:05:57 +00005051 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5052 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005053
5054 llvm::CallingConv::ID getLLVMDefaultCC() const;
5055 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005056 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005057
5058 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5059 ArrayRef<llvm::Type*> scalars,
5060 bool asReturnValue) const override {
5061 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5062 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005063};
5064
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005065class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5066public:
Chris Lattner2b037972010-07-29 02:01:43 +00005067 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5068 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005069
John McCall3480ef22011-08-30 01:42:09 +00005070 const ARMABIInfo &getABIInfo() const {
5071 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5072 }
5073
Craig Topper4f12f102014-03-12 06:41:41 +00005074 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005075 return 13;
5076 }
Roman Divackyc1617352011-05-18 19:36:54 +00005077
Craig Topper4f12f102014-03-12 06:41:41 +00005078 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005079 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5080 }
5081
Roman Divackyc1617352011-05-18 19:36:54 +00005082 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005083 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005084 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005085
5086 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005087 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005088 return false;
5089 }
John McCall3480ef22011-08-30 01:42:09 +00005090
Craig Topper4f12f102014-03-12 06:41:41 +00005091 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005092 if (getABIInfo().isEABI()) return 88;
5093 return TargetCodeGenInfo::getSizeOfUnwindException();
5094 }
Tim Northovera484bc02013-10-01 14:34:25 +00005095
Eric Christopher162c91c2015-06-05 22:03:00 +00005096 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005097 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005098 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005099 if (!FD)
5100 return;
5101
5102 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5103 if (!Attr)
5104 return;
5105
5106 const char *Kind;
5107 switch (Attr->getInterrupt()) {
5108 case ARMInterruptAttr::Generic: Kind = ""; break;
5109 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5110 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5111 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5112 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5113 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5114 }
5115
5116 llvm::Function *Fn = cast<llvm::Function>(GV);
5117
5118 Fn->addFnAttr("interrupt", Kind);
5119
Tim Northover5627d392015-10-30 16:30:45 +00005120 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5121 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005122 return;
5123
5124 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5125 // however this is not necessarily true on taking any interrupt. Instruct
5126 // the backend to perform a realignment as part of the function prologue.
5127 llvm::AttrBuilder B;
5128 B.addStackAlignmentAttr(8);
5129 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5130 llvm::AttributeSet::get(CGM.getLLVMContext(),
5131 llvm::AttributeSet::FunctionIndex,
5132 B));
5133 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005134};
5135
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005136class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005137public:
5138 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5139 : ARMTargetCodeGenInfo(CGT, K) {}
5140
Eric Christopher162c91c2015-06-05 22:03:00 +00005141 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005142 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005143
5144 void getDependentLibraryOption(llvm::StringRef Lib,
5145 llvm::SmallString<24> &Opt) const override {
5146 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5147 }
5148
5149 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5150 llvm::SmallString<32> &Opt) const override {
5151 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5152 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005153};
5154
Eric Christopher162c91c2015-06-05 22:03:00 +00005155void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005156 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005157 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005158 addStackProbeSizeTargetAttribute(D, GV, CGM);
5159}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005160}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005161
Chris Lattner22326a12010-07-29 02:31:05 +00005162void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005163 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005164 FI.getReturnInfo() =
5165 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005166
Tim Northoverbc784d12015-02-24 17:22:40 +00005167 for (auto &I : FI.arguments())
5168 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005169
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005170 // Always honor user-specified calling convention.
5171 if (FI.getCallingConvention() != llvm::CallingConv::C)
5172 return;
5173
John McCall882987f2013-02-28 19:01:20 +00005174 llvm::CallingConv::ID cc = getRuntimeCC();
5175 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005176 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005177}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005178
John McCall882987f2013-02-28 19:01:20 +00005179/// Return the default calling convention that LLVM will use.
5180llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5181 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005182 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005183 return llvm::CallingConv::ARM_AAPCS_VFP;
5184 else if (isEABI())
5185 return llvm::CallingConv::ARM_AAPCS;
5186 else
5187 return llvm::CallingConv::ARM_APCS;
5188}
5189
5190/// Return the calling convention that our ABI would like us to use
5191/// as the C calling convention.
5192llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005193 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005194 case APCS: return llvm::CallingConv::ARM_APCS;
5195 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5196 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005197 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005198 }
John McCall882987f2013-02-28 19:01:20 +00005199 llvm_unreachable("bad ABI kind");
5200}
5201
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005202void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005203 assert(getRuntimeCC() == llvm::CallingConv::C);
5204
5205 // Don't muddy up the IR with a ton of explicit annotations if
5206 // they'd just match what LLVM will infer from the triple.
5207 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5208 if (abiCC != getLLVMDefaultCC())
5209 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005210
Tim Northover5627d392015-10-30 16:30:45 +00005211 // AAPCS apparently requires runtime support functions to be soft-float, but
5212 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5213 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5214 switch (getABIKind()) {
5215 case APCS:
5216 case AAPCS16_VFP:
5217 if (abiCC != getLLVMDefaultCC())
5218 BuiltinCC = abiCC;
5219 break;
5220 case AAPCS:
5221 case AAPCS_VFP:
5222 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5223 break;
5224 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005225}
5226
Tim Northoverbc784d12015-02-24 17:22:40 +00005227ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5228 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005229 // 6.1.2.1 The following argument types are VFP CPRCs:
5230 // A single-precision floating-point type (including promoted
5231 // half-precision types); A double-precision floating-point type;
5232 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5233 // with a Base Type of a single- or double-precision floating-point type,
5234 // 64-bit containerized vectors or 128-bit containerized vectors with one
5235 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005236 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005237
Reid Klecknerb1be6832014-11-15 01:41:41 +00005238 Ty = useFirstFieldIfTransparentUnion(Ty);
5239
Manman Renfef9e312012-10-16 19:18:39 +00005240 // Handle illegal vector types here.
5241 if (isIllegalVectorType(Ty)) {
5242 uint64_t Size = getContext().getTypeSize(Ty);
5243 if (Size <= 32) {
5244 llvm::Type *ResType =
5245 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005246 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005247 }
5248 if (Size == 64) {
5249 llvm::Type *ResType = llvm::VectorType::get(
5250 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005251 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005252 }
5253 if (Size == 128) {
5254 llvm::Type *ResType = llvm::VectorType::get(
5255 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005256 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005257 }
John McCall7f416cc2015-09-08 08:05:57 +00005258 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005259 }
5260
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005261 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5262 // unspecified. This is not done for OpenCL as it handles the half type
5263 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005264 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005265 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5266 llvm::Type::getFloatTy(getVMContext()) :
5267 llvm::Type::getInt32Ty(getVMContext());
5268 return ABIArgInfo::getDirect(ResType);
5269 }
5270
John McCalla1dee5302010-08-22 10:59:02 +00005271 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005272 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005273 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005274 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005275 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005276
Tim Northover5a1558e2014-11-07 22:30:50 +00005277 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5278 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005279 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005280
Oliver Stannard405bded2014-02-11 09:25:50 +00005281 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005282 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005283 }
Tim Northover1060eae2013-06-21 22:49:34 +00005284
Daniel Dunbar09d33622009-09-14 21:54:03 +00005285 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005286 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005287 return ABIArgInfo::getIgnore();
5288
Tim Northover5a1558e2014-11-07 22:30:50 +00005289 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005290 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5291 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005292 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005293 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005294 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005295 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005296 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005297 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005298 }
Tim Northover5627d392015-10-30 16:30:45 +00005299 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5300 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5301 // this convention even for a variadic function: the backend will use GPRs
5302 // if needed.
5303 const Type *Base = nullptr;
5304 uint64_t Members = 0;
5305 if (isHomogeneousAggregate(Ty, Base, Members)) {
5306 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5307 llvm::Type *Ty =
5308 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5309 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5310 }
5311 }
5312
5313 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5314 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5315 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5316 // bigger than 128-bits, they get placed in space allocated by the caller,
5317 // and a pointer is passed.
5318 return ABIArgInfo::getIndirect(
5319 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005320 }
5321
Manman Ren6c30e132012-08-13 21:23:55 +00005322 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005323 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5324 // most 8-byte. We realign the indirect argument if type alignment is bigger
5325 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005326 uint64_t ABIAlign = 4;
5327 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5328 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005329 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005330 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005331
Manman Ren8cd99812012-11-06 04:58:01 +00005332 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005333 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005334 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5335 /*ByVal=*/true,
5336 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005337 }
5338
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005339 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5340 // same size and alignment.
5341 if (getTarget().isRenderScriptTarget()) {
5342 return coerceToIntArray(Ty, getContext(), getVMContext());
5343 }
5344
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005345 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005346 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005347 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005348 // FIXME: Try to match the types of the arguments more accurately where
5349 // we can.
5350 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005351 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5352 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005353 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005354 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5355 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005356 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005357
Tim Northover5a1558e2014-11-07 22:30:50 +00005358 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005359}
5360
Chris Lattner458b2aa2010-07-29 02:16:43 +00005361static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005362 llvm::LLVMContext &VMContext) {
5363 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5364 // is called integer-like if its size is less than or equal to one word, and
5365 // the offset of each of its addressable sub-fields is zero.
5366
5367 uint64_t Size = Context.getTypeSize(Ty);
5368
5369 // Check that the type fits in a word.
5370 if (Size > 32)
5371 return false;
5372
5373 // FIXME: Handle vector types!
5374 if (Ty->isVectorType())
5375 return false;
5376
Daniel Dunbard53bac72009-09-14 02:20:34 +00005377 // Float types are never treated as "integer like".
5378 if (Ty->isRealFloatingType())
5379 return false;
5380
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005381 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005382 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005383 return true;
5384
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005385 // Small complex integer types are "integer like".
5386 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5387 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005388
5389 // Single element and zero sized arrays should be allowed, by the definition
5390 // above, but they are not.
5391
5392 // Otherwise, it must be a record type.
5393 const RecordType *RT = Ty->getAs<RecordType>();
5394 if (!RT) return false;
5395
5396 // Ignore records with flexible arrays.
5397 const RecordDecl *RD = RT->getDecl();
5398 if (RD->hasFlexibleArrayMember())
5399 return false;
5400
5401 // Check that all sub-fields are at offset 0, and are themselves "integer
5402 // like".
5403 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5404
5405 bool HadField = false;
5406 unsigned idx = 0;
5407 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5408 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005409 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005410
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005411 // Bit-fields are not addressable, we only need to verify they are "integer
5412 // like". We still have to disallow a subsequent non-bitfield, for example:
5413 // struct { int : 0; int x }
5414 // is non-integer like according to gcc.
5415 if (FD->isBitField()) {
5416 if (!RD->isUnion())
5417 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005418
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005419 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5420 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005421
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005422 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005423 }
5424
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005425 // Check if this field is at offset 0.
5426 if (Layout.getFieldOffset(idx) != 0)
5427 return false;
5428
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005429 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5430 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005431
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005432 // Only allow at most one field in a structure. This doesn't match the
5433 // wording above, but follows gcc in situations with a field following an
5434 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005435 if (!RD->isUnion()) {
5436 if (HadField)
5437 return false;
5438
5439 HadField = true;
5440 }
5441 }
5442
5443 return true;
5444}
5445
Oliver Stannard405bded2014-02-11 09:25:50 +00005446ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5447 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005448 bool IsEffectivelyAAPCS_VFP =
5449 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005450
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005451 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005452 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005453
Daniel Dunbar19964db2010-09-23 01:54:32 +00005454 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005455 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005456 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005457 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005458
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005459 // __fp16 gets returned as if it were an int or float, but with the top 16
5460 // bits unspecified. This is not done for OpenCL as it handles the half type
5461 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005462 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005463 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5464 llvm::Type::getFloatTy(getVMContext()) :
5465 llvm::Type::getInt32Ty(getVMContext());
5466 return ABIArgInfo::getDirect(ResType);
5467 }
5468
John McCalla1dee5302010-08-22 10:59:02 +00005469 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005470 // Treat an enum type as its underlying type.
5471 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5472 RetTy = EnumTy->getDecl()->getIntegerType();
5473
Tim Northover5a1558e2014-11-07 22:30:50 +00005474 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5475 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005476 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005477
5478 // Are we following APCS?
5479 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005480 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005481 return ABIArgInfo::getIgnore();
5482
Daniel Dunbareedf1512010-02-01 23:31:19 +00005483 // Complex types are all returned as packed integers.
5484 //
5485 // FIXME: Consider using 2 x vector types if the back end handles them
5486 // correctly.
5487 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005488 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5489 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005490
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005491 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005492 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005493 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005494 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005495 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005496 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005497 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005498 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5499 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005500 }
5501
5502 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005503 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005504 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005505
5506 // Otherwise this is an AAPCS variant.
5507
Chris Lattner458b2aa2010-07-29 02:16:43 +00005508 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005509 return ABIArgInfo::getIgnore();
5510
Bob Wilson1d9269a2011-11-02 04:51:36 +00005511 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005512 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005513 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005514 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005515 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005516 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005517 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005518 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005519 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005520 }
5521
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005522 // Aggregates <= 4 bytes are returned in r0; other aggregates
5523 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005524 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005525 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005526 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5527 // same size and alignment.
5528 if (getTarget().isRenderScriptTarget()) {
5529 return coerceToIntArray(RetTy, getContext(), getVMContext());
5530 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005531 if (getDataLayout().isBigEndian())
5532 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005533 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005534
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005535 // Return in the smallest viable integer type.
5536 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005537 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005538 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005539 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5540 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005541 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5542 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5543 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005544 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005545 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005546 }
5547
John McCall7f416cc2015-09-08 08:05:57 +00005548 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005549}
5550
Manman Renfef9e312012-10-16 19:18:39 +00005551/// isIllegalVector - check whether Ty is an illegal vector type.
5552bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005553 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5554 if (isAndroid()) {
5555 // Android shipped using Clang 3.1, which supported a slightly different
5556 // vector ABI. The primary differences were that 3-element vector types
5557 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5558 // accepts that legacy behavior for Android only.
5559 // Check whether VT is legal.
5560 unsigned NumElements = VT->getNumElements();
5561 // NumElements should be power of 2 or equal to 3.
5562 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5563 return true;
5564 } else {
5565 // Check whether VT is legal.
5566 unsigned NumElements = VT->getNumElements();
5567 uint64_t Size = getContext().getTypeSize(VT);
5568 // NumElements should be power of 2.
5569 if (!llvm::isPowerOf2_32(NumElements))
5570 return true;
5571 // Size should be greater than 32 bits.
5572 return Size <= 32;
5573 }
Manman Renfef9e312012-10-16 19:18:39 +00005574 }
5575 return false;
5576}
5577
Reid Klecknere9f6a712014-10-31 17:10:41 +00005578bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5579 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5580 // double, or 64-bit or 128-bit vectors.
5581 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5582 if (BT->getKind() == BuiltinType::Float ||
5583 BT->getKind() == BuiltinType::Double ||
5584 BT->getKind() == BuiltinType::LongDouble)
5585 return true;
5586 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5587 unsigned VecSize = getContext().getTypeSize(VT);
5588 if (VecSize == 64 || VecSize == 128)
5589 return true;
5590 }
5591 return false;
5592}
5593
5594bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5595 uint64_t Members) const {
5596 return Members <= 4;
5597}
5598
John McCall7f416cc2015-09-08 08:05:57 +00005599Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5600 QualType Ty) const {
5601 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005602
John McCall7f416cc2015-09-08 08:05:57 +00005603 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005604 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005605 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5606 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5607 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005608 }
5609
John McCall7f416cc2015-09-08 08:05:57 +00005610 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5611 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005612
John McCall7f416cc2015-09-08 08:05:57 +00005613 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5614 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005615 const Type *Base = nullptr;
5616 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005617 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5618 IsIndirect = true;
5619
Tim Northover5627d392015-10-30 16:30:45 +00005620 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5621 // allocated by the caller.
5622 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5623 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5624 !isHomogeneousAggregate(Ty, Base, Members)) {
5625 IsIndirect = true;
5626
John McCall7f416cc2015-09-08 08:05:57 +00005627 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005628 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5629 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005630 // Our callers should be prepared to handle an under-aligned address.
5631 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5632 getABIKind() == ARMABIInfo::AAPCS) {
5633 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5634 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005635 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5636 // ARMv7k allows type alignment up to 16 bytes.
5637 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5638 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005639 } else {
5640 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005641 }
John McCall7f416cc2015-09-08 08:05:57 +00005642 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005643
John McCall7f416cc2015-09-08 08:05:57 +00005644 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5645 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005646}
5647
Chris Lattner0cf24192010-06-28 20:05:43 +00005648//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005649// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005650//===----------------------------------------------------------------------===//
5651
5652namespace {
5653
Justin Holewinski83e96682012-05-24 17:43:12 +00005654class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005655public:
Justin Holewinski36837432013-03-30 14:38:24 +00005656 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005657
5658 ABIArgInfo classifyReturnType(QualType RetTy) const;
5659 ABIArgInfo classifyArgumentType(QualType Ty) const;
5660
Craig Topper4f12f102014-03-12 06:41:41 +00005661 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005662 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5663 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005664};
5665
Justin Holewinski83e96682012-05-24 17:43:12 +00005666class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005667public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005668 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5669 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005670
Eric Christopher162c91c2015-06-05 22:03:00 +00005671 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005672 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005673private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005674 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5675 // resulting MDNode to the nvvm.annotations MDNode.
5676 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005677};
5678
Justin Holewinski83e96682012-05-24 17:43:12 +00005679ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005680 if (RetTy->isVoidType())
5681 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005682
5683 // note: this is different from default ABI
5684 if (!RetTy->isScalarType())
5685 return ABIArgInfo::getDirect();
5686
5687 // Treat an enum type as its underlying type.
5688 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5689 RetTy = EnumTy->getDecl()->getIntegerType();
5690
5691 return (RetTy->isPromotableIntegerType() ?
5692 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005693}
5694
Justin Holewinski83e96682012-05-24 17:43:12 +00005695ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005696 // Treat an enum type as its underlying type.
5697 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5698 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005699
Eli Bendersky95338a02014-10-29 13:43:21 +00005700 // Return aggregates type as indirect by value
5701 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005702 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005703
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005704 return (Ty->isPromotableIntegerType() ?
5705 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005706}
5707
Justin Holewinski83e96682012-05-24 17:43:12 +00005708void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005709 if (!getCXXABI().classifyReturnType(FI))
5710 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005711 for (auto &I : FI.arguments())
5712 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005713
5714 // Always honor user-specified calling convention.
5715 if (FI.getCallingConvention() != llvm::CallingConv::C)
5716 return;
5717
John McCall882987f2013-02-28 19:01:20 +00005718 FI.setEffectiveCallingConvention(getRuntimeCC());
5719}
5720
John McCall7f416cc2015-09-08 08:05:57 +00005721Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5722 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005723 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005724}
5725
Justin Holewinski83e96682012-05-24 17:43:12 +00005726void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005727setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005728 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005729 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005730 if (!FD) return;
5731
5732 llvm::Function *F = cast<llvm::Function>(GV);
5733
5734 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005735 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005736 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005737 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005738 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005739 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005740 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5741 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005742 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005743 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005744 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005745 }
Justin Holewinski38031972011-10-05 17:58:44 +00005746
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005747 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005748 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005749 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005750 // __global__ functions cannot be called from the device, we do not
5751 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005752 if (FD->hasAttr<CUDAGlobalAttr>()) {
5753 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5754 addNVVMMetadata(F, "kernel", 1);
5755 }
Artem Belevich7093e402015-04-21 22:55:54 +00005756 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005757 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005758 llvm::APSInt MaxThreads(32);
5759 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5760 if (MaxThreads > 0)
5761 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5762
5763 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5764 // not specified in __launch_bounds__ or if the user specified a 0 value,
5765 // we don't have to add a PTX directive.
5766 if (Attr->getMinBlocks()) {
5767 llvm::APSInt MinBlocks(32);
5768 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5769 if (MinBlocks > 0)
5770 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5771 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005772 }
5773 }
Justin Holewinski38031972011-10-05 17:58:44 +00005774 }
5775}
5776
Eli Benderskye06a2c42014-04-15 16:57:05 +00005777void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5778 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005779 llvm::Module *M = F->getParent();
5780 llvm::LLVMContext &Ctx = M->getContext();
5781
5782 // Get "nvvm.annotations" metadata node
5783 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5784
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005785 llvm::Metadata *MDVals[] = {
5786 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5787 llvm::ConstantAsMetadata::get(
5788 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005789 // Append metadata to nvvm.annotations
5790 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5791}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005792}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005793
5794//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005795// SystemZ ABI Implementation
5796//===----------------------------------------------------------------------===//
5797
5798namespace {
5799
Bryan Chane3f1ed52016-04-28 13:56:43 +00005800class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005801 bool HasVector;
5802
Ulrich Weigand47445072013-05-06 16:26:41 +00005803public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005804 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00005805 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005806
5807 bool isPromotableIntegerType(QualType Ty) const;
5808 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005809 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005810 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005811 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005812
5813 ABIArgInfo classifyReturnType(QualType RetTy) const;
5814 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5815
Craig Topper4f12f102014-03-12 06:41:41 +00005816 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005817 if (!getCXXABI().classifyReturnType(FI))
5818 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005819 for (auto &I : FI.arguments())
5820 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005821 }
5822
John McCall7f416cc2015-09-08 08:05:57 +00005823 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5824 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00005825
5826 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5827 ArrayRef<llvm::Type*> scalars,
5828 bool asReturnValue) const override {
5829 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5830 }
Ulrich Weigand47445072013-05-06 16:26:41 +00005831};
5832
5833class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5834public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005835 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5836 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005837};
5838
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005839}
Ulrich Weigand47445072013-05-06 16:26:41 +00005840
5841bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5842 // Treat an enum type as its underlying type.
5843 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5844 Ty = EnumTy->getDecl()->getIntegerType();
5845
5846 // Promotable integer types are required to be promoted by the ABI.
5847 if (Ty->isPromotableIntegerType())
5848 return true;
5849
5850 // 32-bit values must also be promoted.
5851 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5852 switch (BT->getKind()) {
5853 case BuiltinType::Int:
5854 case BuiltinType::UInt:
5855 return true;
5856 default:
5857 return false;
5858 }
5859 return false;
5860}
5861
5862bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005863 return (Ty->isAnyComplexType() ||
5864 Ty->isVectorType() ||
5865 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005866}
5867
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005868bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5869 return (HasVector &&
5870 Ty->isVectorType() &&
5871 getContext().getTypeSize(Ty) <= 128);
5872}
5873
Ulrich Weigand47445072013-05-06 16:26:41 +00005874bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5875 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5876 switch (BT->getKind()) {
5877 case BuiltinType::Float:
5878 case BuiltinType::Double:
5879 return true;
5880 default:
5881 return false;
5882 }
5883
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005884 return false;
5885}
5886
5887QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005888 if (const RecordType *RT = Ty->getAsStructureType()) {
5889 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005890 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005891
5892 // If this is a C++ record, check the bases first.
5893 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005894 for (const auto &I : CXXRD->bases()) {
5895 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005896
5897 // Empty bases don't affect things either way.
5898 if (isEmptyRecord(getContext(), Base, true))
5899 continue;
5900
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005901 if (!Found.isNull())
5902 return Ty;
5903 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005904 }
5905
5906 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005907 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005908 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005909 // Unlike isSingleElementStruct(), empty structure and array fields
5910 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005911 if (getContext().getLangOpts().CPlusPlus &&
5912 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5913 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005914
5915 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005916 // Nested structures still do though.
5917 if (!Found.isNull())
5918 return Ty;
5919 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005920 }
5921
5922 // Unlike isSingleElementStruct(), trailing padding is allowed.
5923 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005924 if (!Found.isNull())
5925 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005926 }
5927
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005928 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005929}
5930
John McCall7f416cc2015-09-08 08:05:57 +00005931Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5932 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005933 // Assume that va_list type is correct; should be pointer to LLVM type:
5934 // struct {
5935 // i64 __gpr;
5936 // i64 __fpr;
5937 // i8 *__overflow_arg_area;
5938 // i8 *__reg_save_area;
5939 // };
5940
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005941 // Every non-vector argument occupies 8 bytes and is passed by preference
5942 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5943 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005944 Ty = getContext().getCanonicalType(Ty);
5945 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005946 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005947 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005948 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005949 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005950 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005951 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005952 CharUnits UnpaddedSize;
5953 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005954 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005955 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5956 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005957 } else {
5958 if (AI.getCoerceToType())
5959 ArgTy = AI.getCoerceToType();
5960 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005961 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005962 UnpaddedSize = TyInfo.first;
5963 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005964 }
John McCall7f416cc2015-09-08 08:05:57 +00005965 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5966 if (IsVector && UnpaddedSize > PaddedSize)
5967 PaddedSize = CharUnits::fromQuantity(16);
5968 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005969
John McCall7f416cc2015-09-08 08:05:57 +00005970 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005971
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005972 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005973 llvm::Value *PaddedSizeV =
5974 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005975
5976 if (IsVector) {
5977 // Work out the address of a vector argument on the stack.
5978 // Vector arguments are always passed in the high bits of a
5979 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005980 Address OverflowArgAreaPtr =
5981 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005982 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005983 Address OverflowArgArea =
5984 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5985 TyInfo.second);
5986 Address MemAddr =
5987 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005988
5989 // Update overflow_arg_area_ptr pointer
5990 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005991 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5992 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005993 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5994
5995 return MemAddr;
5996 }
5997
John McCall7f416cc2015-09-08 08:05:57 +00005998 assert(PaddedSize.getQuantity() == 8);
5999
6000 unsigned MaxRegs, RegCountField, RegSaveIndex;
6001 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006002 if (InFPRs) {
6003 MaxRegs = 4; // Maximum of 4 FPR arguments
6004 RegCountField = 1; // __fpr
6005 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006006 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006007 } else {
6008 MaxRegs = 5; // Maximum of 5 GPR arguments
6009 RegCountField = 0; // __gpr
6010 RegSaveIndex = 2; // save offset for r2
6011 RegPadding = Padding; // values are passed in the low bits of a GPR
6012 }
6013
John McCall7f416cc2015-09-08 08:05:57 +00006014 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6015 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6016 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006017 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006018 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6019 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006020 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006021
6022 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6023 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6024 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6025 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6026
6027 // Emit code to load the value if it was passed in registers.
6028 CGF.EmitBlock(InRegBlock);
6029
6030 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006031 llvm::Value *ScaledRegCount =
6032 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6033 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006034 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6035 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006036 llvm::Value *RegOffset =
6037 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006038 Address RegSaveAreaPtr =
6039 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6040 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006041 llvm::Value *RegSaveArea =
6042 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006043 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6044 "raw_reg_addr"),
6045 PaddedSize);
6046 Address RegAddr =
6047 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006048
6049 // Update the register count
6050 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6051 llvm::Value *NewRegCount =
6052 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6053 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6054 CGF.EmitBranch(ContBlock);
6055
6056 // Emit code to load the value if it was passed in memory.
6057 CGF.EmitBlock(InMemBlock);
6058
6059 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006060 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6061 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6062 Address OverflowArgArea =
6063 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6064 PaddedSize);
6065 Address RawMemAddr =
6066 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6067 Address MemAddr =
6068 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006069
6070 // Update overflow_arg_area_ptr pointer
6071 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006072 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6073 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006074 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6075 CGF.EmitBranch(ContBlock);
6076
6077 // Return the appropriate result.
6078 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006079 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6080 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006081
6082 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006083 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6084 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006085
6086 return ResAddr;
6087}
6088
Ulrich Weigand47445072013-05-06 16:26:41 +00006089ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6090 if (RetTy->isVoidType())
6091 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006092 if (isVectorArgumentType(RetTy))
6093 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006094 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006095 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006096 return (isPromotableIntegerType(RetTy) ?
6097 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6098}
6099
6100ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6101 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006102 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006103 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006104
6105 // Integers and enums are extended to full register width.
6106 if (isPromotableIntegerType(Ty))
6107 return ABIArgInfo::getExtend();
6108
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006109 // Handle vector types and vector-like structure types. Note that
6110 // as opposed to float-like structure types, we do not allow any
6111 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006112 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006113 QualType SingleElementTy = GetSingleElementType(Ty);
6114 if (isVectorArgumentType(SingleElementTy) &&
6115 getContext().getTypeSize(SingleElementTy) == Size)
6116 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6117
6118 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006119 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006120 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006121
6122 // Handle small structures.
6123 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6124 // Structures with flexible arrays have variable length, so really
6125 // fail the size test above.
6126 const RecordDecl *RD = RT->getDecl();
6127 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006128 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006129
6130 // The structure is passed as an unextended integer, a float, or a double.
6131 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006132 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006133 assert(Size == 32 || Size == 64);
6134 if (Size == 32)
6135 PassTy = llvm::Type::getFloatTy(getVMContext());
6136 else
6137 PassTy = llvm::Type::getDoubleTy(getVMContext());
6138 } else
6139 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6140 return ABIArgInfo::getDirect(PassTy);
6141 }
6142
6143 // Non-structure compounds are passed indirectly.
6144 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006145 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006146
Craig Topper8a13c412014-05-21 05:09:00 +00006147 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006148}
6149
6150//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006151// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006152//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006153
6154namespace {
6155
6156class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6157public:
Chris Lattner2b037972010-07-29 02:01:43 +00006158 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6159 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006160 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006161 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006162};
6163
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006164}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006165
Eric Christopher162c91c2015-06-05 22:03:00 +00006166void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006167 llvm::GlobalValue *GV,
6168 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006169 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006170 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6171 // Handle 'interrupt' attribute:
6172 llvm::Function *F = cast<llvm::Function>(GV);
6173
6174 // Step 1: Set ISR calling convention.
6175 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6176
6177 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006178 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006179
6180 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006181 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006182 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6183 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006184 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006185 }
6186}
6187
Chris Lattner0cf24192010-06-28 20:05:43 +00006188//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006189// MIPS ABI Implementation. This works for both little-endian and
6190// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006191//===----------------------------------------------------------------------===//
6192
John McCall943fae92010-05-27 06:19:26 +00006193namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006194class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006195 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006196 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6197 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006198 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006199 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006200 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006201 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006202public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006203 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006204 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006205 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006206
6207 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006208 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006209 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006210 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6211 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006212 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006213};
6214
John McCall943fae92010-05-27 06:19:26 +00006215class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006216 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006217public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006218 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6219 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006220 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006221
Craig Topper4f12f102014-03-12 06:41:41 +00006222 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006223 return 29;
6224 }
6225
Eric Christopher162c91c2015-06-05 22:03:00 +00006226 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006227 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006228 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006229 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006230 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006231 if (FD->hasAttr<Mips16Attr>()) {
6232 Fn->addFnAttr("mips16");
6233 }
6234 else if (FD->hasAttr<NoMips16Attr>()) {
6235 Fn->addFnAttr("nomips16");
6236 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006237
6238 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6239 if (!Attr)
6240 return;
6241
6242 const char *Kind;
6243 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006244 case MipsInterruptAttr::eic: Kind = "eic"; break;
6245 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6246 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6247 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6248 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6249 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6250 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6251 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6252 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6253 }
6254
6255 Fn->addFnAttr("interrupt", Kind);
6256
Reed Kotler373feca2013-01-16 17:10:28 +00006257 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006258
John McCall943fae92010-05-27 06:19:26 +00006259 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006260 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006261
Craig Topper4f12f102014-03-12 06:41:41 +00006262 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006263 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006264 }
John McCall943fae92010-05-27 06:19:26 +00006265};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006266}
John McCall943fae92010-05-27 06:19:26 +00006267
Eric Christopher7565e0d2015-05-29 23:09:49 +00006268void MipsABIInfo::CoerceToIntArgs(
6269 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006270 llvm::IntegerType *IntTy =
6271 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006272
6273 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6274 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6275 ArgList.push_back(IntTy);
6276
6277 // If necessary, add one more integer type to ArgList.
6278 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6279
6280 if (R)
6281 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006282}
6283
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006284// In N32/64, an aligned double precision floating point field is passed in
6285// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006286llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006287 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6288
6289 if (IsO32) {
6290 CoerceToIntArgs(TySize, ArgList);
6291 return llvm::StructType::get(getVMContext(), ArgList);
6292 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006293
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006294 if (Ty->isComplexType())
6295 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006296
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006297 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006298
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006299 // Unions/vectors are passed in integer registers.
6300 if (!RT || !RT->isStructureOrClassType()) {
6301 CoerceToIntArgs(TySize, ArgList);
6302 return llvm::StructType::get(getVMContext(), ArgList);
6303 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006304
6305 const RecordDecl *RD = RT->getDecl();
6306 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006307 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006308
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006309 uint64_t LastOffset = 0;
6310 unsigned idx = 0;
6311 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6312
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006313 // Iterate over fields in the struct/class and check if there are any aligned
6314 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006315 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6316 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006317 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006318 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6319
6320 if (!BT || BT->getKind() != BuiltinType::Double)
6321 continue;
6322
6323 uint64_t Offset = Layout.getFieldOffset(idx);
6324 if (Offset % 64) // Ignore doubles that are not aligned.
6325 continue;
6326
6327 // Add ((Offset - LastOffset) / 64) args of type i64.
6328 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6329 ArgList.push_back(I64);
6330
6331 // Add double type.
6332 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6333 LastOffset = Offset + 64;
6334 }
6335
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006336 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6337 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006338
6339 return llvm::StructType::get(getVMContext(), ArgList);
6340}
6341
Akira Hatanakaddd66342013-10-29 18:41:15 +00006342llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6343 uint64_t Offset) const {
6344 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006345 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006346
Akira Hatanakaddd66342013-10-29 18:41:15 +00006347 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006348}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006349
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006350ABIArgInfo
6351MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006352 Ty = useFirstFieldIfTransparentUnion(Ty);
6353
Akira Hatanaka1632af62012-01-09 19:31:25 +00006354 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006355 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006356 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006357
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006358 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6359 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006360 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6361 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006362
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006363 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006364 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006365 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006366 return ABIArgInfo::getIgnore();
6367
Mark Lacey3825e832013-10-06 01:33:34 +00006368 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006369 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006370 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006371 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006372
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006373 // If we have reached here, aggregates are passed directly by coercing to
6374 // another structure type. Padding is inserted if the offset of the
6375 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006376 ABIArgInfo ArgInfo =
6377 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6378 getPaddingType(OrigOffset, CurrOffset));
6379 ArgInfo.setInReg(true);
6380 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006381 }
6382
6383 // Treat an enum type as its underlying type.
6384 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6385 Ty = EnumTy->getDecl()->getIntegerType();
6386
Daniel Sanders5b445b32014-10-24 14:42:42 +00006387 // All integral types are promoted to the GPR width.
6388 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006389 return ABIArgInfo::getExtend();
6390
Akira Hatanakaddd66342013-10-29 18:41:15 +00006391 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006392 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006393}
6394
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006395llvm::Type*
6396MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006397 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006398 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006399
Akira Hatanakab6f74432012-02-09 18:49:26 +00006400 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006401 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006402 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6403 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006404
Akira Hatanakab6f74432012-02-09 18:49:26 +00006405 // N32/64 returns struct/classes in floating point registers if the
6406 // following conditions are met:
6407 // 1. The size of the struct/class is no larger than 128-bit.
6408 // 2. The struct/class has one or two fields all of which are floating
6409 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006410 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006411 //
6412 // Any other composite results are returned in integer registers.
6413 //
6414 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6415 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6416 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006417 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006418
Akira Hatanakab6f74432012-02-09 18:49:26 +00006419 if (!BT || !BT->isFloatingPoint())
6420 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006421
David Blaikie2d7c57e2012-04-30 02:36:29 +00006422 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006423 }
6424
6425 if (b == e)
6426 return llvm::StructType::get(getVMContext(), RTList,
6427 RD->hasAttr<PackedAttr>());
6428
6429 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006430 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006431 }
6432
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006433 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006434 return llvm::StructType::get(getVMContext(), RTList);
6435}
6436
Akira Hatanakab579fe52011-06-02 00:09:17 +00006437ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006438 uint64_t Size = getContext().getTypeSize(RetTy);
6439
Daniel Sandersed39f582014-09-04 13:28:14 +00006440 if (RetTy->isVoidType())
6441 return ABIArgInfo::getIgnore();
6442
6443 // O32 doesn't treat zero-sized structs differently from other structs.
6444 // However, N32/N64 ignores zero sized return values.
6445 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006446 return ABIArgInfo::getIgnore();
6447
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006448 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006449 if (Size <= 128) {
6450 if (RetTy->isAnyComplexType())
6451 return ABIArgInfo::getDirect();
6452
Daniel Sanderse5018b62014-09-04 15:05:39 +00006453 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006454 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006455 if (!IsO32 ||
6456 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6457 ABIArgInfo ArgInfo =
6458 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6459 ArgInfo.setInReg(true);
6460 return ArgInfo;
6461 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006462 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006463
John McCall7f416cc2015-09-08 08:05:57 +00006464 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006465 }
6466
6467 // Treat an enum type as its underlying type.
6468 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6469 RetTy = EnumTy->getDecl()->getIntegerType();
6470
6471 return (RetTy->isPromotableIntegerType() ?
6472 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6473}
6474
6475void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006476 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006477 if (!getCXXABI().classifyReturnType(FI))
6478 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006479
Eric Christopher7565e0d2015-05-29 23:09:49 +00006480 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006481 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006482
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006483 for (auto &I : FI.arguments())
6484 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006485}
6486
John McCall7f416cc2015-09-08 08:05:57 +00006487Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6488 QualType OrigTy) const {
6489 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006490
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006491 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6492 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006493 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006494 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006495 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006496 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006497 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006498 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006499 DidPromote = true;
6500 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6501 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006502 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006503
John McCall7f416cc2015-09-08 08:05:57 +00006504 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006505
John McCall7f416cc2015-09-08 08:05:57 +00006506 // The alignment of things in the argument area is never larger than
6507 // StackAlignInBytes.
6508 TyInfo.second =
6509 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6510
6511 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6512 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6513
6514 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6515 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6516
6517
6518 // If there was a promotion, "unpromote" into a temporary.
6519 // TODO: can we just use a pointer into a subset of the original slot?
6520 if (DidPromote) {
6521 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6522 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6523
6524 // Truncate down to the right width.
6525 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6526 : CGF.IntPtrTy);
6527 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6528 if (OrigTy->isPointerType())
6529 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6530
6531 CGF.Builder.CreateStore(V, Temp);
6532 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006533 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006534
John McCall7f416cc2015-09-08 08:05:57 +00006535 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006536}
6537
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006538bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6539 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006540
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006541 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6542 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6543 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006544
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006545 return false;
6546}
6547
John McCall943fae92010-05-27 06:19:26 +00006548bool
6549MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6550 llvm::Value *Address) const {
6551 // This information comes from gcc's implementation, which seems to
6552 // as canonical as it gets.
6553
John McCall943fae92010-05-27 06:19:26 +00006554 // Everything on MIPS is 4 bytes. Double-precision FP registers
6555 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006556 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006557
6558 // 0-31 are the general purpose registers, $0 - $31.
6559 // 32-63 are the floating-point registers, $f0 - $f31.
6560 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6561 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006562 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006563
6564 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6565 // They are one bit wide and ignored here.
6566
6567 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6568 // (coprocessor 1 is the FP unit)
6569 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6570 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6571 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006572 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006573 return false;
6574}
6575
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006576//===----------------------------------------------------------------------===//
6577// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006578// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006579// handling.
6580//===----------------------------------------------------------------------===//
6581
6582namespace {
6583
6584class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6585public:
6586 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6587 : DefaultTargetCodeGenInfo(CGT) {}
6588
Eric Christopher162c91c2015-06-05 22:03:00 +00006589 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006590 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006591};
6592
Eric Christopher162c91c2015-06-05 22:03:00 +00006593void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006594 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006595 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006596 if (!FD) return;
6597
6598 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006599
David Blaikiebbafb8a2012-03-11 07:00:24 +00006600 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006601 if (FD->hasAttr<OpenCLKernelAttr>()) {
6602 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006603 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006604 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6605 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006606 // Convert the reqd_work_group_size() attributes to metadata.
6607 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006608 llvm::NamedMDNode *OpenCLMetadata =
6609 M.getModule().getOrInsertNamedMetadata(
6610 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006611
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006612 SmallVector<llvm::Metadata *, 5> Operands;
6613 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006614
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006615 Operands.push_back(
6616 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6617 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6618 Operands.push_back(
6619 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6620 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6621 Operands.push_back(
6622 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6623 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006624
Eric Christopher7565e0d2015-05-29 23:09:49 +00006625 // Add a boolean constant operand for "required" (true) or "hint"
6626 // (false) for implementing the work_group_size_hint attr later.
6627 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006628 Operands.push_back(
6629 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006630 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6631 }
6632 }
6633 }
6634}
6635
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006636}
John McCall943fae92010-05-27 06:19:26 +00006637
Tony Linthicum76329bf2011-12-12 21:14:55 +00006638//===----------------------------------------------------------------------===//
6639// Hexagon ABI Implementation
6640//===----------------------------------------------------------------------===//
6641
6642namespace {
6643
6644class HexagonABIInfo : public ABIInfo {
6645
6646
6647public:
6648 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6649
6650private:
6651
6652 ABIArgInfo classifyReturnType(QualType RetTy) const;
6653 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6654
Craig Topper4f12f102014-03-12 06:41:41 +00006655 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006656
John McCall7f416cc2015-09-08 08:05:57 +00006657 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6658 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006659};
6660
6661class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6662public:
6663 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6664 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6665
Craig Topper4f12f102014-03-12 06:41:41 +00006666 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006667 return 29;
6668 }
6669};
6670
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006671}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006672
6673void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006674 if (!getCXXABI().classifyReturnType(FI))
6675 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006676 for (auto &I : FI.arguments())
6677 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006678}
6679
6680ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6681 if (!isAggregateTypeForABI(Ty)) {
6682 // Treat an enum type as its underlying type.
6683 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6684 Ty = EnumTy->getDecl()->getIntegerType();
6685
6686 return (Ty->isPromotableIntegerType() ?
6687 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6688 }
6689
6690 // Ignore empty records.
6691 if (isEmptyRecord(getContext(), Ty, true))
6692 return ABIArgInfo::getIgnore();
6693
Mark Lacey3825e832013-10-06 01:33:34 +00006694 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006695 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006696
6697 uint64_t Size = getContext().getTypeSize(Ty);
6698 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006699 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006700 // Pass in the smallest viable integer type.
6701 else if (Size > 32)
6702 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6703 else if (Size > 16)
6704 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6705 else if (Size > 8)
6706 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6707 else
6708 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6709}
6710
6711ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6712 if (RetTy->isVoidType())
6713 return ABIArgInfo::getIgnore();
6714
6715 // Large vector types should be returned via memory.
6716 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006717 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006718
6719 if (!isAggregateTypeForABI(RetTy)) {
6720 // Treat an enum type as its underlying type.
6721 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6722 RetTy = EnumTy->getDecl()->getIntegerType();
6723
6724 return (RetTy->isPromotableIntegerType() ?
6725 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6726 }
6727
Tony Linthicum76329bf2011-12-12 21:14:55 +00006728 if (isEmptyRecord(getContext(), RetTy, true))
6729 return ABIArgInfo::getIgnore();
6730
6731 // Aggregates <= 8 bytes are returned in r0; other aggregates
6732 // are returned indirectly.
6733 uint64_t Size = getContext().getTypeSize(RetTy);
6734 if (Size <= 64) {
6735 // Return in the smallest viable integer type.
6736 if (Size <= 8)
6737 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6738 if (Size <= 16)
6739 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6740 if (Size <= 32)
6741 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6742 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6743 }
6744
John McCall7f416cc2015-09-08 08:05:57 +00006745 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006746}
6747
John McCall7f416cc2015-09-08 08:05:57 +00006748Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6749 QualType Ty) const {
6750 // FIXME: Someone needs to audit that this handle alignment correctly.
6751 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6752 getContext().getTypeInfoInChars(Ty),
6753 CharUnits::fromQuantity(4),
6754 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006755}
6756
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006757//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006758// Lanai ABI Implementation
6759//===----------------------------------------------------------------------===//
6760
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006761namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006762class LanaiABIInfo : public DefaultABIInfo {
6763public:
6764 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6765
6766 bool shouldUseInReg(QualType Ty, CCState &State) const;
6767
6768 void computeInfo(CGFunctionInfo &FI) const override {
6769 CCState State(FI.getCallingConvention());
6770 // Lanai uses 4 registers to pass arguments unless the function has the
6771 // regparm attribute set.
6772 if (FI.getHasRegParm()) {
6773 State.FreeRegs = FI.getRegParm();
6774 } else {
6775 State.FreeRegs = 4;
6776 }
6777
6778 if (!getCXXABI().classifyReturnType(FI))
6779 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6780 for (auto &I : FI.arguments())
6781 I.info = classifyArgumentType(I.type, State);
6782 }
6783
Jacques Pienaare74d9132016-04-26 00:09:29 +00006784 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006785 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6786};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006787} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006788
6789bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6790 unsigned Size = getContext().getTypeSize(Ty);
6791 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6792
6793 if (SizeInRegs == 0)
6794 return false;
6795
6796 if (SizeInRegs > State.FreeRegs) {
6797 State.FreeRegs = 0;
6798 return false;
6799 }
6800
6801 State.FreeRegs -= SizeInRegs;
6802
6803 return true;
6804}
6805
Jacques Pienaare74d9132016-04-26 00:09:29 +00006806ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6807 CCState &State) const {
6808 if (!ByVal) {
6809 if (State.FreeRegs) {
6810 --State.FreeRegs; // Non-byval indirects just use one pointer.
6811 return getNaturalAlignIndirectInReg(Ty);
6812 }
6813 return getNaturalAlignIndirect(Ty, false);
6814 }
6815
6816 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00006817 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00006818 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6819 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6820 /*Realign=*/TypeAlign >
6821 MinABIStackAlignInBytes);
6822}
6823
Jacques Pienaard964cc22016-03-28 21:02:54 +00006824ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6825 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006826 // Check with the C++ ABI first.
6827 const RecordType *RT = Ty->getAs<RecordType>();
6828 if (RT) {
6829 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6830 if (RAA == CGCXXABI::RAA_Indirect) {
6831 return getIndirectResult(Ty, /*ByVal=*/false, State);
6832 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6833 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6834 }
6835 }
6836
6837 if (isAggregateTypeForABI(Ty)) {
6838 // Structures with flexible arrays are always indirect.
6839 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6840 return getIndirectResult(Ty, /*ByVal=*/true, State);
6841
6842 // Ignore empty structs/unions.
6843 if (isEmptyRecord(getContext(), Ty, true))
6844 return ABIArgInfo::getIgnore();
6845
6846 llvm::LLVMContext &LLVMContext = getVMContext();
6847 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6848 if (SizeInRegs <= State.FreeRegs) {
6849 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6850 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6851 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6852 State.FreeRegs -= SizeInRegs;
6853 return ABIArgInfo::getDirectInReg(Result);
6854 } else {
6855 State.FreeRegs = 0;
6856 }
6857 return getIndirectResult(Ty, true, State);
6858 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00006859
6860 // Treat an enum type as its underlying type.
6861 if (const auto *EnumTy = Ty->getAs<EnumType>())
6862 Ty = EnumTy->getDecl()->getIntegerType();
6863
Jacques Pienaare74d9132016-04-26 00:09:29 +00006864 bool InReg = shouldUseInReg(Ty, State);
6865 if (Ty->isPromotableIntegerType()) {
6866 if (InReg)
6867 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006868 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00006869 }
6870 if (InReg)
6871 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006872 return ABIArgInfo::getDirect();
6873}
6874
6875namespace {
6876class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6877public:
6878 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
6879 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
6880};
6881}
6882
6883//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006884// AMDGPU ABI Implementation
6885//===----------------------------------------------------------------------===//
6886
6887namespace {
6888
Matt Arsenault88d7da02016-08-22 19:25:59 +00006889class AMDGPUABIInfo final : public DefaultABIInfo {
6890public:
6891 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6892
6893private:
6894 ABIArgInfo classifyArgumentType(QualType Ty) const;
6895
6896 void computeInfo(CGFunctionInfo &FI) const override;
6897};
6898
6899void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
6900 if (!getCXXABI().classifyReturnType(FI))
6901 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6902
6903 unsigned CC = FI.getCallingConvention();
6904 for (auto &Arg : FI.arguments())
6905 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
6906 Arg.info = classifyArgumentType(Arg.type);
6907 else
6908 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
6909}
6910
6911/// \brief Classify argument of given type \p Ty.
6912ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
6913 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6914 if (!StrTy) {
6915 return DefaultABIInfo::classifyArgumentType(Ty);
6916 }
6917
6918 // Coerce single element structs to its element.
6919 if (StrTy->getNumElements() == 1) {
6920 return ABIArgInfo::getDirect();
6921 }
6922
6923 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
6924 // individual elements, which confuses the Clover OpenCL backend; therefore we
6925 // have to set it to false here. Other args of getDirect() are just defaults.
6926 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6927}
6928
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006929class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6930public:
6931 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00006932 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006933 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006934 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00006935 unsigned getOpenCLKernelCallingConv() const override;
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006936};
6937
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006938}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006939
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00006940static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
6941
Eric Christopher162c91c2015-06-05 22:03:00 +00006942void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006943 const Decl *D,
6944 llvm::GlobalValue *GV,
6945 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006946 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006947 if (!FD)
6948 return;
6949
6950 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6951 llvm::Function *F = cast<llvm::Function>(GV);
6952 uint32_t NumVGPR = Attr->getNumVGPR();
6953 if (NumVGPR != 0)
6954 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6955 }
6956
6957 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6958 llvm::Function *F = cast<llvm::Function>(GV);
6959 unsigned NumSGPR = Attr->getNumSGPR();
6960 if (NumSGPR != 0)
6961 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6962 }
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006963
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00006964 appendOpenCLVersionMD(M);
6965}
6966
Tony Linthicum76329bf2011-12-12 21:14:55 +00006967
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00006968unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
6969 return llvm::CallingConv::AMDGPU_KERNEL;
6970}
6971
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006972//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00006973// SPARC v8 ABI Implementation.
6974// Based on the SPARC Compliance Definition version 2.4.1.
6975//
6976// Ensures that complex values are passed in registers.
6977//
6978namespace {
6979class SparcV8ABIInfo : public DefaultABIInfo {
6980public:
6981 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6982
6983private:
6984 ABIArgInfo classifyReturnType(QualType RetTy) const;
6985 void computeInfo(CGFunctionInfo &FI) const override;
6986};
6987} // end anonymous namespace
6988
6989
6990ABIArgInfo
6991SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
6992 if (Ty->isAnyComplexType()) {
6993 return ABIArgInfo::getDirect();
6994 }
6995 else {
6996 return DefaultABIInfo::classifyReturnType(Ty);
6997 }
6998}
6999
7000void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7001
7002 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7003 for (auto &Arg : FI.arguments())
7004 Arg.info = classifyArgumentType(Arg.type);
7005}
7006
7007namespace {
7008class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7009public:
7010 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7011 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7012};
7013} // end anonymous namespace
7014
7015//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007016// SPARC v9 ABI Implementation.
7017// Based on the SPARC Compliance Definition version 2.4.1.
7018//
7019// Function arguments a mapped to a nominal "parameter array" and promoted to
7020// registers depending on their type. Each argument occupies 8 or 16 bytes in
7021// the array, structs larger than 16 bytes are passed indirectly.
7022//
7023// One case requires special care:
7024//
7025// struct mixed {
7026// int i;
7027// float f;
7028// };
7029//
7030// When a struct mixed is passed by value, it only occupies 8 bytes in the
7031// parameter array, but the int is passed in an integer register, and the float
7032// is passed in a floating point register. This is represented as two arguments
7033// with the LLVM IR inreg attribute:
7034//
7035// declare void f(i32 inreg %i, float inreg %f)
7036//
7037// The code generator will only allocate 4 bytes from the parameter array for
7038// the inreg arguments. All other arguments are allocated a multiple of 8
7039// bytes.
7040//
7041namespace {
7042class SparcV9ABIInfo : public ABIInfo {
7043public:
7044 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7045
7046private:
7047 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007048 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007049 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7050 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007051
7052 // Coercion type builder for structs passed in registers. The coercion type
7053 // serves two purposes:
7054 //
7055 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7056 // in registers.
7057 // 2. Expose aligned floating point elements as first-level elements, so the
7058 // code generator knows to pass them in floating point registers.
7059 //
7060 // We also compute the InReg flag which indicates that the struct contains
7061 // aligned 32-bit floats.
7062 //
7063 struct CoerceBuilder {
7064 llvm::LLVMContext &Context;
7065 const llvm::DataLayout &DL;
7066 SmallVector<llvm::Type*, 8> Elems;
7067 uint64_t Size;
7068 bool InReg;
7069
7070 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7071 : Context(c), DL(dl), Size(0), InReg(false) {}
7072
7073 // Pad Elems with integers until Size is ToSize.
7074 void pad(uint64_t ToSize) {
7075 assert(ToSize >= Size && "Cannot remove elements");
7076 if (ToSize == Size)
7077 return;
7078
7079 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007080 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007081 if (Aligned > Size && Aligned <= ToSize) {
7082 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7083 Size = Aligned;
7084 }
7085
7086 // Add whole 64-bit words.
7087 while (Size + 64 <= ToSize) {
7088 Elems.push_back(llvm::Type::getInt64Ty(Context));
7089 Size += 64;
7090 }
7091
7092 // Final in-word padding.
7093 if (Size < ToSize) {
7094 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7095 Size = ToSize;
7096 }
7097 }
7098
7099 // Add a floating point element at Offset.
7100 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7101 // Unaligned floats are treated as integers.
7102 if (Offset % Bits)
7103 return;
7104 // The InReg flag is only required if there are any floats < 64 bits.
7105 if (Bits < 64)
7106 InReg = true;
7107 pad(Offset);
7108 Elems.push_back(Ty);
7109 Size = Offset + Bits;
7110 }
7111
7112 // Add a struct type to the coercion type, starting at Offset (in bits).
7113 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7114 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7115 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7116 llvm::Type *ElemTy = StrTy->getElementType(i);
7117 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7118 switch (ElemTy->getTypeID()) {
7119 case llvm::Type::StructTyID:
7120 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7121 break;
7122 case llvm::Type::FloatTyID:
7123 addFloat(ElemOffset, ElemTy, 32);
7124 break;
7125 case llvm::Type::DoubleTyID:
7126 addFloat(ElemOffset, ElemTy, 64);
7127 break;
7128 case llvm::Type::FP128TyID:
7129 addFloat(ElemOffset, ElemTy, 128);
7130 break;
7131 case llvm::Type::PointerTyID:
7132 if (ElemOffset % 64 == 0) {
7133 pad(ElemOffset);
7134 Elems.push_back(ElemTy);
7135 Size += 64;
7136 }
7137 break;
7138 default:
7139 break;
7140 }
7141 }
7142 }
7143
7144 // Check if Ty is a usable substitute for the coercion type.
7145 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007146 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007147 }
7148
7149 // Get the coercion type as a literal struct type.
7150 llvm::Type *getType() const {
7151 if (Elems.size() == 1)
7152 return Elems.front();
7153 else
7154 return llvm::StructType::get(Context, Elems);
7155 }
7156 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007157};
7158} // end anonymous namespace
7159
7160ABIArgInfo
7161SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7162 if (Ty->isVoidType())
7163 return ABIArgInfo::getIgnore();
7164
7165 uint64_t Size = getContext().getTypeSize(Ty);
7166
7167 // Anything too big to fit in registers is passed with an explicit indirect
7168 // pointer / sret pointer.
7169 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007170 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007171
7172 // Treat an enum type as its underlying type.
7173 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7174 Ty = EnumTy->getDecl()->getIntegerType();
7175
7176 // Integer types smaller than a register are extended.
7177 if (Size < 64 && Ty->isIntegerType())
7178 return ABIArgInfo::getExtend();
7179
7180 // Other non-aggregates go in registers.
7181 if (!isAggregateTypeForABI(Ty))
7182 return ABIArgInfo::getDirect();
7183
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007184 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7185 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7186 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007187 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007188
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007189 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007190 // Build a coercion type from the LLVM struct type.
7191 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7192 if (!StrTy)
7193 return ABIArgInfo::getDirect();
7194
7195 CoerceBuilder CB(getVMContext(), getDataLayout());
7196 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007197 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007198
7199 // Try to use the original type for coercion.
7200 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7201
7202 if (CB.InReg)
7203 return ABIArgInfo::getDirectInReg(CoerceTy);
7204 else
7205 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007206}
7207
John McCall7f416cc2015-09-08 08:05:57 +00007208Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7209 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007210 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7211 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7212 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7213 AI.setCoerceToType(ArgTy);
7214
John McCall7f416cc2015-09-08 08:05:57 +00007215 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007216
John McCall7f416cc2015-09-08 08:05:57 +00007217 CGBuilderTy &Builder = CGF.Builder;
7218 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7219 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7220
7221 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7222
7223 Address ArgAddr = Address::invalid();
7224 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007225 switch (AI.getKind()) {
7226 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007227 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007228 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007229 llvm_unreachable("Unsupported ABI kind for va_arg");
7230
John McCall7f416cc2015-09-08 08:05:57 +00007231 case ABIArgInfo::Extend: {
7232 Stride = SlotSize;
7233 CharUnits Offset = SlotSize - TypeInfo.first;
7234 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007235 break;
John McCall7f416cc2015-09-08 08:05:57 +00007236 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007237
John McCall7f416cc2015-09-08 08:05:57 +00007238 case ABIArgInfo::Direct: {
7239 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007240 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007241 ArgAddr = Addr;
7242 break;
John McCall7f416cc2015-09-08 08:05:57 +00007243 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007244
7245 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007246 Stride = SlotSize;
7247 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7248 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7249 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007250 break;
7251
7252 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007253 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007254 }
7255
7256 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007257 llvm::Value *NextPtr =
7258 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7259 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007260
John McCall7f416cc2015-09-08 08:05:57 +00007261 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007262}
7263
7264void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7265 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007266 for (auto &I : FI.arguments())
7267 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007268}
7269
7270namespace {
7271class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7272public:
7273 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7274 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007275
Craig Topper4f12f102014-03-12 06:41:41 +00007276 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007277 return 14;
7278 }
7279
7280 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007281 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007282};
7283} // end anonymous namespace
7284
Roman Divackyf02c9942014-02-24 18:46:27 +00007285bool
7286SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7287 llvm::Value *Address) const {
7288 // This is calculated from the LLVM and GCC tables and verified
7289 // against gcc output. AFAIK all ABIs use the same encoding.
7290
7291 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7292
7293 llvm::IntegerType *i8 = CGF.Int8Ty;
7294 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7295 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7296
7297 // 0-31: the 8-byte general-purpose registers
7298 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7299
7300 // 32-63: f0-31, the 4-byte floating-point registers
7301 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7302
7303 // Y = 64
7304 // PSR = 65
7305 // WIM = 66
7306 // TBR = 67
7307 // PC = 68
7308 // NPC = 69
7309 // FSR = 70
7310 // CSR = 71
7311 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007312
Roman Divackyf02c9942014-02-24 18:46:27 +00007313 // 72-87: d0-15, the 8-byte floating-point registers
7314 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7315
7316 return false;
7317}
7318
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007319
Robert Lytton0e076492013-08-13 09:43:10 +00007320//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007321// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007322//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007323
Robert Lytton0e076492013-08-13 09:43:10 +00007324namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007325
7326/// A SmallStringEnc instance is used to build up the TypeString by passing
7327/// it by reference between functions that append to it.
7328typedef llvm::SmallString<128> SmallStringEnc;
7329
7330/// TypeStringCache caches the meta encodings of Types.
7331///
7332/// The reason for caching TypeStrings is two fold:
7333/// 1. To cache a type's encoding for later uses;
7334/// 2. As a means to break recursive member type inclusion.
7335///
7336/// A cache Entry can have a Status of:
7337/// NonRecursive: The type encoding is not recursive;
7338/// Recursive: The type encoding is recursive;
7339/// Incomplete: An incomplete TypeString;
7340/// IncompleteUsed: An incomplete TypeString that has been used in a
7341/// Recursive type encoding.
7342///
7343/// A NonRecursive entry will have all of its sub-members expanded as fully
7344/// as possible. Whilst it may contain types which are recursive, the type
7345/// itself is not recursive and thus its encoding may be safely used whenever
7346/// the type is encountered.
7347///
7348/// A Recursive entry will have all of its sub-members expanded as fully as
7349/// possible. The type itself is recursive and it may contain other types which
7350/// are recursive. The Recursive encoding must not be used during the expansion
7351/// of a recursive type's recursive branch. For simplicity the code uses
7352/// IncompleteCount to reject all usage of Recursive encodings for member types.
7353///
7354/// An Incomplete entry is always a RecordType and only encodes its
7355/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7356/// are placed into the cache during type expansion as a means to identify and
7357/// handle recursive inclusion of types as sub-members. If there is recursion
7358/// the entry becomes IncompleteUsed.
7359///
7360/// During the expansion of a RecordType's members:
7361///
7362/// If the cache contains a NonRecursive encoding for the member type, the
7363/// cached encoding is used;
7364///
7365/// If the cache contains a Recursive encoding for the member type, the
7366/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7367///
7368/// If the member is a RecordType, an Incomplete encoding is placed into the
7369/// cache to break potential recursive inclusion of itself as a sub-member;
7370///
7371/// Once a member RecordType has been expanded, its temporary incomplete
7372/// entry is removed from the cache. If a Recursive encoding was swapped out
7373/// it is swapped back in;
7374///
7375/// If an incomplete entry is used to expand a sub-member, the incomplete
7376/// entry is marked as IncompleteUsed. The cache keeps count of how many
7377/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7378///
7379/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7380/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7381/// Else the member is part of a recursive type and thus the recursion has
7382/// been exited too soon for the encoding to be correct for the member.
7383///
7384class TypeStringCache {
7385 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7386 struct Entry {
7387 std::string Str; // The encoded TypeString for the type.
7388 enum Status State; // Information about the encoding in 'Str'.
7389 std::string Swapped; // A temporary place holder for a Recursive encoding
7390 // during the expansion of RecordType's members.
7391 };
7392 std::map<const IdentifierInfo *, struct Entry> Map;
7393 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7394 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7395public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007396 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007397 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7398 bool removeIncomplete(const IdentifierInfo *ID);
7399 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7400 bool IsRecursive);
7401 StringRef lookupStr(const IdentifierInfo *ID);
7402};
7403
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007404/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007405/// FieldEncoding is a helper for this ordering process.
7406class FieldEncoding {
7407 bool HasName;
7408 std::string Enc;
7409public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007410 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7411 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007412 bool operator<(const FieldEncoding &rhs) const {
7413 if (HasName != rhs.HasName) return HasName;
7414 return Enc < rhs.Enc;
7415 }
7416};
7417
Robert Lytton7d1db152013-08-19 09:46:39 +00007418class XCoreABIInfo : public DefaultABIInfo {
7419public:
7420 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007421 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7422 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007423};
7424
Robert Lyttond21e2d72014-03-03 13:45:29 +00007425class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007426 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007427public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007428 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007429 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007430 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7431 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007432};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007433
Robert Lytton2d196952013-10-11 10:29:34 +00007434} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007435
James Y Knight29b5f082016-02-24 02:59:33 +00007436// TODO: this implementation is likely now redundant with the default
7437// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007438Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7439 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007440 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007441
Robert Lytton2d196952013-10-11 10:29:34 +00007442 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007443 CharUnits SlotSize = CharUnits::fromQuantity(4);
7444 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007445
Robert Lytton2d196952013-10-11 10:29:34 +00007446 // Handle the argument.
7447 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007448 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007449 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7450 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7451 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007452 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007453
7454 Address Val = Address::invalid();
7455 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007456 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007457 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007458 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007459 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007460 llvm_unreachable("Unsupported ABI kind for va_arg");
7461 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007462 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7463 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007464 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007465 case ABIArgInfo::Extend:
7466 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007467 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7468 ArgSize = CharUnits::fromQuantity(
7469 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007470 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007471 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007472 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007473 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7474 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7475 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007476 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007477 }
Robert Lytton2d196952013-10-11 10:29:34 +00007478
7479 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007480 if (!ArgSize.isZero()) {
7481 llvm::Value *APN =
7482 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7483 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007484 }
John McCall7f416cc2015-09-08 08:05:57 +00007485
Robert Lytton2d196952013-10-11 10:29:34 +00007486 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007487}
Robert Lytton0e076492013-08-13 09:43:10 +00007488
Robert Lytton844aeeb2014-05-02 09:33:20 +00007489/// During the expansion of a RecordType, an incomplete TypeString is placed
7490/// into the cache as a means to identify and break recursion.
7491/// If there is a Recursive encoding in the cache, it is swapped out and will
7492/// be reinserted by removeIncomplete().
7493/// All other types of encoding should have been used rather than arriving here.
7494void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7495 std::string StubEnc) {
7496 if (!ID)
7497 return;
7498 Entry &E = Map[ID];
7499 assert( (E.Str.empty() || E.State == Recursive) &&
7500 "Incorrectly use of addIncomplete");
7501 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7502 E.Swapped.swap(E.Str); // swap out the Recursive
7503 E.Str.swap(StubEnc);
7504 E.State = Incomplete;
7505 ++IncompleteCount;
7506}
7507
7508/// Once the RecordType has been expanded, the temporary incomplete TypeString
7509/// must be removed from the cache.
7510/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7511/// Returns true if the RecordType was defined recursively.
7512bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7513 if (!ID)
7514 return false;
7515 auto I = Map.find(ID);
7516 assert(I != Map.end() && "Entry not present");
7517 Entry &E = I->second;
7518 assert( (E.State == Incomplete ||
7519 E.State == IncompleteUsed) &&
7520 "Entry must be an incomplete type");
7521 bool IsRecursive = false;
7522 if (E.State == IncompleteUsed) {
7523 // We made use of our Incomplete encoding, thus we are recursive.
7524 IsRecursive = true;
7525 --IncompleteUsedCount;
7526 }
7527 if (E.Swapped.empty())
7528 Map.erase(I);
7529 else {
7530 // Swap the Recursive back.
7531 E.Swapped.swap(E.Str);
7532 E.Swapped.clear();
7533 E.State = Recursive;
7534 }
7535 --IncompleteCount;
7536 return IsRecursive;
7537}
7538
7539/// Add the encoded TypeString to the cache only if it is NonRecursive or
7540/// Recursive (viz: all sub-members were expanded as fully as possible).
7541void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7542 bool IsRecursive) {
7543 if (!ID || IncompleteUsedCount)
7544 return; // No key or it is is an incomplete sub-type so don't add.
7545 Entry &E = Map[ID];
7546 if (IsRecursive && !E.Str.empty()) {
7547 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7548 "This is not the same Recursive entry");
7549 // The parent container was not recursive after all, so we could have used
7550 // this Recursive sub-member entry after all, but we assumed the worse when
7551 // we started viz: IncompleteCount!=0.
7552 return;
7553 }
7554 assert(E.Str.empty() && "Entry already present");
7555 E.Str = Str.str();
7556 E.State = IsRecursive? Recursive : NonRecursive;
7557}
7558
7559/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7560/// are recursively expanding a type (IncompleteCount != 0) and the cached
7561/// encoding is Recursive, return an empty StringRef.
7562StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7563 if (!ID)
7564 return StringRef(); // We have no key.
7565 auto I = Map.find(ID);
7566 if (I == Map.end())
7567 return StringRef(); // We have no encoding.
7568 Entry &E = I->second;
7569 if (E.State == Recursive && IncompleteCount)
7570 return StringRef(); // We don't use Recursive encodings for member types.
7571
7572 if (E.State == Incomplete) {
7573 // The incomplete type is being used to break out of recursion.
7574 E.State = IncompleteUsed;
7575 ++IncompleteUsedCount;
7576 }
7577 return E.Str.c_str();
7578}
7579
7580/// The XCore ABI includes a type information section that communicates symbol
7581/// type information to the linker. The linker uses this information to verify
7582/// safety/correctness of things such as array bound and pointers et al.
7583/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7584/// This type information (TypeString) is emitted into meta data for all global
7585/// symbols: definitions, declarations, functions & variables.
7586///
7587/// The TypeString carries type, qualifier, name, size & value details.
7588/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007589/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007590/// The output is tested by test/CodeGen/xcore-stringtype.c.
7591///
7592static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7593 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7594
7595/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7596void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7597 CodeGen::CodeGenModule &CGM) const {
7598 SmallStringEnc Enc;
7599 if (getTypeString(Enc, D, CGM, TSC)) {
7600 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00007601 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
7602 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007603 llvm::NamedMDNode *MD =
7604 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7605 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7606 }
7607}
7608
Xiuli Pan972bea82016-03-24 03:57:17 +00007609//===----------------------------------------------------------------------===//
7610// SPIR ABI Implementation
7611//===----------------------------------------------------------------------===//
7612
7613namespace {
7614class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7615public:
7616 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7617 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7618 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7619 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007620 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00007621};
7622} // End anonymous namespace.
7623
7624/// Emit SPIR specific metadata: OpenCL and SPIR version.
7625void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7626 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00007627 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7628 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7629 llvm::Module &M = CGM.getModule();
7630 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7631 // opencl.spir.version named metadata.
7632 llvm::Metadata *SPIRVerElts[] = {
7633 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7634 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7635 llvm::NamedMDNode *SPIRVerMD =
7636 M.getOrInsertNamedMetadata("opencl.spir.version");
7637 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007638 appendOpenCLVersionMD(CGM);
7639}
7640
7641static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM) {
7642 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7643 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7644 llvm::Module &M = CGM.getModule();
Xiuli Pan972bea82016-03-24 03:57:17 +00007645 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7646 // opencl.ocl.version named metadata node.
7647 llvm::Metadata *OCLVerElts[] = {
7648 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7649 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7650 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7651 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7652 llvm::NamedMDNode *OCLVerMD =
7653 M.getOrInsertNamedMetadata("opencl.ocl.version");
7654 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7655}
7656
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007657unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7658 return llvm::CallingConv::SPIR_KERNEL;
7659}
7660
Robert Lytton844aeeb2014-05-02 09:33:20 +00007661static bool appendType(SmallStringEnc &Enc, QualType QType,
7662 const CodeGen::CodeGenModule &CGM,
7663 TypeStringCache &TSC);
7664
7665/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007666/// Builds a SmallVector containing the encoded field types in declaration
7667/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007668static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7669 const RecordDecl *RD,
7670 const CodeGen::CodeGenModule &CGM,
7671 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007672 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007673 SmallStringEnc Enc;
7674 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007675 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007676 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007677 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007678 Enc += "b(";
7679 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007680 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007681 Enc += ':';
7682 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007683 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007684 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007685 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007686 Enc += ')';
7687 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007688 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007689 }
7690 return true;
7691}
7692
7693/// Appends structure and union types to Enc and adds encoding to cache.
7694/// Recursively calls appendType (via extractFieldType) for each field.
7695/// Union types have their fields ordered according to the ABI.
7696static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7697 const CodeGen::CodeGenModule &CGM,
7698 TypeStringCache &TSC, const IdentifierInfo *ID) {
7699 // Append the cached TypeString if we have one.
7700 StringRef TypeString = TSC.lookupStr(ID);
7701 if (!TypeString.empty()) {
7702 Enc += TypeString;
7703 return true;
7704 }
7705
7706 // Start to emit an incomplete TypeString.
7707 size_t Start = Enc.size();
7708 Enc += (RT->isUnionType()? 'u' : 's');
7709 Enc += '(';
7710 if (ID)
7711 Enc += ID->getName();
7712 Enc += "){";
7713
7714 // We collect all encoded fields and order as necessary.
7715 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007716 const RecordDecl *RD = RT->getDecl()->getDefinition();
7717 if (RD && !RD->field_empty()) {
7718 // An incomplete TypeString stub is placed in the cache for this RecordType
7719 // so that recursive calls to this RecordType will use it whilst building a
7720 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007721 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007722 std::string StubEnc(Enc.substr(Start).str());
7723 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7724 TSC.addIncomplete(ID, std::move(StubEnc));
7725 if (!extractFieldType(FE, RD, CGM, TSC)) {
7726 (void) TSC.removeIncomplete(ID);
7727 return false;
7728 }
7729 IsRecursive = TSC.removeIncomplete(ID);
7730 // The ABI requires unions to be sorted but not structures.
7731 // See FieldEncoding::operator< for sort algorithm.
7732 if (RT->isUnionType())
7733 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007734 // We can now complete the TypeString.
7735 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007736 for (unsigned I = 0; I != E; ++I) {
7737 if (I)
7738 Enc += ',';
7739 Enc += FE[I].str();
7740 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007741 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007742 Enc += '}';
7743 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7744 return true;
7745}
7746
7747/// Appends enum types to Enc and adds the encoding to the cache.
7748static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7749 TypeStringCache &TSC,
7750 const IdentifierInfo *ID) {
7751 // Append the cached TypeString if we have one.
7752 StringRef TypeString = TSC.lookupStr(ID);
7753 if (!TypeString.empty()) {
7754 Enc += TypeString;
7755 return true;
7756 }
7757
7758 size_t Start = Enc.size();
7759 Enc += "e(";
7760 if (ID)
7761 Enc += ID->getName();
7762 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007763
7764 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007765 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007766 SmallVector<FieldEncoding, 16> FE;
7767 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7768 ++I) {
7769 SmallStringEnc EnumEnc;
7770 EnumEnc += "m(";
7771 EnumEnc += I->getName();
7772 EnumEnc += "){";
7773 I->getInitVal().toString(EnumEnc);
7774 EnumEnc += '}';
7775 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7776 }
7777 std::sort(FE.begin(), FE.end());
7778 unsigned E = FE.size();
7779 for (unsigned I = 0; I != E; ++I) {
7780 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007781 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007782 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007783 }
7784 }
7785 Enc += '}';
7786 TSC.addIfComplete(ID, Enc.substr(Start), false);
7787 return true;
7788}
7789
7790/// Appends type's qualifier to Enc.
7791/// This is done prior to appending the type's encoding.
7792static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7793 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007794 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007795 int Lookup = 0;
7796 if (QT.isConstQualified())
7797 Lookup += 1<<0;
7798 if (QT.isRestrictQualified())
7799 Lookup += 1<<1;
7800 if (QT.isVolatileQualified())
7801 Lookup += 1<<2;
7802 Enc += Table[Lookup];
7803}
7804
7805/// Appends built-in types to Enc.
7806static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7807 const char *EncType;
7808 switch (BT->getKind()) {
7809 case BuiltinType::Void:
7810 EncType = "0";
7811 break;
7812 case BuiltinType::Bool:
7813 EncType = "b";
7814 break;
7815 case BuiltinType::Char_U:
7816 EncType = "uc";
7817 break;
7818 case BuiltinType::UChar:
7819 EncType = "uc";
7820 break;
7821 case BuiltinType::SChar:
7822 EncType = "sc";
7823 break;
7824 case BuiltinType::UShort:
7825 EncType = "us";
7826 break;
7827 case BuiltinType::Short:
7828 EncType = "ss";
7829 break;
7830 case BuiltinType::UInt:
7831 EncType = "ui";
7832 break;
7833 case BuiltinType::Int:
7834 EncType = "si";
7835 break;
7836 case BuiltinType::ULong:
7837 EncType = "ul";
7838 break;
7839 case BuiltinType::Long:
7840 EncType = "sl";
7841 break;
7842 case BuiltinType::ULongLong:
7843 EncType = "ull";
7844 break;
7845 case BuiltinType::LongLong:
7846 EncType = "sll";
7847 break;
7848 case BuiltinType::Float:
7849 EncType = "ft";
7850 break;
7851 case BuiltinType::Double:
7852 EncType = "d";
7853 break;
7854 case BuiltinType::LongDouble:
7855 EncType = "ld";
7856 break;
7857 default:
7858 return false;
7859 }
7860 Enc += EncType;
7861 return true;
7862}
7863
7864/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7865static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7866 const CodeGen::CodeGenModule &CGM,
7867 TypeStringCache &TSC) {
7868 Enc += "p(";
7869 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7870 return false;
7871 Enc += ')';
7872 return true;
7873}
7874
7875/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007876static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7877 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007878 const CodeGen::CodeGenModule &CGM,
7879 TypeStringCache &TSC, StringRef NoSizeEnc) {
7880 if (AT->getSizeModifier() != ArrayType::Normal)
7881 return false;
7882 Enc += "a(";
7883 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7884 CAT->getSize().toStringUnsigned(Enc);
7885 else
7886 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7887 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007888 // The Qualifiers should be attached to the type rather than the array.
7889 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007890 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7891 return false;
7892 Enc += ')';
7893 return true;
7894}
7895
7896/// Appends a function encoding to Enc, calling appendType for the return type
7897/// and the arguments.
7898static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7899 const CodeGen::CodeGenModule &CGM,
7900 TypeStringCache &TSC) {
7901 Enc += "f{";
7902 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7903 return false;
7904 Enc += "}(";
7905 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7906 // N.B. we are only interested in the adjusted param types.
7907 auto I = FPT->param_type_begin();
7908 auto E = FPT->param_type_end();
7909 if (I != E) {
7910 do {
7911 if (!appendType(Enc, *I, CGM, TSC))
7912 return false;
7913 ++I;
7914 if (I != E)
7915 Enc += ',';
7916 } while (I != E);
7917 if (FPT->isVariadic())
7918 Enc += ",va";
7919 } else {
7920 if (FPT->isVariadic())
7921 Enc += "va";
7922 else
7923 Enc += '0';
7924 }
7925 }
7926 Enc += ')';
7927 return true;
7928}
7929
7930/// Handles the type's qualifier before dispatching a call to handle specific
7931/// type encodings.
7932static bool appendType(SmallStringEnc &Enc, QualType QType,
7933 const CodeGen::CodeGenModule &CGM,
7934 TypeStringCache &TSC) {
7935
7936 QualType QT = QType.getCanonicalType();
7937
Robert Lytton6adb20f2014-06-05 09:06:21 +00007938 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7939 // The Qualifiers should be attached to the type rather than the array.
7940 // Thus we don't call appendQualifier() here.
7941 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7942
Robert Lytton844aeeb2014-05-02 09:33:20 +00007943 appendQualifier(Enc, QT);
7944
7945 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7946 return appendBuiltinType(Enc, BT);
7947
Robert Lytton844aeeb2014-05-02 09:33:20 +00007948 if (const PointerType *PT = QT->getAs<PointerType>())
7949 return appendPointerType(Enc, PT, CGM, TSC);
7950
7951 if (const EnumType *ET = QT->getAs<EnumType>())
7952 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7953
7954 if (const RecordType *RT = QT->getAsStructureType())
7955 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7956
7957 if (const RecordType *RT = QT->getAsUnionType())
7958 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7959
7960 if (const FunctionType *FT = QT->getAs<FunctionType>())
7961 return appendFunctionType(Enc, FT, CGM, TSC);
7962
7963 return false;
7964}
7965
7966static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7967 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7968 if (!D)
7969 return false;
7970
7971 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7972 if (FD->getLanguageLinkage() != CLanguageLinkage)
7973 return false;
7974 return appendType(Enc, FD->getType(), CGM, TSC);
7975 }
7976
7977 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7978 if (VD->getLanguageLinkage() != CLanguageLinkage)
7979 return false;
7980 QualType QT = VD->getType().getCanonicalType();
7981 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7982 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007983 // The Qualifiers should be attached to the type rather than the array.
7984 // Thus we don't call appendQualifier() here.
7985 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007986 }
7987 return appendType(Enc, QT, CGM, TSC);
7988 }
7989 return false;
7990}
7991
7992
Robert Lytton0e076492013-08-13 09:43:10 +00007993//===----------------------------------------------------------------------===//
7994// Driver code
7995//===----------------------------------------------------------------------===//
7996
Rafael Espindola9f834732014-09-19 01:54:22 +00007997const llvm::Triple &CodeGenModule::getTriple() const {
7998 return getTarget().getTriple();
7999}
8000
8001bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008002 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008003}
8004
Chris Lattner2b037972010-07-29 02:01:43 +00008005const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008006 if (TheTargetCodeGenInfo)
8007 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008008
Reid Kleckner9305fd12016-04-13 23:37:17 +00008009 // Helper to set the unique_ptr while still keeping the return value.
8010 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8011 this->TheTargetCodeGenInfo.reset(P);
8012 return *P;
8013 };
8014
John McCallc8e01702013-04-16 22:48:15 +00008015 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008016 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008017 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008018 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008019
Derek Schuff09338a22012-09-06 17:37:28 +00008020 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008021 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008022 case llvm::Triple::mips:
8023 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008024 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008025 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8026 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008027
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008028 case llvm::Triple::mips64:
8029 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008030 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008031
Tim Northover25e8a672014-05-24 12:51:25 +00008032 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008033 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008034 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008035 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008036 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00008037
Reid Kleckner9305fd12016-04-13 23:37:17 +00008038 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008039 }
8040
Dan Gohmanc2853072015-09-03 22:51:53 +00008041 case llvm::Triple::wasm32:
8042 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008043 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008044
Daniel Dunbard59655c2009-09-12 00:59:49 +00008045 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008046 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008047 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008048 case llvm::Triple::thumbeb: {
8049 if (Triple.getOS() == llvm::Triple::Win32) {
8050 return SetCGInfo(
8051 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008052 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008053
Reid Kleckner9305fd12016-04-13 23:37:17 +00008054 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8055 StringRef ABIStr = getTarget().getABI();
8056 if (ABIStr == "apcs-gnu")
8057 Kind = ARMABIInfo::APCS;
8058 else if (ABIStr == "aapcs16")
8059 Kind = ARMABIInfo::AAPCS16_VFP;
8060 else if (CodeGenOpts.FloatABI == "hard" ||
8061 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008062 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008063 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008064 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008065 Kind = ARMABIInfo::AAPCS_VFP;
8066
8067 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8068 }
8069
John McCallea8d8bb2010-03-11 00:10:12 +00008070 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008071 return SetCGInfo(
8072 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008073 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008074 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008075 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008076 if (getTarget().getABI() == "elfv2")
8077 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008078 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008079
Reid Kleckner9305fd12016-04-13 23:37:17 +00008080 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008081 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008082 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008083 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008084 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008085 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008086 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008087 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008088 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008089
Reid Kleckner9305fd12016-04-13 23:37:17 +00008090 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008091 }
John McCallea8d8bb2010-03-11 00:10:12 +00008092
Peter Collingbournec947aae2012-05-20 23:28:41 +00008093 case llvm::Triple::nvptx:
8094 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008095 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008096
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008097 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008098 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008099
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008100 case llvm::Triple::systemz: {
8101 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008102 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008103 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008104
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008105 case llvm::Triple::tce:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008106 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008107
Eli Friedman33465822011-07-08 23:31:17 +00008108 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008109 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008110 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008111 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008112 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008113
John McCall1fe2a8c2013-06-18 02:46:29 +00008114 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008115 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8116 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8117 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008118 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008119 return SetCGInfo(new X86_32TargetCodeGenInfo(
8120 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8121 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8122 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008123 }
Eli Friedman33465822011-07-08 23:31:17 +00008124 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008125
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008126 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008127 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008128 X86AVXABILevel AVXLevel =
8129 (ABI == "avx512"
8130 ? X86AVXABILevel::AVX512
8131 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008132
Chris Lattner04dc9572010-08-31 16:44:54 +00008133 switch (Triple.getOS()) {
8134 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008135 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008136 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008137 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008138 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008139 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008140 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008141 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008142 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008143 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008144 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008145 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008146 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008147 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008148 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008149 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008150 case llvm::Triple::sparc:
8151 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008152 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008153 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008154 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008155 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008156 case llvm::Triple::spir:
8157 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008158 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008159 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008160}