blob: caac27b965cc0f4caa86ef9936d27484cf2b3ffe [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;
Erich Keane757d3172016-11-02 18:29:35 +00001232 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1233 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001234 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1235 // The LLVM struct type for such an aggregate should lower properly.
1236 return ABIArgInfo::getDirect();
1237 }
1238
Chris Lattner458b2aa2010-07-29 02:16:43 +00001239 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001240 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001241 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001242 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001243
1244 // 128-bit vectors are a special case; they are returned in
1245 // registers and we need to make sure to pick a type the LLVM
1246 // backend will like.
1247 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001248 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001249 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001250
1251 // Always return in register if it fits in a general purpose
1252 // register, or if it is 64 bits and has a single element.
1253 if ((Size == 8 || Size == 16 || Size == 32) ||
1254 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001255 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001256 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001257
John McCall7f416cc2015-09-08 08:05:57 +00001258 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001259 }
1260
1261 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001262 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001263
John McCalla1dee5302010-08-22 10:59:02 +00001264 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001265 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001266 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001267 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001268 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001269 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001270
David Chisnallde3a0692009-08-17 23:08:21 +00001271 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001272 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001273 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001274
Denis Zobnin380b2242016-02-11 11:26:03 +00001275 // Ignore empty structs/unions.
1276 if (isEmptyRecord(getContext(), RetTy, true))
1277 return ABIArgInfo::getIgnore();
1278
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001279 // Small structures which are register sized are generally returned
1280 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001281 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001282 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001283
1284 // As a special-case, if the struct is a "single-element" struct, and
1285 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001286 // floating-point register. (MSVC does not apply this special case.)
1287 // We apply a similar transformation for pointer types to improve the
1288 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001289 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001290 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001291 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001292 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1293
1294 // FIXME: We should be able to narrow this integer in cases with dead
1295 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001296 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001297 }
1298
John McCall7f416cc2015-09-08 08:05:57 +00001299 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001300 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001301
Chris Lattner458b2aa2010-07-29 02:16:43 +00001302 // Treat an enum type as its underlying type.
1303 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1304 RetTy = EnumTy->getDecl()->getIntegerType();
1305
1306 return (RetTy->isPromotableIntegerType() ?
1307 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001308}
1309
Eli Friedman7919bea2012-06-05 19:40:46 +00001310static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1311 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1312}
1313
Daniel Dunbared23de32010-09-16 20:42:00 +00001314static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1315 const RecordType *RT = Ty->getAs<RecordType>();
1316 if (!RT)
1317 return 0;
1318 const RecordDecl *RD = RT->getDecl();
1319
1320 // If this is a C++ record, check the bases first.
1321 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001322 for (const auto &I : CXXRD->bases())
1323 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001324 return false;
1325
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001326 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001327 QualType FT = i->getType();
1328
Eli Friedman7919bea2012-06-05 19:40:46 +00001329 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001330 return true;
1331
1332 if (isRecordWithSSEVectorType(Context, FT))
1333 return true;
1334 }
1335
1336 return false;
1337}
1338
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001339unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1340 unsigned Align) const {
1341 // Otherwise, if the alignment is less than or equal to the minimum ABI
1342 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001343 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001344 return 0; // Use default alignment.
1345
1346 // On non-Darwin, the stack type alignment is always 4.
1347 if (!IsDarwinVectorABI) {
1348 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001349 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001350 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001351
Daniel Dunbared23de32010-09-16 20:42:00 +00001352 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001353 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1354 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001355 return 16;
1356
1357 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001358}
1359
Rafael Espindola703c47f2012-10-19 05:04:37 +00001360ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001361 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001362 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001363 if (State.FreeRegs) {
1364 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001365 if (!IsMCUABI)
1366 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001367 }
John McCall7f416cc2015-09-08 08:05:57 +00001368 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001369 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001370
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001371 // Compute the byval alignment.
1372 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1373 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1374 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001375 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001376
1377 // If the stack alignment is less than the type alignment, realign the
1378 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001379 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001380 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1381 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001382}
1383
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001384X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1385 const Type *T = isSingleElementStruct(Ty, getContext());
1386 if (!T)
1387 T = Ty.getTypePtr();
1388
1389 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1390 BuiltinType::Kind K = BT->getKind();
1391 if (K == BuiltinType::Float || K == BuiltinType::Double)
1392 return Float;
1393 }
1394 return Integer;
1395}
1396
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001397bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001398 if (!IsSoftFloatABI) {
1399 Class C = classify(Ty);
1400 if (C == Float)
1401 return false;
1402 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001403
Rafael Espindola077dd592012-10-24 01:58:58 +00001404 unsigned Size = getContext().getTypeSize(Ty);
1405 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001406
1407 if (SizeInRegs == 0)
1408 return false;
1409
Michael Kuperstein68901882015-10-25 08:18:20 +00001410 if (!IsMCUABI) {
1411 if (SizeInRegs > State.FreeRegs) {
1412 State.FreeRegs = 0;
1413 return false;
1414 }
1415 } else {
1416 // The MCU psABI allows passing parameters in-reg even if there are
1417 // earlier parameters that are passed on the stack. Also,
1418 // it does not allow passing >8-byte structs in-register,
1419 // even if there are 3 free registers available.
1420 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1421 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001422 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001423
Reid Kleckner661f35b2014-01-18 01:12:41 +00001424 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001425 return true;
1426}
1427
1428bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1429 bool &InReg,
1430 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001431 // On Windows, aggregates other than HFAs are never passed in registers, and
1432 // they do not consume register slots. Homogenous floating-point aggregates
1433 // (HFAs) have already been dealt with at this point.
1434 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1435 return false;
1436
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001437 NeedsPadding = false;
1438 InReg = !IsMCUABI;
1439
1440 if (!updateFreeRegs(Ty, State))
1441 return false;
1442
1443 if (IsMCUABI)
1444 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001445
Reid Kleckner80944df2014-10-31 22:00:51 +00001446 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001447 State.CC == llvm::CallingConv::X86_VectorCall ||
1448 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001449 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001450 NeedsPadding = true;
1451
Rafael Espindola077dd592012-10-24 01:58:58 +00001452 return false;
1453 }
1454
Rafael Espindola703c47f2012-10-19 05:04:37 +00001455 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001456}
1457
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001458bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1459 if (!updateFreeRegs(Ty, State))
1460 return false;
1461
1462 if (IsMCUABI)
1463 return false;
1464
1465 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001466 State.CC == llvm::CallingConv::X86_VectorCall ||
1467 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001468 if (getContext().getTypeSize(Ty) > 32)
1469 return false;
1470
1471 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1472 Ty->isReferenceType());
1473 }
1474
1475 return true;
1476}
1477
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001478ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1479 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001480 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001481
Reid Klecknerb1be6832014-11-15 01:41:41 +00001482 Ty = useFirstFieldIfTransparentUnion(Ty);
1483
Reid Kleckner80944df2014-10-31 22:00:51 +00001484 // Check with the C++ ABI first.
1485 const RecordType *RT = Ty->getAs<RecordType>();
1486 if (RT) {
1487 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1488 if (RAA == CGCXXABI::RAA_Indirect) {
1489 return getIndirectResult(Ty, false, State);
1490 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1491 // The field index doesn't matter, we'll fix it up later.
1492 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1493 }
1494 }
1495
1496 // vectorcall adds the concept of a homogenous vector aggregate, similar
1497 // to other targets.
1498 const Type *Base = nullptr;
1499 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001500 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1501 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001502 isHomogeneousAggregate(Ty, Base, NumElts)) {
1503 if (State.FreeSSERegs >= NumElts) {
1504 State.FreeSSERegs -= NumElts;
1505 if (Ty->isBuiltinType() || Ty->isVectorType())
1506 return ABIArgInfo::getDirect();
1507 return ABIArgInfo::getExpand();
1508 }
1509 return getIndirectResult(Ty, /*ByVal=*/false, State);
1510 }
1511
1512 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001513 // Structures with flexible arrays are always indirect.
1514 // FIXME: This should not be byval!
1515 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1516 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001517
Reid Kleckner04046052016-05-02 17:41:07 +00001518 // Ignore empty structs/unions on non-Windows.
1519 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001520 return ABIArgInfo::getIgnore();
1521
Rafael Espindolafad28de2012-10-24 01:59:00 +00001522 llvm::LLVMContext &LLVMContext = getVMContext();
1523 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001524 bool NeedsPadding = false;
1525 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001526 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001527 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001528 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001529 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001530 if (InReg)
1531 return ABIArgInfo::getDirectInReg(Result);
1532 else
1533 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001534 }
Craig Topper8a13c412014-05-21 05:09:00 +00001535 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001536
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001537 // Expand small (<= 128-bit) record types when we know that the stack layout
1538 // of those arguments will match the struct. This is important because the
1539 // LLVM backend isn't smart enough to remove byval, which inhibits many
1540 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001541 // Don't do this for the MCU if there are still free integer registers
1542 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001543 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1544 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001545 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001546 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001547 State.CC == llvm::CallingConv::X86_VectorCall ||
1548 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001549 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001550
Reid Kleckner661f35b2014-01-18 01:12:41 +00001551 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001552 }
1553
Chris Lattnerd774ae92010-08-26 20:05:13 +00001554 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001555 // On Darwin, some vectors are passed in memory, we handle this by passing
1556 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001557 if (IsDarwinVectorABI) {
1558 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001559 if ((Size == 8 || Size == 16 || Size == 32) ||
1560 (Size == 64 && VT->getNumElements() == 1))
1561 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1562 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001563 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001564
Chad Rosier651c1832013-03-25 21:00:27 +00001565 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1566 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001567
Chris Lattnerd774ae92010-08-26 20:05:13 +00001568 return ABIArgInfo::getDirect();
1569 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001570
1571
Chris Lattner458b2aa2010-07-29 02:16:43 +00001572 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1573 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001574
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001575 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001576
1577 if (Ty->isPromotableIntegerType()) {
1578 if (InReg)
1579 return ABIArgInfo::getExtendInReg();
1580 return ABIArgInfo::getExtend();
1581 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001582
Rafael Espindola703c47f2012-10-19 05:04:37 +00001583 if (InReg)
1584 return ABIArgInfo::getDirectInReg();
1585 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001586}
1587
Rafael Espindolaa6472962012-07-24 00:01:07 +00001588void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001589 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001590 if (IsMCUABI)
1591 State.FreeRegs = 3;
1592 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001593 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001594 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1595 State.FreeRegs = 2;
1596 State.FreeSSERegs = 6;
1597 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001598 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001599 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1600 State.FreeRegs = 5;
1601 State.FreeSSERegs = 8;
1602 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001603 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001604
Reid Kleckner677539d2014-07-10 01:58:55 +00001605 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001606 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001607 } else if (FI.getReturnInfo().isIndirect()) {
1608 // The C++ ABI is not aware of register usage, so we have to check if the
1609 // return value was sret and put it in a register ourselves if appropriate.
1610 if (State.FreeRegs) {
1611 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001612 if (!IsMCUABI)
1613 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001614 }
1615 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001616
Peter Collingbournef7706832014-12-12 23:41:25 +00001617 // The chain argument effectively gives us another free register.
1618 if (FI.isChainCall())
1619 ++State.FreeRegs;
1620
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001621 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001622 for (auto &I : FI.arguments()) {
1623 I.info = classifyArgumentType(I.type, State);
1624 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001625 }
1626
1627 // If we needed to use inalloca for any argument, do a second pass and rewrite
1628 // all the memory arguments to use inalloca.
1629 if (UsedInAlloca)
1630 rewriteWithInAlloca(FI);
1631}
1632
1633void
1634X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001635 CharUnits &StackOffset, ABIArgInfo &Info,
1636 QualType Type) const {
1637 // Arguments are always 4-byte-aligned.
1638 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1639
1640 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001641 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1642 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001643 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001644
John McCall7f416cc2015-09-08 08:05:57 +00001645 // Insert padding bytes to respect alignment.
1646 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001647 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001648 if (StackOffset != FieldEnd) {
1649 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001650 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001651 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001652 FrameFields.push_back(Ty);
1653 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001654}
1655
Reid Kleckner852361d2014-07-26 00:12:26 +00001656static bool isArgInAlloca(const ABIArgInfo &Info) {
1657 // Leave ignored and inreg arguments alone.
1658 switch (Info.getKind()) {
1659 case ABIArgInfo::InAlloca:
1660 return true;
1661 case ABIArgInfo::Indirect:
1662 assert(Info.getIndirectByVal());
1663 return true;
1664 case ABIArgInfo::Ignore:
1665 return false;
1666 case ABIArgInfo::Direct:
1667 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001668 if (Info.getInReg())
1669 return false;
1670 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001671 case ABIArgInfo::Expand:
1672 case ABIArgInfo::CoerceAndExpand:
1673 // These are aggregate types which are never passed in registers when
1674 // inalloca is involved.
1675 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001676 }
1677 llvm_unreachable("invalid enum");
1678}
1679
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001680void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1681 assert(IsWin32StructABI && "inalloca only supported on win32");
1682
1683 // Build a packed struct type for all of the arguments in memory.
1684 SmallVector<llvm::Type *, 6> FrameFields;
1685
John McCall7f416cc2015-09-08 08:05:57 +00001686 // The stack alignment is always 4.
1687 CharUnits StackAlign = CharUnits::fromQuantity(4);
1688
1689 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001690 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1691
1692 // Put 'this' into the struct before 'sret', if necessary.
1693 bool IsThisCall =
1694 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1695 ABIArgInfo &Ret = FI.getReturnInfo();
1696 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1697 isArgInAlloca(I->info)) {
1698 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1699 ++I;
1700 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001701
1702 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001703 if (Ret.isIndirect() && !Ret.getInReg()) {
1704 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1705 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001706 // On Windows, the hidden sret parameter is always returned in eax.
1707 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001708 }
1709
1710 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001711 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001712 ++I;
1713
1714 // Put arguments passed in memory into the struct.
1715 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001716 if (isArgInAlloca(I->info))
1717 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001718 }
1719
1720 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001721 /*isPacked=*/true),
1722 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001723}
1724
John McCall7f416cc2015-09-08 08:05:57 +00001725Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1726 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001727
John McCall7f416cc2015-09-08 08:05:57 +00001728 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001729
John McCall7f416cc2015-09-08 08:05:57 +00001730 // x86-32 changes the alignment of certain arguments on the stack.
1731 //
1732 // Just messing with TypeInfo like this works because we never pass
1733 // anything indirectly.
1734 TypeInfo.second = CharUnits::fromQuantity(
1735 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001736
John McCall7f416cc2015-09-08 08:05:57 +00001737 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1738 TypeInfo, CharUnits::fromQuantity(4),
1739 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001740}
1741
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001742bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1743 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1744 assert(Triple.getArch() == llvm::Triple::x86);
1745
1746 switch (Opts.getStructReturnConvention()) {
1747 case CodeGenOptions::SRCK_Default:
1748 break;
1749 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1750 return false;
1751 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1752 return true;
1753 }
1754
Michael Kupersteind749f232015-10-27 07:46:22 +00001755 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001756 return true;
1757
1758 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001759 case llvm::Triple::DragonFly:
1760 case llvm::Triple::FreeBSD:
1761 case llvm::Triple::OpenBSD:
1762 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001763 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001764 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001765 default:
1766 return false;
1767 }
1768}
1769
Eric Christopher162c91c2015-06-05 22:03:00 +00001770void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001771 llvm::GlobalValue *GV,
1772 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001773 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001774 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1775 // Get the LLVM function.
1776 llvm::Function *Fn = cast<llvm::Function>(GV);
1777
1778 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001779 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001780 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001781 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1782 llvm::AttributeSet::get(CGM.getLLVMContext(),
1783 llvm::AttributeSet::FunctionIndex,
1784 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001785 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001786 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1787 llvm::Function *Fn = cast<llvm::Function>(GV);
1788 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1789 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001790 }
1791}
1792
John McCallbeec5a02010-03-06 00:35:14 +00001793bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1794 CodeGen::CodeGenFunction &CGF,
1795 llvm::Value *Address) const {
1796 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001797
Chris Lattnerece04092012-02-07 00:39:47 +00001798 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001799
John McCallbeec5a02010-03-06 00:35:14 +00001800 // 0-7 are the eight integer registers; the order is different
1801 // on Darwin (for EH), but the range is the same.
1802 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001803 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001804
John McCallc8e01702013-04-16 22:48:15 +00001805 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001806 // 12-16 are st(0..4). Not sure why we stop at 4.
1807 // These have size 16, which is sizeof(long double) on
1808 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001809 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001810 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001811
John McCallbeec5a02010-03-06 00:35:14 +00001812 } else {
1813 // 9 is %eflags, which doesn't get a size on Darwin for some
1814 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001815 Builder.CreateAlignedStore(
1816 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1817 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001818
1819 // 11-16 are st(0..5). Not sure why we stop at 5.
1820 // These have size 12, which is sizeof(long double) on
1821 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001822 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001823 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1824 }
John McCallbeec5a02010-03-06 00:35:14 +00001825
1826 return false;
1827}
1828
Chris Lattner0cf24192010-06-28 20:05:43 +00001829//===----------------------------------------------------------------------===//
1830// X86-64 ABI Implementation
1831//===----------------------------------------------------------------------===//
1832
1833
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001834namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001835/// The AVX ABI level for X86 targets.
1836enum class X86AVXABILevel {
1837 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001838 AVX,
1839 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001840};
1841
1842/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1843static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1844 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001845 case X86AVXABILevel::AVX512:
1846 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001847 case X86AVXABILevel::AVX:
1848 return 256;
1849 case X86AVXABILevel::None:
1850 return 128;
1851 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001852 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001853}
1854
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001855/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001856class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001857 enum Class {
1858 Integer = 0,
1859 SSE,
1860 SSEUp,
1861 X87,
1862 X87Up,
1863 ComplexX87,
1864 NoClass,
1865 Memory
1866 };
1867
1868 /// merge - Implement the X86_64 ABI merging algorithm.
1869 ///
1870 /// Merge an accumulating classification \arg Accum with a field
1871 /// classification \arg Field.
1872 ///
1873 /// \param Accum - The accumulating classification. This should
1874 /// always be either NoClass or the result of a previous merge
1875 /// call. In addition, this should never be Memory (the caller
1876 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001877 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001878
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001879 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1880 ///
1881 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1882 /// final MEMORY or SSE classes when necessary.
1883 ///
1884 /// \param AggregateSize - The size of the current aggregate in
1885 /// the classification process.
1886 ///
1887 /// \param Lo - The classification for the parts of the type
1888 /// residing in the low word of the containing object.
1889 ///
1890 /// \param Hi - The classification for the parts of the type
1891 /// residing in the higher words of the containing object.
1892 ///
1893 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1894
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001895 /// classify - Determine the x86_64 register classes in which the
1896 /// given type T should be passed.
1897 ///
1898 /// \param Lo - The classification for the parts of the type
1899 /// residing in the low word of the containing object.
1900 ///
1901 /// \param Hi - The classification for the parts of the type
1902 /// residing in the high word of the containing object.
1903 ///
1904 /// \param OffsetBase - The bit offset of this type in the
1905 /// containing object. Some parameters are classified different
1906 /// depending on whether they straddle an eightbyte boundary.
1907 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001908 /// \param isNamedArg - Whether the argument in question is a "named"
1909 /// argument, as used in AMD64-ABI 3.5.7.
1910 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001911 /// If a word is unused its result will be NoClass; if a type should
1912 /// be passed in Memory then at least the classification of \arg Lo
1913 /// will be Memory.
1914 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001915 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001916 ///
1917 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1918 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001919 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1920 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001921
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001922 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001923 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1924 unsigned IROffset, QualType SourceTy,
1925 unsigned SourceOffset) const;
1926 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1927 unsigned IROffset, QualType SourceTy,
1928 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001929
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001930 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001931 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001932 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001933
1934 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001935 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001936 ///
1937 /// \param freeIntRegs - The number of free integer registers remaining
1938 /// available.
1939 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001940
Chris Lattner458b2aa2010-07-29 02:16:43 +00001941 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001942
Erich Keane757d3172016-11-02 18:29:35 +00001943 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
1944 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00001945 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001946
Erich Keane757d3172016-11-02 18:29:35 +00001947 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
1948 unsigned &NeededSSE) const;
1949
1950 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
1951 unsigned &NeededSSE) const;
1952
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001953 bool IsIllegalVectorType(QualType Ty) const;
1954
John McCalle0fda732011-04-21 01:20:55 +00001955 /// The 0.98 ABI revision clarified a lot of ambiguities,
1956 /// unfortunately in ways that were not always consistent with
1957 /// certain previous compilers. In particular, platforms which
1958 /// required strict binary compatibility with older versions of GCC
1959 /// may need to exempt themselves.
1960 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001961 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001962 }
1963
David Majnemere2ae2282016-03-04 05:26:16 +00001964 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1965 // compilers require us to classify it as INTEGER.
1966 bool classifyIntegerMMXAsSSE() const {
1967 const llvm::Triple &Triple = getTarget().getTriple();
1968 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1969 return false;
1970 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1971 return false;
1972 return true;
1973 }
1974
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001975 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001976 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1977 // 64-bit hardware.
1978 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001979
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001980public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001981 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00001982 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001983 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001984 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001985
John McCalla729c622012-02-17 03:33:10 +00001986 bool isPassedUsingAVXType(QualType type) const {
1987 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001988 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001989 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1990 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001991 if (info.isDirect()) {
1992 llvm::Type *ty = info.getCoerceToType();
1993 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1994 return (vectorTy->getBitWidth() > 128);
1995 }
1996 return false;
1997 }
1998
Craig Topper4f12f102014-03-12 06:41:41 +00001999 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002000
John McCall7f416cc2015-09-08 08:05:57 +00002001 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2002 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002003 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2004 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002005
2006 bool has64BitPointers() const {
2007 return Has64BitPointers;
2008 }
John McCall12f23522016-04-04 18:33:08 +00002009
2010 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2011 ArrayRef<llvm::Type*> scalars,
2012 bool asReturnValue) const override {
2013 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2014 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002015};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002016
Chris Lattner04dc9572010-08-31 16:44:54 +00002017/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002018class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002019public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002020 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002021 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002022 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002023
Craig Topper4f12f102014-03-12 06:41:41 +00002024 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002025
John McCall7f416cc2015-09-08 08:05:57 +00002026 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2027 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002028
2029 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2030 // FIXME: Assumes vectorcall is in use.
2031 return isX86VectorTypeForVectorCall(getContext(), Ty);
2032 }
2033
2034 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2035 uint64_t NumMembers) const override {
2036 // FIXME: Assumes vectorcall is in use.
2037 return isX86VectorCallAggregateSmallEnough(NumMembers);
2038 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002039
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002040 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2041 ArrayRef<llvm::Type *> scalars,
2042 bool asReturnValue) const override {
2043 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2044 }
2045
Reid Kleckner11a17192015-10-28 22:29:52 +00002046private:
2047 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
2048 bool IsReturnType) const;
2049
2050 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002051};
2052
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002053class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2054public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002055 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002056 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002057
John McCalla729c622012-02-17 03:33:10 +00002058 const X86_64ABIInfo &getABIInfo() const {
2059 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2060 }
2061
Craig Topper4f12f102014-03-12 06:41:41 +00002062 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002063 return 7;
2064 }
2065
2066 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002067 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002068 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002069
John McCall943fae92010-05-27 06:19:26 +00002070 // 0-15 are the 16 integer registers.
2071 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002072 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002073 return false;
2074 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002075
Jay Foad7c57be32011-07-11 09:56:20 +00002076 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002077 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002078 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002079 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2080 }
2081
John McCalla729c622012-02-17 03:33:10 +00002082 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002083 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002084 // The default CC on x86-64 sets %al to the number of SSA
2085 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002086 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002087 // that when AVX types are involved: the ABI explicitly states it is
2088 // undefined, and it doesn't work in practice because of how the ABI
2089 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002090 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002091 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002092 for (CallArgList::const_iterator
2093 it = args.begin(), ie = args.end(); it != ie; ++it) {
2094 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2095 HasAVXType = true;
2096 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002097 }
2098 }
John McCalla729c622012-02-17 03:33:10 +00002099
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002100 if (!HasAVXType)
2101 return true;
2102 }
John McCallcbc038a2011-09-21 08:08:30 +00002103
John McCalla729c622012-02-17 03:33:10 +00002104 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002105 }
2106
Craig Topper4f12f102014-03-12 06:41:41 +00002107 llvm::Constant *
2108 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002109 unsigned Sig;
2110 if (getABIInfo().has64BitPointers())
2111 Sig = (0xeb << 0) | // jmp rel8
2112 (0x0a << 8) | // .+0x0c
2113 ('F' << 16) |
2114 ('T' << 24);
2115 else
2116 Sig = (0xeb << 0) | // jmp rel8
2117 (0x06 << 8) | // .+0x08
2118 ('F' << 16) |
2119 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002120 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2121 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002122
2123 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2124 CodeGen::CodeGenModule &CGM) const override {
2125 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2126 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2127 llvm::Function *Fn = cast<llvm::Function>(GV);
2128 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2129 }
2130 }
2131 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002132};
2133
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002134class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2135public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002136 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2137 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002138
2139 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002140 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002141 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002142 // If the argument contains a space, enclose it in quotes.
2143 if (Lib.find(" ") != StringRef::npos)
2144 Opt += "\"" + Lib.str() + "\"";
2145 else
2146 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002147 }
2148};
2149
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002150static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002151 // If the argument does not end in .lib, automatically add the suffix.
2152 // If the argument contains a space, enclose it in quotes.
2153 // This matches the behavior of MSVC.
2154 bool Quote = (Lib.find(" ") != StringRef::npos);
2155 std::string ArgStr = Quote ? "\"" : "";
2156 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002157 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002158 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002159 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002160 return ArgStr;
2161}
2162
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002163class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2164public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002165 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002166 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2167 unsigned NumRegisterParameters)
2168 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002169 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002170
Eric Christopher162c91c2015-06-05 22:03:00 +00002171 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002172 CodeGen::CodeGenModule &CGM) const override;
2173
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002174 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002175 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002176 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002177 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002178 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002179
2180 void getDetectMismatchOption(llvm::StringRef Name,
2181 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002182 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002183 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002184 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002185};
2186
Hans Wennborg77dc2362015-01-20 19:45:50 +00002187static void addStackProbeSizeTargetAttribute(const Decl *D,
2188 llvm::GlobalValue *GV,
2189 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002190 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002191 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2192 llvm::Function *Fn = cast<llvm::Function>(GV);
2193
Eric Christopher7565e0d2015-05-29 23:09:49 +00002194 Fn->addFnAttr("stack-probe-size",
2195 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002196 }
2197 }
2198}
2199
Eric Christopher162c91c2015-06-05 22:03:00 +00002200void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002201 llvm::GlobalValue *GV,
2202 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002203 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002204
2205 addStackProbeSizeTargetAttribute(D, GV, CGM);
2206}
2207
Chris Lattner04dc9572010-08-31 16:44:54 +00002208class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2209public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002210 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2211 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002212 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002213
Eric Christopher162c91c2015-06-05 22:03:00 +00002214 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002215 CodeGen::CodeGenModule &CGM) const override;
2216
Craig Topper4f12f102014-03-12 06:41:41 +00002217 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002218 return 7;
2219 }
2220
2221 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002222 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002223 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002224
Chris Lattner04dc9572010-08-31 16:44:54 +00002225 // 0-15 are the 16 integer registers.
2226 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002227 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002228 return false;
2229 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002230
2231 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002232 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002233 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002234 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002235 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002236
2237 void getDetectMismatchOption(llvm::StringRef Name,
2238 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002239 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002240 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002241 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002242};
2243
Eric Christopher162c91c2015-06-05 22:03:00 +00002244void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002245 llvm::GlobalValue *GV,
2246 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002247 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002248
Alexey Bataevd51e9932016-01-15 04:06:31 +00002249 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2250 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2251 llvm::Function *Fn = cast<llvm::Function>(GV);
2252 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2253 }
2254 }
2255
Hans Wennborg77dc2362015-01-20 19:45:50 +00002256 addStackProbeSizeTargetAttribute(D, GV, CGM);
2257}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002258}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002259
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002260void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2261 Class &Hi) const {
2262 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2263 //
2264 // (a) If one of the classes is Memory, the whole argument is passed in
2265 // memory.
2266 //
2267 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2268 // memory.
2269 //
2270 // (c) If the size of the aggregate exceeds two eightbytes and the first
2271 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2272 // argument is passed in memory. NOTE: This is necessary to keep the
2273 // ABI working for processors that don't support the __m256 type.
2274 //
2275 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2276 //
2277 // Some of these are enforced by the merging logic. Others can arise
2278 // only with unions; for example:
2279 // union { _Complex double; unsigned; }
2280 //
2281 // Note that clauses (b) and (c) were added in 0.98.
2282 //
2283 if (Hi == Memory)
2284 Lo = Memory;
2285 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2286 Lo = Memory;
2287 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2288 Lo = Memory;
2289 if (Hi == SSEUp && Lo != SSE)
2290 Hi = SSE;
2291}
2292
Chris Lattnerd776fb12010-06-28 21:43:59 +00002293X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002294 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2295 // classified recursively so that always two fields are
2296 // considered. The resulting class is calculated according to
2297 // the classes of the fields in the eightbyte:
2298 //
2299 // (a) If both classes are equal, this is the resulting class.
2300 //
2301 // (b) If one of the classes is NO_CLASS, the resulting class is
2302 // the other class.
2303 //
2304 // (c) If one of the classes is MEMORY, the result is the MEMORY
2305 // class.
2306 //
2307 // (d) If one of the classes is INTEGER, the result is the
2308 // INTEGER.
2309 //
2310 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2311 // MEMORY is used as class.
2312 //
2313 // (f) Otherwise class SSE is used.
2314
2315 // Accum should never be memory (we should have returned) or
2316 // ComplexX87 (because this cannot be passed in a structure).
2317 assert((Accum != Memory && Accum != ComplexX87) &&
2318 "Invalid accumulated classification during merge.");
2319 if (Accum == Field || Field == NoClass)
2320 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002321 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002322 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002323 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002324 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002325 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002326 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002327 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2328 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002329 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002330 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002331}
2332
Chris Lattner5c740f12010-06-30 19:14:05 +00002333void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002334 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002335 // FIXME: This code can be simplified by introducing a simple value class for
2336 // Class pairs with appropriate constructor methods for the various
2337 // situations.
2338
2339 // FIXME: Some of the split computations are wrong; unaligned vectors
2340 // shouldn't be passed in registers for example, so there is no chance they
2341 // can straddle an eightbyte. Verify & simplify.
2342
2343 Lo = Hi = NoClass;
2344
2345 Class &Current = OffsetBase < 64 ? Lo : Hi;
2346 Current = Memory;
2347
John McCall9dd450b2009-09-21 23:43:11 +00002348 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002349 BuiltinType::Kind k = BT->getKind();
2350
2351 if (k == BuiltinType::Void) {
2352 Current = NoClass;
2353 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2354 Lo = Integer;
2355 Hi = Integer;
2356 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2357 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002358 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002359 Current = SSE;
2360 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002361 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2362 if (LDF == &llvm::APFloat::IEEEquad) {
2363 Lo = SSE;
2364 Hi = SSEUp;
2365 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2366 Lo = X87;
2367 Hi = X87Up;
2368 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2369 Current = SSE;
2370 } else
2371 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002372 }
2373 // FIXME: _Decimal32 and _Decimal64 are SSE.
2374 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002375 return;
2376 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002377
Chris Lattnerd776fb12010-06-28 21:43:59 +00002378 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002379 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002380 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002381 return;
2382 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002383
Chris Lattnerd776fb12010-06-28 21:43:59 +00002384 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002385 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002386 return;
2387 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002388
Chris Lattnerd776fb12010-06-28 21:43:59 +00002389 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002390 if (Ty->isMemberFunctionPointerType()) {
2391 if (Has64BitPointers) {
2392 // If Has64BitPointers, this is an {i64, i64}, so classify both
2393 // Lo and Hi now.
2394 Lo = Hi = Integer;
2395 } else {
2396 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2397 // straddles an eightbyte boundary, Hi should be classified as well.
2398 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2399 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2400 if (EB_FuncPtr != EB_ThisAdj) {
2401 Lo = Hi = Integer;
2402 } else {
2403 Current = Integer;
2404 }
2405 }
2406 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002407 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002408 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002409 return;
2410 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002411
Chris Lattnerd776fb12010-06-28 21:43:59 +00002412 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002413 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002414 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2415 // gcc passes the following as integer:
2416 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2417 // 2 bytes - <2 x char>, <1 x short>
2418 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002419 Current = Integer;
2420
2421 // If this type crosses an eightbyte boundary, it should be
2422 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002423 uint64_t EB_Lo = (OffsetBase) / 64;
2424 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2425 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002426 Hi = Lo;
2427 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002428 QualType ElementType = VT->getElementType();
2429
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002430 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002431 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002432 return;
2433
David Majnemere2ae2282016-03-04 05:26:16 +00002434 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2435 // pass them as integer. For platforms where clang is the de facto
2436 // platform compiler, we must continue to use integer.
2437 if (!classifyIntegerMMXAsSSE() &&
2438 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2439 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2440 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2441 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002442 Current = Integer;
2443 else
2444 Current = SSE;
2445
2446 // If this type crosses an eightbyte boundary, it should be
2447 // split.
2448 if (OffsetBase && OffsetBase != 64)
2449 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002450 } else if (Size == 128 ||
2451 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002452 // Arguments of 256-bits are split into four eightbyte chunks. The
2453 // least significant one belongs to class SSE and all the others to class
2454 // SSEUP. The original Lo and Hi design considers that types can't be
2455 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2456 // This design isn't correct for 256-bits, but since there're no cases
2457 // where the upper parts would need to be inspected, avoid adding
2458 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002459 //
2460 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2461 // registers if they are "named", i.e. not part of the "..." of a
2462 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002463 //
2464 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2465 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002466 Lo = SSE;
2467 Hi = SSEUp;
2468 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002469 return;
2470 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002471
Chris Lattnerd776fb12010-06-28 21:43:59 +00002472 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002473 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002474
Chris Lattner2b037972010-07-29 02:01:43 +00002475 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002476 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002477 if (Size <= 64)
2478 Current = Integer;
2479 else if (Size <= 128)
2480 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002481 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002482 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002483 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002484 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002485 } else if (ET == getContext().LongDoubleTy) {
2486 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2487 if (LDF == &llvm::APFloat::IEEEquad)
2488 Current = Memory;
2489 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2490 Current = ComplexX87;
2491 else if (LDF == &llvm::APFloat::IEEEdouble)
2492 Lo = Hi = SSE;
2493 else
2494 llvm_unreachable("unexpected long double representation!");
2495 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002496
2497 // If this complex type crosses an eightbyte boundary then it
2498 // should be split.
2499 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002500 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002501 if (Hi == NoClass && EB_Real != EB_Imag)
2502 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002503
Chris Lattnerd776fb12010-06-28 21:43:59 +00002504 return;
2505 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002506
Chris Lattner2b037972010-07-29 02:01:43 +00002507 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002508 // Arrays are treated like structures.
2509
Chris Lattner2b037972010-07-29 02:01:43 +00002510 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002511
2512 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002513 // than eight eightbytes, ..., it has class MEMORY.
2514 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002515 return;
2516
2517 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2518 // fields, it has class MEMORY.
2519 //
2520 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002521 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002522 return;
2523
2524 // Otherwise implement simplified merge. We could be smarter about
2525 // this, but it isn't worth it and would be harder to verify.
2526 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002527 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002528 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002529
2530 // The only case a 256-bit wide vector could be used is when the array
2531 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2532 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002533 //
2534 if (Size > 128 &&
2535 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002536 return;
2537
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002538 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2539 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002540 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002541 Lo = merge(Lo, FieldLo);
2542 Hi = merge(Hi, FieldHi);
2543 if (Lo == Memory || Hi == Memory)
2544 break;
2545 }
2546
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002547 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002548 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002549 return;
2550 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002551
Chris Lattnerd776fb12010-06-28 21:43:59 +00002552 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002553 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002554
2555 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002556 // than eight eightbytes, ..., it has class MEMORY.
2557 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002558 return;
2559
Anders Carlsson20759ad2009-09-16 15:53:40 +00002560 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2561 // copy constructor or a non-trivial destructor, it is passed by invisible
2562 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002563 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002564 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002565
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002566 const RecordDecl *RD = RT->getDecl();
2567
2568 // Assume variable sized types are passed in memory.
2569 if (RD->hasFlexibleArrayMember())
2570 return;
2571
Chris Lattner2b037972010-07-29 02:01:43 +00002572 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002573
2574 // Reset Lo class, this will be recomputed.
2575 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002576
2577 // If this is a C++ record, classify the bases first.
2578 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002579 for (const auto &I : CXXRD->bases()) {
2580 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002581 "Unexpected base class!");
2582 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002583 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002584
2585 // Classify this field.
2586 //
2587 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2588 // single eightbyte, each is classified separately. Each eightbyte gets
2589 // initialized to class NO_CLASS.
2590 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002591 uint64_t Offset =
2592 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002593 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002594 Lo = merge(Lo, FieldLo);
2595 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002596 if (Lo == Memory || Hi == Memory) {
2597 postMerge(Size, Lo, Hi);
2598 return;
2599 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002600 }
2601 }
2602
2603 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002604 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002605 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002606 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002607 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2608 bool BitField = i->isBitField();
2609
David Majnemerb439dfe2016-08-15 07:20:40 +00002610 // Ignore padding bit-fields.
2611 if (BitField && i->isUnnamedBitfield())
2612 continue;
2613
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002614 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2615 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002617 // The only case a 256-bit wide vector could be used is when the struct
2618 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2619 // to work for sizes wider than 128, early check and fallback to memory.
2620 //
David Majnemerb229cb02016-08-15 06:39:18 +00002621 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2622 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002623 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002624 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002625 return;
2626 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002627 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002628 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002629 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002630 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002631 return;
2632 }
2633
2634 // Classify this field.
2635 //
2636 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2637 // exceeds a single eightbyte, each is classified
2638 // separately. Each eightbyte gets initialized to class
2639 // NO_CLASS.
2640 Class FieldLo, FieldHi;
2641
2642 // Bit-fields require special handling, they do not force the
2643 // structure to be passed in memory even if unaligned, and
2644 // therefore they can straddle an eightbyte.
2645 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002646 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002647 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002648 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002649
2650 uint64_t EB_Lo = Offset / 64;
2651 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002652
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002653 if (EB_Lo) {
2654 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2655 FieldLo = NoClass;
2656 FieldHi = Integer;
2657 } else {
2658 FieldLo = Integer;
2659 FieldHi = EB_Hi ? Integer : NoClass;
2660 }
2661 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002662 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002663 Lo = merge(Lo, FieldLo);
2664 Hi = merge(Hi, FieldHi);
2665 if (Lo == Memory || Hi == Memory)
2666 break;
2667 }
2668
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002669 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002670 }
2671}
2672
Chris Lattner22a931e2010-06-29 06:01:59 +00002673ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002674 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2675 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002676 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002677 // Treat an enum type as its underlying type.
2678 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2679 Ty = EnumTy->getDecl()->getIntegerType();
2680
2681 return (Ty->isPromotableIntegerType() ?
2682 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2683 }
2684
John McCall7f416cc2015-09-08 08:05:57 +00002685 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002686}
2687
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002688bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2689 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2690 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002691 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002692 if (Size <= 64 || Size > LargestVector)
2693 return true;
2694 }
2695
2696 return false;
2697}
2698
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002699ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2700 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002701 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2702 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002703 //
2704 // This assumption is optimistic, as there could be free registers available
2705 // when we need to pass this argument in memory, and LLVM could try to pass
2706 // the argument in the free register. This does not seem to happen currently,
2707 // but this code would be much safer if we could mark the argument with
2708 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002709 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002710 // Treat an enum type as its underlying type.
2711 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2712 Ty = EnumTy->getDecl()->getIntegerType();
2713
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002714 return (Ty->isPromotableIntegerType() ?
2715 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002716 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002717
Mark Lacey3825e832013-10-06 01:33:34 +00002718 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002719 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002720
Chris Lattner44c2b902011-05-22 23:21:23 +00002721 // Compute the byval alignment. We specify the alignment of the byval in all
2722 // cases so that the mid-level optimizer knows the alignment of the byval.
2723 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002724
2725 // Attempt to avoid passing indirect results using byval when possible. This
2726 // is important for good codegen.
2727 //
2728 // We do this by coercing the value into a scalar type which the backend can
2729 // handle naturally (i.e., without using byval).
2730 //
2731 // For simplicity, we currently only do this when we have exhausted all of the
2732 // free integer registers. Doing this when there are free integer registers
2733 // would require more care, as we would have to ensure that the coerced value
2734 // did not claim the unused register. That would require either reording the
2735 // arguments to the function (so that any subsequent inreg values came first),
2736 // or only doing this optimization when there were no following arguments that
2737 // might be inreg.
2738 //
2739 // We currently expect it to be rare (particularly in well written code) for
2740 // arguments to be passed on the stack when there are still free integer
2741 // registers available (this would typically imply large structs being passed
2742 // by value), so this seems like a fair tradeoff for now.
2743 //
2744 // We can revisit this if the backend grows support for 'onstack' parameter
2745 // attributes. See PR12193.
2746 if (freeIntRegs == 0) {
2747 uint64_t Size = getContext().getTypeSize(Ty);
2748
2749 // If this type fits in an eightbyte, coerce it into the matching integral
2750 // type, which will end up on the stack (with alignment 8).
2751 if (Align == 8 && Size <= 64)
2752 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2753 Size));
2754 }
2755
John McCall7f416cc2015-09-08 08:05:57 +00002756 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002757}
2758
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002759/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2760/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002761llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002762 // Wrapper structs/arrays that only contain vectors are passed just like
2763 // vectors; strip them off if present.
2764 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2765 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002766
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002767 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002768 if (isa<llvm::VectorType>(IRType) ||
2769 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002770 return IRType;
2771
2772 // We couldn't find the preferred IR vector type for 'Ty'.
2773 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002774 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002775
2776 // Return a LLVM IR vector type based on the size of 'Ty'.
2777 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2778 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002779}
2780
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002781/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2782/// is known to either be off the end of the specified type or being in
2783/// alignment padding. The user type specified is known to be at most 128 bits
2784/// in size, and have passed through X86_64ABIInfo::classify with a successful
2785/// classification that put one of the two halves in the INTEGER class.
2786///
2787/// It is conservatively correct to return false.
2788static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2789 unsigned EndBit, ASTContext &Context) {
2790 // If the bytes being queried are off the end of the type, there is no user
2791 // data hiding here. This handles analysis of builtins, vectors and other
2792 // types that don't contain interesting padding.
2793 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2794 if (TySize <= StartBit)
2795 return true;
2796
Chris Lattner98076a22010-07-29 07:43:55 +00002797 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2798 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2799 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2800
2801 // Check each element to see if the element overlaps with the queried range.
2802 for (unsigned i = 0; i != NumElts; ++i) {
2803 // If the element is after the span we care about, then we're done..
2804 unsigned EltOffset = i*EltSize;
2805 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002806
Chris Lattner98076a22010-07-29 07:43:55 +00002807 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2808 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2809 EndBit-EltOffset, Context))
2810 return false;
2811 }
2812 // If it overlaps no elements, then it is safe to process as padding.
2813 return true;
2814 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002815
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002816 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2817 const RecordDecl *RD = RT->getDecl();
2818 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002819
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002820 // If this is a C++ record, check the bases first.
2821 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002822 for (const auto &I : CXXRD->bases()) {
2823 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002824 "Unexpected base class!");
2825 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002826 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002827
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002828 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002829 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002830 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002831
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002832 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002833 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002834 EndBit-BaseOffset, Context))
2835 return false;
2836 }
2837 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002838
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002839 // Verify that no field has data that overlaps the region of interest. Yes
2840 // this could be sped up a lot by being smarter about queried fields,
2841 // however we're only looking at structs up to 16 bytes, so we don't care
2842 // much.
2843 unsigned idx = 0;
2844 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2845 i != e; ++i, ++idx) {
2846 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002847
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002848 // If we found a field after the region we care about, then we're done.
2849 if (FieldOffset >= EndBit) break;
2850
2851 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2852 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2853 Context))
2854 return false;
2855 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002856
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002857 // If nothing in this record overlapped the area of interest, then we're
2858 // clean.
2859 return true;
2860 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002861
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002862 return false;
2863}
2864
Chris Lattnere556a712010-07-29 18:39:32 +00002865/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2866/// float member at the specified offset. For example, {int,{float}} has a
2867/// float at offset 4. It is conservatively correct for this routine to return
2868/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002869static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002870 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002871 // Base case if we find a float.
2872 if (IROffset == 0 && IRType->isFloatTy())
2873 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002874
Chris Lattnere556a712010-07-29 18:39:32 +00002875 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002876 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002877 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2878 unsigned Elt = SL->getElementContainingOffset(IROffset);
2879 IROffset -= SL->getElementOffset(Elt);
2880 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2881 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002882
Chris Lattnere556a712010-07-29 18:39:32 +00002883 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002884 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2885 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002886 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2887 IROffset -= IROffset/EltSize*EltSize;
2888 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2889 }
2890
2891 return false;
2892}
2893
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002894
2895/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2896/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002897llvm::Type *X86_64ABIInfo::
2898GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002899 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002900 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002901 // pass as float if the last 4 bytes is just padding. This happens for
2902 // structs that contain 3 floats.
2903 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2904 SourceOffset*8+64, getContext()))
2905 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002906
Chris Lattnere556a712010-07-29 18:39:32 +00002907 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2908 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2909 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002910 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2911 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002912 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002913
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002914 return llvm::Type::getDoubleTy(getVMContext());
2915}
2916
2917
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002918/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2919/// an 8-byte GPR. This means that we either have a scalar or we are talking
2920/// about the high or low part of an up-to-16-byte struct. This routine picks
2921/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002922/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2923/// etc).
2924///
2925/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2926/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2927/// the 8-byte value references. PrefType may be null.
2928///
Alp Toker9907f082014-07-09 14:06:35 +00002929/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002930/// an offset into this that we're processing (which is always either 0 or 8).
2931///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002932llvm::Type *X86_64ABIInfo::
2933GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002934 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002935 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2936 // returning an 8-byte unit starting with it. See if we can safely use it.
2937 if (IROffset == 0) {
2938 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002939 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2940 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002941 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002942
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002943 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2944 // goodness in the source type is just tail padding. This is allowed to
2945 // kick in for struct {double,int} on the int, but not on
2946 // struct{double,int,int} because we wouldn't return the second int. We
2947 // have to do this analysis on the source type because we can't depend on
2948 // unions being lowered a specific way etc.
2949 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002950 IRType->isIntegerTy(32) ||
2951 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2952 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2953 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002954
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002955 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2956 SourceOffset*8+64, getContext()))
2957 return IRType;
2958 }
2959 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002960
Chris Lattner2192fe52011-07-18 04:24:23 +00002961 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002962 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002963 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002964 if (IROffset < SL->getSizeInBytes()) {
2965 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2966 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002967
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002968 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2969 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002970 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002971 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002972
Chris Lattner2192fe52011-07-18 04:24:23 +00002973 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002974 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002975 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002976 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002977 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2978 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002979 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002980
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002981 // Okay, we don't have any better idea of what to pass, so we pass this in an
2982 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002983 unsigned TySizeInBytes =
2984 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002985
Chris Lattner3f763422010-07-29 17:34:39 +00002986 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002987
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002988 // It is always safe to classify this as an integer type up to i64 that
2989 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002990 return llvm::IntegerType::get(getVMContext(),
2991 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002992}
2993
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002994
2995/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2996/// be used as elements of a two register pair to pass or return, return a
2997/// first class aggregate to represent them. For example, if the low part of
2998/// a by-value argument should be passed as i32* and the high part as float,
2999/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003000static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003001GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003002 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003003 // In order to correctly satisfy the ABI, we need to the high part to start
3004 // at offset 8. If the high and low parts we inferred are both 4-byte types
3005 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3006 // the second element at offset 8. Check for this:
3007 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3008 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003009 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003010 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003011
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003012 // To handle this, we have to increase the size of the low part so that the
3013 // second element will start at an 8 byte offset. We can't increase the size
3014 // of the second element because it might make us access off the end of the
3015 // struct.
3016 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003017 // There are usually two sorts of types the ABI generation code can produce
3018 // for the low part of a pair that aren't 8 bytes in size: float or
3019 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3020 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003021 // Promote these to a larger type.
3022 if (Lo->isFloatTy())
3023 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3024 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003025 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3026 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003027 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3028 }
3029 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003030
Reid Kleckneree7cf842014-12-01 22:02:27 +00003031 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003032
3033
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003034 // Verify that the second element is at an 8-byte offset.
3035 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3036 "Invalid x86-64 argument pair!");
3037 return Result;
3038}
3039
Chris Lattner31faff52010-07-28 23:06:14 +00003040ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003041classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003042 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3043 // classification algorithm.
3044 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003045 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003046
3047 // Check some invariants.
3048 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003049 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3050
Craig Topper8a13c412014-05-21 05:09:00 +00003051 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003052 switch (Lo) {
3053 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003054 if (Hi == NoClass)
3055 return ABIArgInfo::getIgnore();
3056 // If the low part is just padding, it takes no register, leave ResType
3057 // null.
3058 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3059 "Unknown missing lo part");
3060 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003061
3062 case SSEUp:
3063 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003064 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003065
3066 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3067 // hidden argument.
3068 case Memory:
3069 return getIndirectReturnResult(RetTy);
3070
3071 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3072 // available register of the sequence %rax, %rdx is used.
3073 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003074 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003075
Chris Lattner1f3a0632010-07-29 21:42:50 +00003076 // If we have a sign or zero extended integer, make sure to return Extend
3077 // so that the parameter gets the right LLVM IR attributes.
3078 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3079 // Treat an enum type as its underlying type.
3080 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3081 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003082
Chris Lattner1f3a0632010-07-29 21:42:50 +00003083 if (RetTy->isIntegralOrEnumerationType() &&
3084 RetTy->isPromotableIntegerType())
3085 return ABIArgInfo::getExtend();
3086 }
Chris Lattner31faff52010-07-28 23:06:14 +00003087 break;
3088
3089 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3090 // available SSE register of the sequence %xmm0, %xmm1 is used.
3091 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003092 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003093 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003094
3095 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3096 // returned on the X87 stack in %st0 as 80-bit x87 number.
3097 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003098 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003099 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003100
3101 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3102 // part of the value is returned in %st0 and the imaginary part in
3103 // %st1.
3104 case ComplexX87:
3105 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003106 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003107 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003108 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003109 break;
3110 }
3111
Craig Topper8a13c412014-05-21 05:09:00 +00003112 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003113 switch (Hi) {
3114 // Memory was handled previously and X87 should
3115 // never occur as a hi class.
3116 case Memory:
3117 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003118 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003119
3120 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003121 case NoClass:
3122 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003123
Chris Lattner52b3c132010-09-01 00:20:33 +00003124 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003125 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003126 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3127 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003128 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003129 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003130 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003131 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3132 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003133 break;
3134
3135 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003136 // is passed in the next available eightbyte chunk if the last used
3137 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003138 //
Chris Lattner57540c52011-04-15 05:22:18 +00003139 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003140 case SSEUp:
3141 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003142 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003143 break;
3144
3145 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3146 // returned together with the previous X87 value in %st0.
3147 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003148 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003149 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003150 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003151 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003152 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003153 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003154 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3155 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003156 }
Chris Lattner31faff52010-07-28 23:06:14 +00003157 break;
3158 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003159
Chris Lattner52b3c132010-09-01 00:20:33 +00003160 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003161 // known to pass in the high eightbyte of the result. We do this by forming a
3162 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003163 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003164 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003165
Chris Lattner1f3a0632010-07-29 21:42:50 +00003166 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003167}
3168
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003169ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003170 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3171 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003172 const
3173{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003174 Ty = useFirstFieldIfTransparentUnion(Ty);
3175
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003176 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003177 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003178
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003179 // Check some invariants.
3180 // FIXME: Enforce these by construction.
3181 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003182 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3183
3184 neededInt = 0;
3185 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003186 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003187 switch (Lo) {
3188 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003189 if (Hi == NoClass)
3190 return ABIArgInfo::getIgnore();
3191 // If the low part is just padding, it takes no register, leave ResType
3192 // null.
3193 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3194 "Unknown missing lo part");
3195 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003196
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003197 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3198 // on the stack.
3199 case Memory:
3200
3201 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3202 // COMPLEX_X87, it is passed in memory.
3203 case X87:
3204 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003205 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003206 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003207 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003208
3209 case SSEUp:
3210 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003211 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003212
3213 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3214 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3215 // and %r9 is used.
3216 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003217 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003218
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003219 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003220 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003221
3222 // If we have a sign or zero extended integer, make sure to return Extend
3223 // so that the parameter gets the right LLVM IR attributes.
3224 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3225 // Treat an enum type as its underlying type.
3226 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3227 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003228
Chris Lattner1f3a0632010-07-29 21:42:50 +00003229 if (Ty->isIntegralOrEnumerationType() &&
3230 Ty->isPromotableIntegerType())
3231 return ABIArgInfo::getExtend();
3232 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003233
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003234 break;
3235
3236 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3237 // available SSE register is used, the registers are taken in the
3238 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003239 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003240 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003241 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003242 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003243 break;
3244 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003245 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003246
Craig Topper8a13c412014-05-21 05:09:00 +00003247 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003248 switch (Hi) {
3249 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003250 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003251 // which is passed in memory.
3252 case Memory:
3253 case X87:
3254 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003255 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003256
3257 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003258
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003259 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003260 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003261 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003262 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003263
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003264 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3265 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003266 break;
3267
3268 // X87Up generally doesn't occur here (long double is passed in
3269 // memory), except in situations involving unions.
3270 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003271 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003272 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003273
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003274 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3275 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003276
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003277 ++neededSSE;
3278 break;
3279
3280 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3281 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003282 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003283 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003284 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003285 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003286 break;
3287 }
3288
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003289 // If a high part was specified, merge it together with the low part. It is
3290 // known to pass in the high eightbyte of the result. We do this by forming a
3291 // first class struct aggregate with the high and low part: {low, high}
3292 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003293 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003294
Chris Lattner1f3a0632010-07-29 21:42:50 +00003295 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003296}
3297
Erich Keane757d3172016-11-02 18:29:35 +00003298ABIArgInfo
3299X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3300 unsigned &NeededSSE) const {
3301 auto RT = Ty->getAs<RecordType>();
3302 assert(RT && "classifyRegCallStructType only valid with struct types");
3303
3304 if (RT->getDecl()->hasFlexibleArrayMember())
3305 return getIndirectReturnResult(Ty);
3306
3307 // Sum up bases
3308 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3309 if (CXXRD->isDynamicClass()) {
3310 NeededInt = NeededSSE = 0;
3311 return getIndirectReturnResult(Ty);
3312 }
3313
3314 for (const auto &I : CXXRD->bases())
3315 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3316 .isIndirect()) {
3317 NeededInt = NeededSSE = 0;
3318 return getIndirectReturnResult(Ty);
3319 }
3320 }
3321
3322 // Sum up members
3323 for (const auto *FD : RT->getDecl()->fields()) {
3324 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3325 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3326 .isIndirect()) {
3327 NeededInt = NeededSSE = 0;
3328 return getIndirectReturnResult(Ty);
3329 }
3330 } else {
3331 unsigned LocalNeededInt, LocalNeededSSE;
3332 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3333 LocalNeededSSE, true)
3334 .isIndirect()) {
3335 NeededInt = NeededSSE = 0;
3336 return getIndirectReturnResult(Ty);
3337 }
3338 NeededInt += LocalNeededInt;
3339 NeededSSE += LocalNeededSSE;
3340 }
3341 }
3342
3343 return ABIArgInfo::getDirect();
3344}
3345
3346ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3347 unsigned &NeededInt,
3348 unsigned &NeededSSE) const {
3349
3350 NeededInt = 0;
3351 NeededSSE = 0;
3352
3353 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3354}
3355
Chris Lattner22326a12010-07-29 02:31:05 +00003356void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003357
Erich Keane757d3172016-11-02 18:29:35 +00003358 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003359
3360 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003361 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3362 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3363 unsigned NeededInt, NeededSSE;
3364
3365 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3366 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3367 FI.getReturnInfo() =
3368 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3369 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3370 FreeIntRegs -= NeededInt;
3371 FreeSSERegs -= NeededSSE;
3372 } else {
3373 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3374 }
3375 } else if (!getCXXABI().classifyReturnType(FI))
3376 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003377
3378 // If the return value is indirect, then the hidden argument is consuming one
3379 // integer register.
3380 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003381 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003382
Peter Collingbournef7706832014-12-12 23:41:25 +00003383 // The chain argument effectively gives us another free register.
3384 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003385 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003386
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003387 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003388 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3389 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003390 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003391 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003392 it != ie; ++it, ++ArgNo) {
3393 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003394
Erich Keane757d3172016-11-02 18:29:35 +00003395 if (IsRegCall && it->type->isStructureOrClassType())
3396 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3397 else
3398 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3399 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003400
3401 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3402 // eightbyte of an argument, the whole argument is passed on the
3403 // stack. If registers have already been assigned for some
3404 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003405 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3406 FreeIntRegs -= NeededInt;
3407 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003408 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003409 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003410 }
3411 }
3412}
3413
John McCall7f416cc2015-09-08 08:05:57 +00003414static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3415 Address VAListAddr, QualType Ty) {
3416 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3417 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003418 llvm::Value *overflow_arg_area =
3419 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3420
3421 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3422 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003423 // It isn't stated explicitly in the standard, but in practice we use
3424 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003425 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3426 if (Align > CharUnits::fromQuantity(8)) {
3427 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3428 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003429 }
3430
3431 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003432 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003433 llvm::Value *Res =
3434 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003435 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003436
3437 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3438 // l->overflow_arg_area + sizeof(type).
3439 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3440 // an 8 byte boundary.
3441
3442 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003443 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003444 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003445 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3446 "overflow_arg_area.next");
3447 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3448
3449 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003450 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003451}
3452
John McCall7f416cc2015-09-08 08:05:57 +00003453Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3454 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003455 // Assume that va_list type is correct; should be pointer to LLVM type:
3456 // struct {
3457 // i32 gp_offset;
3458 // i32 fp_offset;
3459 // i8* overflow_arg_area;
3460 // i8* reg_save_area;
3461 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003462 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003463
John McCall7f416cc2015-09-08 08:05:57 +00003464 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003465 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003466 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003467
3468 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3469 // in the registers. If not go to step 7.
3470 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003471 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003472
3473 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3474 // general purpose registers needed to pass type and num_fp to hold
3475 // the number of floating point registers needed.
3476
3477 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3478 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3479 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3480 //
3481 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3482 // register save space).
3483
Craig Topper8a13c412014-05-21 05:09:00 +00003484 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003485 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3486 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003487 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003488 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003489 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3490 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003491 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003492 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3493 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003494 }
3495
3496 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003497 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003498 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3499 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003500 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3501 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003502 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3503 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003504 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3505 }
3506
3507 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3508 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3509 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3510 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3511
3512 // Emit code to load the value if it was passed in registers.
3513
3514 CGF.EmitBlock(InRegBlock);
3515
3516 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3517 // an offset of l->gp_offset and/or l->fp_offset. This may require
3518 // copying to a temporary location in case the parameter is passed
3519 // in different register classes or requires an alignment greater
3520 // than 8 for general purpose registers and 16 for XMM registers.
3521 //
3522 // FIXME: This really results in shameful code when we end up needing to
3523 // collect arguments from different places; often what should result in a
3524 // simple assembling of a structure from scattered addresses has many more
3525 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003526 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003527 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3528 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3529 "reg_save_area");
3530
3531 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003532 if (neededInt && neededSSE) {
3533 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003534 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003535 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003536 Address Tmp = CGF.CreateMemTemp(Ty);
3537 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003538 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003539 llvm::Type *TyLo = ST->getElementType(0);
3540 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003541 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003542 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003543 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3544 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003545 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3546 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003547 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3548 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003549
John McCall7f416cc2015-09-08 08:05:57 +00003550 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003551 // FIXME: Our choice of alignment here and below is probably pessimistic.
3552 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3553 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3554 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003555 CGF.Builder.CreateStore(V,
3556 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3557
3558 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003559 V = CGF.Builder.CreateAlignedLoad(
3560 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3561 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003562 CharUnits Offset = CharUnits::fromQuantity(
3563 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3564 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3565
3566 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003567 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003568 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3569 CharUnits::fromQuantity(8));
3570 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003571
3572 // Copy to a temporary if necessary to ensure the appropriate alignment.
3573 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003574 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003575 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003576 CharUnits TyAlign = SizeAlign.second;
3577
3578 // Copy into a temporary if the type is more aligned than the
3579 // register save area.
3580 if (TyAlign.getQuantity() > 8) {
3581 Address Tmp = CGF.CreateMemTemp(Ty);
3582 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003583 RegAddr = Tmp;
3584 }
John McCall7f416cc2015-09-08 08:05:57 +00003585
Chris Lattner0cf24192010-06-28 20:05:43 +00003586 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003587 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3588 CharUnits::fromQuantity(16));
3589 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003590 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003591 assert(neededSSE == 2 && "Invalid number of needed registers!");
3592 // SSE registers are spaced 16 bytes apart in the register save
3593 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003594 // The ABI isn't explicit about this, but it seems reasonable
3595 // to assume that the slots are 16-byte aligned, since the stack is
3596 // naturally 16-byte aligned and the prologue is expected to store
3597 // all the SSE registers to the RSA.
3598 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3599 CharUnits::fromQuantity(16));
3600 Address RegAddrHi =
3601 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3602 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003603 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003604 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003605 llvm::Value *V;
3606 Address Tmp = CGF.CreateMemTemp(Ty);
3607 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3608 V = CGF.Builder.CreateLoad(
3609 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3610 CGF.Builder.CreateStore(V,
3611 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3612 V = CGF.Builder.CreateLoad(
3613 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3614 CGF.Builder.CreateStore(V,
3615 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3616
3617 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003618 }
3619
3620 // AMD64-ABI 3.5.7p5: Step 5. Set:
3621 // l->gp_offset = l->gp_offset + num_gp * 8
3622 // l->fp_offset = l->fp_offset + num_fp * 16.
3623 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003624 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003625 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3626 gp_offset_p);
3627 }
3628 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003629 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003630 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3631 fp_offset_p);
3632 }
3633 CGF.EmitBranch(ContBlock);
3634
3635 // Emit code to load the value if it was passed in memory.
3636
3637 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003638 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003639
3640 // Return the appropriate result.
3641
3642 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003643 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3644 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003645 return ResAddr;
3646}
3647
Charles Davisc7d5c942015-09-17 20:55:33 +00003648Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3649 QualType Ty) const {
3650 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3651 CGF.getContext().getTypeInfoInChars(Ty),
3652 CharUnits::fromQuantity(8),
3653 /*allowHigherAlign*/ false);
3654}
3655
Reid Kleckner80944df2014-10-31 22:00:51 +00003656ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3657 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003658
3659 if (Ty->isVoidType())
3660 return ABIArgInfo::getIgnore();
3661
3662 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3663 Ty = EnumTy->getDecl()->getIntegerType();
3664
Reid Kleckner80944df2014-10-31 22:00:51 +00003665 TypeInfo Info = getContext().getTypeInfo(Ty);
3666 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003667 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003668
Reid Kleckner9005f412014-05-02 00:51:20 +00003669 const RecordType *RT = Ty->getAs<RecordType>();
3670 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003671 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003672 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003673 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003674 }
3675
3676 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003677 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003678
Reid Kleckner9005f412014-05-02 00:51:20 +00003679 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003680
Reid Kleckner80944df2014-10-31 22:00:51 +00003681 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3682 // other targets.
3683 const Type *Base = nullptr;
3684 uint64_t NumElts = 0;
3685 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3686 if (FreeSSERegs >= NumElts) {
3687 FreeSSERegs -= NumElts;
3688 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3689 return ABIArgInfo::getDirect();
3690 return ABIArgInfo::getExpand();
3691 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003692 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003693 }
3694
3695
Reid Klecknerec87fec2014-05-02 01:17:12 +00003696 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003697 // If the member pointer is represented by an LLVM int or ptr, pass it
3698 // directly.
3699 llvm::Type *LLTy = CGT.ConvertType(Ty);
3700 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3701 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003702 }
3703
Michael Kuperstein4f818702015-02-24 09:35:58 +00003704 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003705 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3706 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003707 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003708 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003709
Reid Kleckner9005f412014-05-02 00:51:20 +00003710 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003711 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003712 }
3713
Julien Lerouge10dcff82014-08-27 00:36:55 +00003714 // Bool type is always extended to the ABI, other builtin types are not
3715 // extended.
3716 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3717 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003718 return ABIArgInfo::getExtend();
3719
Reid Kleckner11a17192015-10-28 22:29:52 +00003720 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3721 // passes them indirectly through memory.
3722 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3723 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3724 if (LDF == &llvm::APFloat::x87DoubleExtended)
3725 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3726 }
3727
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003728 return ABIArgInfo::getDirect();
3729}
3730
3731void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003732 bool IsVectorCall =
3733 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003734 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003735
Erich Keane757d3172016-11-02 18:29:35 +00003736 unsigned FreeSSERegs = 0;
3737 if (IsVectorCall) {
3738 // We can use up to 4 SSE return registers with vectorcall.
3739 FreeSSERegs = 4;
3740 } else if (IsRegCall) {
3741 // RegCall gives us 16 SSE registers.
3742 FreeSSERegs = 16;
3743 }
3744
Reid Kleckner80944df2014-10-31 22:00:51 +00003745 if (!getCXXABI().classifyReturnType(FI))
3746 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3747
Erich Keane757d3172016-11-02 18:29:35 +00003748 if (IsVectorCall) {
3749 // We can use up to 6 SSE register parameters with vectorcall.
3750 FreeSSERegs = 6;
3751 } else if (IsRegCall) {
3752 FreeSSERegs = 16;
3753 }
3754
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003755 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003756 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003757}
3758
John McCall7f416cc2015-09-08 08:05:57 +00003759Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3760 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00003761
3762 bool IsIndirect = false;
3763
3764 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3765 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3766 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3767 uint64_t Width = getContext().getTypeSize(Ty);
3768 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3769 }
3770
3771 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00003772 CGF.getContext().getTypeInfoInChars(Ty),
3773 CharUnits::fromQuantity(8),
3774 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003775}
Chris Lattner0cf24192010-06-28 20:05:43 +00003776
John McCallea8d8bb2010-03-11 00:10:12 +00003777// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003778namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003779/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3780class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003781bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003782public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003783 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3784 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003785
John McCall7f416cc2015-09-08 08:05:57 +00003786 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3787 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003788};
3789
3790class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3791public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003792 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3793 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003794
Craig Topper4f12f102014-03-12 06:41:41 +00003795 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003796 // This is recovered from gcc output.
3797 return 1; // r1 is the dedicated stack pointer
3798 }
3799
3800 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003801 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003802};
3803
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003804}
John McCallea8d8bb2010-03-11 00:10:12 +00003805
James Y Knight29b5f082016-02-24 02:59:33 +00003806// TODO: this implementation is now likely redundant with
3807// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003808Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3809 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003810 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003811 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3812 // TODO: Implement this. For now ignore.
3813 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003814 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003815 }
3816
John McCall7f416cc2015-09-08 08:05:57 +00003817 // struct __va_list_tag {
3818 // unsigned char gpr;
3819 // unsigned char fpr;
3820 // unsigned short reserved;
3821 // void *overflow_arg_area;
3822 // void *reg_save_area;
3823 // };
3824
Roman Divacky8a12d842014-11-03 18:32:54 +00003825 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003826 bool isInt =
3827 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003828 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003829
3830 // All aggregates are passed indirectly? That doesn't seem consistent
3831 // with the argument-lowering code.
3832 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003833
3834 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003835
3836 // The calling convention either uses 1-2 GPRs or 1 FPR.
3837 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003838 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003839 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3840 } else {
3841 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003842 }
John McCall7f416cc2015-09-08 08:05:57 +00003843
3844 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3845
3846 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003847 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003848 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3849 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3850 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003851
Eric Christopher7565e0d2015-05-29 23:09:49 +00003852 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003853 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003854
3855 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3856 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3857 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3858
3859 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3860
John McCall7f416cc2015-09-08 08:05:57 +00003861 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3862 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003863
John McCall7f416cc2015-09-08 08:05:57 +00003864 // Case 1: consume registers.
3865 Address RegAddr = Address::invalid();
3866 {
3867 CGF.EmitBlock(UsingRegs);
3868
3869 Address RegSaveAreaPtr =
3870 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3871 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3872 CharUnits::fromQuantity(8));
3873 assert(RegAddr.getElementType() == CGF.Int8Ty);
3874
3875 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003876 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003877 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3878 CharUnits::fromQuantity(32));
3879 }
3880
3881 // Get the address of the saved value by scaling the number of
3882 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003883 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003884 llvm::Value *RegOffset =
3885 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3886 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3887 RegAddr.getPointer(), RegOffset),
3888 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3889 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3890
3891 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003892 NumRegs =
3893 Builder.CreateAdd(NumRegs,
3894 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003895 Builder.CreateStore(NumRegs, NumRegsAddr);
3896
3897 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003898 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003899
John McCall7f416cc2015-09-08 08:05:57 +00003900 // Case 2: consume space in the overflow area.
3901 Address MemAddr = Address::invalid();
3902 {
3903 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003904
Roman Divacky039b9702016-02-20 08:31:24 +00003905 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3906
John McCall7f416cc2015-09-08 08:05:57 +00003907 // Everything in the overflow area is rounded up to a size of at least 4.
3908 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3909
3910 CharUnits Size;
3911 if (!isIndirect) {
3912 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003913 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003914 } else {
3915 Size = CGF.getPointerSize();
3916 }
3917
3918 Address OverflowAreaAddr =
3919 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003920 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003921 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003922 // Round up address of argument to alignment
3923 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3924 if (Align > OverflowAreaAlign) {
3925 llvm::Value *Ptr = OverflowArea.getPointer();
3926 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3927 Align);
3928 }
3929
John McCall7f416cc2015-09-08 08:05:57 +00003930 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3931
3932 // Increase the overflow area.
3933 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3934 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3935 CGF.EmitBranch(Cont);
3936 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003937
3938 CGF.EmitBlock(Cont);
3939
John McCall7f416cc2015-09-08 08:05:57 +00003940 // Merge the cases with a phi.
3941 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3942 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003943
John McCall7f416cc2015-09-08 08:05:57 +00003944 // Load the pointer if the argument was passed indirectly.
3945 if (isIndirect) {
3946 Result = Address(Builder.CreateLoad(Result, "aggr"),
3947 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003948 }
3949
3950 return Result;
3951}
3952
John McCallea8d8bb2010-03-11 00:10:12 +00003953bool
3954PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3955 llvm::Value *Address) const {
3956 // This is calculated from the LLVM and GCC tables and verified
3957 // against gcc output. AFAIK all ABIs use the same encoding.
3958
3959 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003960
Chris Lattnerece04092012-02-07 00:39:47 +00003961 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003962 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3963 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3964 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3965
3966 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003967 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003968
3969 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003970 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003971
3972 // 64-76 are various 4-byte special-purpose registers:
3973 // 64: mq
3974 // 65: lr
3975 // 66: ctr
3976 // 67: ap
3977 // 68-75 cr0-7
3978 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003979 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003980
3981 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003982 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003983
3984 // 109: vrsave
3985 // 110: vscr
3986 // 111: spe_acc
3987 // 112: spefscr
3988 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003989 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003990
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003991 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003992}
3993
Roman Divackyd966e722012-05-09 18:22:46 +00003994// PowerPC-64
3995
3996namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003997/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00003998class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003999public:
4000 enum ABIKind {
4001 ELFv1 = 0,
4002 ELFv2
4003 };
4004
4005private:
4006 static const unsigned GPRBits = 64;
4007 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004008 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004009 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004010
4011 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4012 // will be passed in a QPX register.
4013 bool IsQPXVectorTy(const Type *Ty) const {
4014 if (!HasQPX)
4015 return false;
4016
4017 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4018 unsigned NumElements = VT->getNumElements();
4019 if (NumElements == 1)
4020 return false;
4021
4022 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4023 if (getContext().getTypeSize(Ty) <= 256)
4024 return true;
4025 } else if (VT->getElementType()->
4026 isSpecificBuiltinType(BuiltinType::Float)) {
4027 if (getContext().getTypeSize(Ty) <= 128)
4028 return true;
4029 }
4030 }
4031
4032 return false;
4033 }
4034
4035 bool IsQPXVectorTy(QualType Ty) const {
4036 return IsQPXVectorTy(Ty.getTypePtr());
4037 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004038
4039public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004040 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4041 bool SoftFloatABI)
4042 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4043 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004044
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004045 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004046 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004047
4048 ABIArgInfo classifyReturnType(QualType RetTy) const;
4049 ABIArgInfo classifyArgumentType(QualType Ty) const;
4050
Reid Klecknere9f6a712014-10-31 17:10:41 +00004051 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4052 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4053 uint64_t Members) const override;
4054
Bill Schmidt84d37792012-10-12 19:26:17 +00004055 // TODO: We can add more logic to computeInfo to improve performance.
4056 // Example: For aggregate arguments that fit in a register, we could
4057 // use getDirectInReg (as is done below for structs containing a single
4058 // floating-point value) to avoid pushing them to memory on function
4059 // entry. This would require changing the logic in PPCISelLowering
4060 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004061 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004062 if (!getCXXABI().classifyReturnType(FI))
4063 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004064 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004065 // We rely on the default argument classification for the most part.
4066 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004067 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004068 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004069 if (T) {
4070 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004071 if (IsQPXVectorTy(T) ||
4072 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004073 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004074 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004075 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004076 continue;
4077 }
4078 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004079 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004080 }
4081 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004082
John McCall7f416cc2015-09-08 08:05:57 +00004083 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4084 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004085};
4086
4087class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004088
Bill Schmidt25cb3492012-10-03 19:18:57 +00004089public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004090 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004091 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4092 bool SoftFloatABI)
4093 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4094 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004095
Craig Topper4f12f102014-03-12 06:41:41 +00004096 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004097 // This is recovered from gcc output.
4098 return 1; // r1 is the dedicated stack pointer
4099 }
4100
4101 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004102 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004103};
4104
Roman Divackyd966e722012-05-09 18:22:46 +00004105class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4106public:
4107 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4108
Craig Topper4f12f102014-03-12 06:41:41 +00004109 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004110 // This is recovered from gcc output.
4111 return 1; // r1 is the dedicated stack pointer
4112 }
4113
4114 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004115 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004116};
4117
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004118}
Roman Divackyd966e722012-05-09 18:22:46 +00004119
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004120// Return true if the ABI requires Ty to be passed sign- or zero-
4121// extended to 64 bits.
4122bool
4123PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4124 // Treat an enum type as its underlying type.
4125 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4126 Ty = EnumTy->getDecl()->getIntegerType();
4127
4128 // Promotable integer types are required to be promoted by the ABI.
4129 if (Ty->isPromotableIntegerType())
4130 return true;
4131
4132 // In addition to the usual promotable integer types, we also need to
4133 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4134 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4135 switch (BT->getKind()) {
4136 case BuiltinType::Int:
4137 case BuiltinType::UInt:
4138 return true;
4139 default:
4140 break;
4141 }
4142
4143 return false;
4144}
4145
John McCall7f416cc2015-09-08 08:05:57 +00004146/// isAlignedParamType - Determine whether a type requires 16-byte or
4147/// higher alignment in the parameter area. Always returns at least 8.
4148CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004149 // Complex types are passed just like their elements.
4150 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4151 Ty = CTy->getElementType();
4152
4153 // Only vector types of size 16 bytes need alignment (larger types are
4154 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004155 if (IsQPXVectorTy(Ty)) {
4156 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004157 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004158
John McCall7f416cc2015-09-08 08:05:57 +00004159 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004160 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004161 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004162 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004163
4164 // For single-element float/vector structs, we consider the whole type
4165 // to have the same alignment requirements as its single element.
4166 const Type *AlignAsType = nullptr;
4167 const Type *EltType = isSingleElementStruct(Ty, getContext());
4168 if (EltType) {
4169 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004170 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004171 getContext().getTypeSize(EltType) == 128) ||
4172 (BT && BT->isFloatingPoint()))
4173 AlignAsType = EltType;
4174 }
4175
Ulrich Weigandb7122372014-07-21 00:48:09 +00004176 // Likewise for ELFv2 homogeneous aggregates.
4177 const Type *Base = nullptr;
4178 uint64_t Members = 0;
4179 if (!AlignAsType && Kind == ELFv2 &&
4180 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4181 AlignAsType = Base;
4182
Ulrich Weigand581badc2014-07-10 17:20:07 +00004183 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004184 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4185 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004186 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004187
John McCall7f416cc2015-09-08 08:05:57 +00004188 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004189 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004190 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004191 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004192
4193 // Otherwise, we only need alignment for any aggregate type that
4194 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004195 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4196 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004197 return CharUnits::fromQuantity(32);
4198 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004199 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004200
John McCall7f416cc2015-09-08 08:05:57 +00004201 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004202}
4203
Ulrich Weigandb7122372014-07-21 00:48:09 +00004204/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4205/// aggregate. Base is set to the base element type, and Members is set
4206/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004207bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4208 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004209 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4210 uint64_t NElements = AT->getSize().getZExtValue();
4211 if (NElements == 0)
4212 return false;
4213 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4214 return false;
4215 Members *= NElements;
4216 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4217 const RecordDecl *RD = RT->getDecl();
4218 if (RD->hasFlexibleArrayMember())
4219 return false;
4220
4221 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004222
4223 // If this is a C++ record, check the bases first.
4224 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4225 for (const auto &I : CXXRD->bases()) {
4226 // Ignore empty records.
4227 if (isEmptyRecord(getContext(), I.getType(), true))
4228 continue;
4229
4230 uint64_t FldMembers;
4231 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4232 return false;
4233
4234 Members += FldMembers;
4235 }
4236 }
4237
Ulrich Weigandb7122372014-07-21 00:48:09 +00004238 for (const auto *FD : RD->fields()) {
4239 // Ignore (non-zero arrays of) empty records.
4240 QualType FT = FD->getType();
4241 while (const ConstantArrayType *AT =
4242 getContext().getAsConstantArrayType(FT)) {
4243 if (AT->getSize().getZExtValue() == 0)
4244 return false;
4245 FT = AT->getElementType();
4246 }
4247 if (isEmptyRecord(getContext(), FT, true))
4248 continue;
4249
4250 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4251 if (getContext().getLangOpts().CPlusPlus &&
4252 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4253 continue;
4254
4255 uint64_t FldMembers;
4256 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4257 return false;
4258
4259 Members = (RD->isUnion() ?
4260 std::max(Members, FldMembers) : Members + FldMembers);
4261 }
4262
4263 if (!Base)
4264 return false;
4265
4266 // Ensure there is no padding.
4267 if (getContext().getTypeSize(Base) * Members !=
4268 getContext().getTypeSize(Ty))
4269 return false;
4270 } else {
4271 Members = 1;
4272 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4273 Members = 2;
4274 Ty = CT->getElementType();
4275 }
4276
Reid Klecknere9f6a712014-10-31 17:10:41 +00004277 // Most ABIs only support float, double, and some vector type widths.
4278 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004279 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004280
4281 // The base type must be the same for all members. Types that
4282 // agree in both total size and mode (float vs. vector) are
4283 // treated as being equivalent here.
4284 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004285 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004286 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004287 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4288 // so make sure to widen it explicitly.
4289 if (const VectorType *VT = Base->getAs<VectorType>()) {
4290 QualType EltTy = VT->getElementType();
4291 unsigned NumElements =
4292 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4293 Base = getContext()
4294 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4295 .getTypePtr();
4296 }
4297 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004298
4299 if (Base->isVectorType() != TyPtr->isVectorType() ||
4300 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4301 return false;
4302 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004303 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4304}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004305
Reid Klecknere9f6a712014-10-31 17:10:41 +00004306bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4307 // Homogeneous aggregates for ELFv2 must have base types of float,
4308 // double, long double, or 128-bit vectors.
4309 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4310 if (BT->getKind() == BuiltinType::Float ||
4311 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004312 BT->getKind() == BuiltinType::LongDouble) {
4313 if (IsSoftFloatABI)
4314 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004315 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004316 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004317 }
4318 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004319 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004320 return true;
4321 }
4322 return false;
4323}
4324
4325bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4326 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004327 // Vector types require one register, floating point types require one
4328 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004329 uint32_t NumRegs =
4330 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004331
4332 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004333 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004334}
4335
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004336ABIArgInfo
4337PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004338 Ty = useFirstFieldIfTransparentUnion(Ty);
4339
Bill Schmidt90b22c92012-11-27 02:46:43 +00004340 if (Ty->isAnyComplexType())
4341 return ABIArgInfo::getDirect();
4342
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004343 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4344 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004345 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004346 uint64_t Size = getContext().getTypeSize(Ty);
4347 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004348 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004349 else if (Size < 128) {
4350 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4351 return ABIArgInfo::getDirect(CoerceTy);
4352 }
4353 }
4354
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004355 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004356 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004357 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004358
John McCall7f416cc2015-09-08 08:05:57 +00004359 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4360 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004361
4362 // ELFv2 homogeneous aggregates are passed as array types.
4363 const Type *Base = nullptr;
4364 uint64_t Members = 0;
4365 if (Kind == ELFv2 &&
4366 isHomogeneousAggregate(Ty, Base, Members)) {
4367 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4368 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4369 return ABIArgInfo::getDirect(CoerceTy);
4370 }
4371
Ulrich Weigand601957f2014-07-21 00:56:36 +00004372 // If an aggregate may end up fully in registers, we do not
4373 // use the ByVal method, but pass the aggregate as array.
4374 // This is usually beneficial since we avoid forcing the
4375 // back-end to store the argument to memory.
4376 uint64_t Bits = getContext().getTypeSize(Ty);
4377 if (Bits > 0 && Bits <= 8 * GPRBits) {
4378 llvm::Type *CoerceTy;
4379
4380 // Types up to 8 bytes are passed as integer type (which will be
4381 // properly aligned in the argument save area doubleword).
4382 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004383 CoerceTy =
4384 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004385 // Larger types are passed as arrays, with the base type selected
4386 // according to the required alignment in the save area.
4387 else {
4388 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004389 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004390 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4391 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4392 }
4393
4394 return ABIArgInfo::getDirect(CoerceTy);
4395 }
4396
Ulrich Weigandb7122372014-07-21 00:48:09 +00004397 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004398 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4399 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004400 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004401 }
4402
4403 return (isPromotableTypeForABI(Ty) ?
4404 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4405}
4406
4407ABIArgInfo
4408PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4409 if (RetTy->isVoidType())
4410 return ABIArgInfo::getIgnore();
4411
Bill Schmidta3d121c2012-12-17 04:20:17 +00004412 if (RetTy->isAnyComplexType())
4413 return ABIArgInfo::getDirect();
4414
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004415 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4416 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004417 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004418 uint64_t Size = getContext().getTypeSize(RetTy);
4419 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004420 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004421 else if (Size < 128) {
4422 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4423 return ABIArgInfo::getDirect(CoerceTy);
4424 }
4425 }
4426
Ulrich Weigandb7122372014-07-21 00:48:09 +00004427 if (isAggregateTypeForABI(RetTy)) {
4428 // ELFv2 homogeneous aggregates are returned as array types.
4429 const Type *Base = nullptr;
4430 uint64_t Members = 0;
4431 if (Kind == ELFv2 &&
4432 isHomogeneousAggregate(RetTy, Base, Members)) {
4433 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4434 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4435 return ABIArgInfo::getDirect(CoerceTy);
4436 }
4437
4438 // ELFv2 small aggregates are returned in up to two registers.
4439 uint64_t Bits = getContext().getTypeSize(RetTy);
4440 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4441 if (Bits == 0)
4442 return ABIArgInfo::getIgnore();
4443
4444 llvm::Type *CoerceTy;
4445 if (Bits > GPRBits) {
4446 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004447 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004448 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004449 CoerceTy =
4450 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004451 return ABIArgInfo::getDirect(CoerceTy);
4452 }
4453
4454 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004455 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004456 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004457
4458 return (isPromotableTypeForABI(RetTy) ?
4459 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4460}
4461
Bill Schmidt25cb3492012-10-03 19:18:57 +00004462// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004463Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4464 QualType Ty) const {
4465 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4466 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004467
John McCall7f416cc2015-09-08 08:05:57 +00004468 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004469
Bill Schmidt924c4782013-01-14 17:45:36 +00004470 // If we have a complex type and the base type is smaller than 8 bytes,
4471 // the ABI calls for the real and imaginary parts to be right-adjusted
4472 // in separate doublewords. However, Clang expects us to produce a
4473 // pointer to a structure with the two parts packed tightly. So generate
4474 // loads of the real and imaginary parts relative to the va_list pointer,
4475 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004476 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4477 CharUnits EltSize = TypeInfo.first / 2;
4478 if (EltSize < SlotSize) {
4479 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4480 SlotSize * 2, SlotSize,
4481 SlotSize, /*AllowHigher*/ true);
4482
4483 Address RealAddr = Addr;
4484 Address ImagAddr = RealAddr;
4485 if (CGF.CGM.getDataLayout().isBigEndian()) {
4486 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4487 SlotSize - EltSize);
4488 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4489 2 * SlotSize - EltSize);
4490 } else {
4491 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4492 }
4493
4494 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4495 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4496 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4497 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4498 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4499
4500 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4501 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4502 /*init*/ true);
4503 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004504 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004505 }
4506
John McCall7f416cc2015-09-08 08:05:57 +00004507 // Otherwise, just use the general rule.
4508 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4509 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004510}
4511
4512static bool
4513PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4514 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004515 // This is calculated from the LLVM and GCC tables and verified
4516 // against gcc output. AFAIK all ABIs use the same encoding.
4517
4518 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4519
4520 llvm::IntegerType *i8 = CGF.Int8Ty;
4521 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4522 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4523 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4524
4525 // 0-31: r0-31, the 8-byte general-purpose registers
4526 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4527
4528 // 32-63: fp0-31, the 8-byte floating-point registers
4529 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4530
Hal Finkel84832a72016-08-30 02:38:34 +00004531 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004532 // 64: mq
4533 // 65: lr
4534 // 66: ctr
4535 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004536 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4537
4538 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004539 // 68-75 cr0-7
4540 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004541 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004542
4543 // 77-108: v0-31, the 16-byte vector registers
4544 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4545
4546 // 109: vrsave
4547 // 110: vscr
4548 // 111: spe_acc
4549 // 112: spefscr
4550 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004551 // 114: tfhar
4552 // 115: tfiar
4553 // 116: texasr
4554 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004555
4556 return false;
4557}
John McCallea8d8bb2010-03-11 00:10:12 +00004558
Bill Schmidt25cb3492012-10-03 19:18:57 +00004559bool
4560PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4561 CodeGen::CodeGenFunction &CGF,
4562 llvm::Value *Address) const {
4563
4564 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4565}
4566
4567bool
4568PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4569 llvm::Value *Address) const {
4570
4571 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4572}
4573
Chris Lattner0cf24192010-06-28 20:05:43 +00004574//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004575// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004576//===----------------------------------------------------------------------===//
4577
4578namespace {
4579
John McCall12f23522016-04-04 18:33:08 +00004580class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004581public:
4582 enum ABIKind {
4583 AAPCS = 0,
4584 DarwinPCS
4585 };
4586
4587private:
4588 ABIKind Kind;
4589
4590public:
John McCall12f23522016-04-04 18:33:08 +00004591 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4592 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004593
4594private:
4595 ABIKind getABIKind() const { return Kind; }
4596 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4597
4598 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004599 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004600 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4601 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4602 uint64_t Members) const override;
4603
Tim Northovera2ee4332014-03-29 15:09:45 +00004604 bool isIllegalVectorType(QualType Ty) const;
4605
David Blaikie1cbb9712014-11-14 19:09:44 +00004606 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004607 if (!getCXXABI().classifyReturnType(FI))
4608 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004609
Tim Northoverb047bfa2014-11-27 21:02:49 +00004610 for (auto &it : FI.arguments())
4611 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004612 }
4613
John McCall7f416cc2015-09-08 08:05:57 +00004614 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4615 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004616
John McCall7f416cc2015-09-08 08:05:57 +00004617 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4618 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004619
John McCall7f416cc2015-09-08 08:05:57 +00004620 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4621 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004622 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4623 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4624 }
John McCall12f23522016-04-04 18:33:08 +00004625
4626 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4627 ArrayRef<llvm::Type*> scalars,
4628 bool asReturnValue) const override {
4629 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4630 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004631};
4632
Tim Northover573cbee2014-05-24 12:52:07 +00004633class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004634public:
Tim Northover573cbee2014-05-24 12:52:07 +00004635 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4636 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004637
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004638 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004639 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4640 }
4641
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004642 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4643 return 31;
4644 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004645
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004646 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004647};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004648}
Tim Northovera2ee4332014-03-29 15:09:45 +00004649
Tim Northoverb047bfa2014-11-27 21:02:49 +00004650ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004651 Ty = useFirstFieldIfTransparentUnion(Ty);
4652
Tim Northovera2ee4332014-03-29 15:09:45 +00004653 // Handle illegal vector types here.
4654 if (isIllegalVectorType(Ty)) {
4655 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004656 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004657 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004658 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4659 return ABIArgInfo::getDirect(ResType);
4660 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004661 if (Size <= 32) {
4662 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004663 return ABIArgInfo::getDirect(ResType);
4664 }
4665 if (Size == 64) {
4666 llvm::Type *ResType =
4667 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004668 return ABIArgInfo::getDirect(ResType);
4669 }
4670 if (Size == 128) {
4671 llvm::Type *ResType =
4672 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004673 return ABIArgInfo::getDirect(ResType);
4674 }
John McCall7f416cc2015-09-08 08:05:57 +00004675 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004676 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004677
4678 if (!isAggregateTypeForABI(Ty)) {
4679 // Treat an enum type as its underlying type.
4680 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4681 Ty = EnumTy->getDecl()->getIntegerType();
4682
Tim Northovera2ee4332014-03-29 15:09:45 +00004683 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4684 ? ABIArgInfo::getExtend()
4685 : ABIArgInfo::getDirect());
4686 }
4687
4688 // Structures with either a non-trivial destructor or a non-trivial
4689 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004690 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004691 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4692 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004693 }
4694
4695 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4696 // elsewhere for GNU compatibility.
4697 if (isEmptyRecord(getContext(), Ty, true)) {
4698 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4699 return ABIArgInfo::getIgnore();
4700
Tim Northovera2ee4332014-03-29 15:09:45 +00004701 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4702 }
4703
4704 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004705 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004706 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004707 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004708 return ABIArgInfo::getDirect(
4709 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004710 }
4711
4712 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4713 uint64_t Size = getContext().getTypeSize(Ty);
4714 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004715 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4716 // same size and alignment.
4717 if (getTarget().isRenderScriptTarget()) {
4718 return coerceToIntArray(Ty, getContext(), getVMContext());
4719 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00004720 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004721 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004722
Tim Northovera2ee4332014-03-29 15:09:45 +00004723 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4724 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004725 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004726 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4727 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4728 }
4729 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4730 }
4731
John McCall7f416cc2015-09-08 08:05:57 +00004732 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004733}
4734
Tim Northover573cbee2014-05-24 12:52:07 +00004735ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004736 if (RetTy->isVoidType())
4737 return ABIArgInfo::getIgnore();
4738
4739 // Large vector types should be returned via memory.
4740 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004741 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004742
4743 if (!isAggregateTypeForABI(RetTy)) {
4744 // Treat an enum type as its underlying type.
4745 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4746 RetTy = EnumTy->getDecl()->getIntegerType();
4747
Tim Northover4dab6982014-04-18 13:46:08 +00004748 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4749 ? ABIArgInfo::getExtend()
4750 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004751 }
4752
Tim Northovera2ee4332014-03-29 15:09:45 +00004753 if (isEmptyRecord(getContext(), RetTy, true))
4754 return ABIArgInfo::getIgnore();
4755
Craig Topper8a13c412014-05-21 05:09:00 +00004756 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004757 uint64_t Members = 0;
4758 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004759 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4760 return ABIArgInfo::getDirect();
4761
4762 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4763 uint64_t Size = getContext().getTypeSize(RetTy);
4764 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004765 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4766 // same size and alignment.
4767 if (getTarget().isRenderScriptTarget()) {
4768 return coerceToIntArray(RetTy, getContext(), getVMContext());
4769 }
Pete Cooper635b5092015-04-17 22:16:24 +00004770 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004771 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004772
4773 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4774 // For aggregates with 16-byte alignment, we use i128.
4775 if (Alignment < 128 && Size == 128) {
4776 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4777 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4778 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004779 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4780 }
4781
John McCall7f416cc2015-09-08 08:05:57 +00004782 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004783}
4784
Tim Northover573cbee2014-05-24 12:52:07 +00004785/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4786bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004787 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4788 // Check whether VT is legal.
4789 unsigned NumElements = VT->getNumElements();
4790 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004791 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004792 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004793 return true;
4794 return Size != 64 && (Size != 128 || NumElements == 1);
4795 }
4796 return false;
4797}
4798
Reid Klecknere9f6a712014-10-31 17:10:41 +00004799bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4800 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4801 // point type or a short-vector type. This is the same as the 32-bit ABI,
4802 // but with the difference that any floating-point type is allowed,
4803 // including __fp16.
4804 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4805 if (BT->isFloatingPoint())
4806 return true;
4807 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4808 unsigned VecSize = getContext().getTypeSize(VT);
4809 if (VecSize == 64 || VecSize == 128)
4810 return true;
4811 }
4812 return false;
4813}
4814
4815bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4816 uint64_t Members) const {
4817 return Members <= 4;
4818}
4819
John McCall7f416cc2015-09-08 08:05:57 +00004820Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004821 QualType Ty,
4822 CodeGenFunction &CGF) const {
4823 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004824 bool IsIndirect = AI.isIndirect();
4825
Tim Northoverb047bfa2014-11-27 21:02:49 +00004826 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4827 if (IsIndirect)
4828 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4829 else if (AI.getCoerceToType())
4830 BaseTy = AI.getCoerceToType();
4831
4832 unsigned NumRegs = 1;
4833 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4834 BaseTy = ArrTy->getElementType();
4835 NumRegs = ArrTy->getNumElements();
4836 }
4837 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4838
Tim Northovera2ee4332014-03-29 15:09:45 +00004839 // The AArch64 va_list type and handling is specified in the Procedure Call
4840 // Standard, section B.4:
4841 //
4842 // struct {
4843 // void *__stack;
4844 // void *__gr_top;
4845 // void *__vr_top;
4846 // int __gr_offs;
4847 // int __vr_offs;
4848 // };
4849
4850 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4851 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4852 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4853 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004854
John McCall7f416cc2015-09-08 08:05:57 +00004855 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4856 CharUnits TyAlign = TyInfo.second;
4857
4858 Address reg_offs_p = Address::invalid();
4859 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004860 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004861 CharUnits reg_top_offset;
4862 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004863 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004864 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004865 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004866 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4867 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004868 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4869 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004870 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004871 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004872 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004873 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004874 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004875 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4876 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004877 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4878 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004879 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004880 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004881 }
4882
4883 //=======================================
4884 // Find out where argument was passed
4885 //=======================================
4886
4887 // If reg_offs >= 0 we're already using the stack for this type of
4888 // argument. We don't want to keep updating reg_offs (in case it overflows,
4889 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4890 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004891 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004892 UsingStack = CGF.Builder.CreateICmpSGE(
4893 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4894
4895 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4896
4897 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004898 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004899 CGF.EmitBlock(MaybeRegBlock);
4900
4901 // Integer arguments may need to correct register alignment (for example a
4902 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4903 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004904 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4905 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004906
4907 reg_offs = CGF.Builder.CreateAdd(
4908 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4909 "align_regoffs");
4910 reg_offs = CGF.Builder.CreateAnd(
4911 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4912 "aligned_regoffs");
4913 }
4914
4915 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004916 // The fact that this is done unconditionally reflects the fact that
4917 // allocating an argument to the stack also uses up all the remaining
4918 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004919 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004920 NewOffset = CGF.Builder.CreateAdd(
4921 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4922 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4923
4924 // Now we're in a position to decide whether this argument really was in
4925 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004926 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004927 InRegs = CGF.Builder.CreateICmpSLE(
4928 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4929
4930 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4931
4932 //=======================================
4933 // Argument was in registers
4934 //=======================================
4935
4936 // Now we emit the code for if the argument was originally passed in
4937 // registers. First start the appropriate block:
4938 CGF.EmitBlock(InRegBlock);
4939
John McCall7f416cc2015-09-08 08:05:57 +00004940 llvm::Value *reg_top = nullptr;
4941 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4942 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004943 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004944 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4945 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4946 Address RegAddr = Address::invalid();
4947 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004948
4949 if (IsIndirect) {
4950 // If it's been passed indirectly (actually a struct), whatever we find from
4951 // stored registers or on the stack will actually be a struct **.
4952 MemTy = llvm::PointerType::getUnqual(MemTy);
4953 }
4954
Craig Topper8a13c412014-05-21 05:09:00 +00004955 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004956 uint64_t NumMembers = 0;
4957 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004958 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004959 // Homogeneous aggregates passed in registers will have their elements split
4960 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4961 // qN+1, ...). We reload and store into a temporary local variable
4962 // contiguously.
4963 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004964 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004965 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4966 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004967 Address Tmp = CGF.CreateTempAlloca(HFATy,
4968 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004969
John McCall7f416cc2015-09-08 08:05:57 +00004970 // On big-endian platforms, the value will be right-aligned in its slot.
4971 int Offset = 0;
4972 if (CGF.CGM.getDataLayout().isBigEndian() &&
4973 BaseTyInfo.first.getQuantity() < 16)
4974 Offset = 16 - BaseTyInfo.first.getQuantity();
4975
Tim Northovera2ee4332014-03-29 15:09:45 +00004976 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004977 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4978 Address LoadAddr =
4979 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4980 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4981
4982 Address StoreAddr =
4983 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004984
4985 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4986 CGF.Builder.CreateStore(Elem, StoreAddr);
4987 }
4988
John McCall7f416cc2015-09-08 08:05:57 +00004989 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004990 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004991 // Otherwise the object is contiguous in memory.
4992
4993 // It might be right-aligned in its slot.
4994 CharUnits SlotSize = BaseAddr.getAlignment();
4995 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004996 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004997 TyInfo.first < SlotSize) {
4998 CharUnits Offset = SlotSize - TyInfo.first;
4999 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005000 }
5001
John McCall7f416cc2015-09-08 08:05:57 +00005002 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005003 }
5004
5005 CGF.EmitBranch(ContBlock);
5006
5007 //=======================================
5008 // Argument was on the stack
5009 //=======================================
5010 CGF.EmitBlock(OnStackBlock);
5011
John McCall7f416cc2015-09-08 08:05:57 +00005012 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5013 CharUnits::Zero(), "stack_p");
5014 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005015
John McCall7f416cc2015-09-08 08:05:57 +00005016 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005017 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005018 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5019 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005020
John McCall7f416cc2015-09-08 08:05:57 +00005021 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005022
John McCall7f416cc2015-09-08 08:05:57 +00005023 OnStackPtr = CGF.Builder.CreateAdd(
5024 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005025 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005026 OnStackPtr = CGF.Builder.CreateAnd(
5027 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005028 "align_stack");
5029
John McCall7f416cc2015-09-08 08:05:57 +00005030 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005031 }
John McCall7f416cc2015-09-08 08:05:57 +00005032 Address OnStackAddr(OnStackPtr,
5033 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005034
John McCall7f416cc2015-09-08 08:05:57 +00005035 // All stack slots are multiples of 8 bytes.
5036 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5037 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005038 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005039 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005040 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005041 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005042
John McCall7f416cc2015-09-08 08:05:57 +00005043 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005044 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005045 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005046
5047 // Write the new value of __stack for the next call to va_arg
5048 CGF.Builder.CreateStore(NewStack, stack_p);
5049
5050 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005051 TyInfo.first < StackSlotSize) {
5052 CharUnits Offset = StackSlotSize - TyInfo.first;
5053 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005054 }
5055
John McCall7f416cc2015-09-08 08:05:57 +00005056 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005057
5058 CGF.EmitBranch(ContBlock);
5059
5060 //=======================================
5061 // Tidy up
5062 //=======================================
5063 CGF.EmitBlock(ContBlock);
5064
John McCall7f416cc2015-09-08 08:05:57 +00005065 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5066 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005067
5068 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005069 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5070 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005071
5072 return ResAddr;
5073}
5074
John McCall7f416cc2015-09-08 08:05:57 +00005075Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5076 CodeGenFunction &CGF) const {
5077 // The backend's lowering doesn't support va_arg for aggregates or
5078 // illegal vector types. Lower VAArg here for these cases and use
5079 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005080 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005081 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005082
John McCall7f416cc2015-09-08 08:05:57 +00005083 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005084
John McCall7f416cc2015-09-08 08:05:57 +00005085 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005086 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005087 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5088 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5089 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005090 }
5091
John McCall7f416cc2015-09-08 08:05:57 +00005092 // The size of the actual thing passed, which might end up just
5093 // being a pointer for indirect types.
5094 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5095
5096 // Arguments bigger than 16 bytes which aren't homogeneous
5097 // aggregates should be passed indirectly.
5098 bool IsIndirect = false;
5099 if (TyInfo.first.getQuantity() > 16) {
5100 const Type *Base = nullptr;
5101 uint64_t Members = 0;
5102 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005103 }
5104
John McCall7f416cc2015-09-08 08:05:57 +00005105 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5106 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005107}
5108
5109//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005110// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005111//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005112
5113namespace {
5114
John McCall12f23522016-04-04 18:33:08 +00005115class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005116public:
5117 enum ABIKind {
5118 APCS = 0,
5119 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005120 AAPCS_VFP = 2,
5121 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005122 };
5123
5124private:
5125 ABIKind Kind;
5126
5127public:
John McCall12f23522016-04-04 18:33:08 +00005128 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5129 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005130 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005131 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005132
John McCall3480ef22011-08-30 01:42:09 +00005133 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005134 switch (getTarget().getTriple().getEnvironment()) {
5135 case llvm::Triple::Android:
5136 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005137 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005138 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005139 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005140 case llvm::Triple::MuslEABI:
5141 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005142 return true;
5143 default:
5144 return false;
5145 }
John McCall3480ef22011-08-30 01:42:09 +00005146 }
5147
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005148 bool isEABIHF() const {
5149 switch (getTarget().getTriple().getEnvironment()) {
5150 case llvm::Triple::EABIHF:
5151 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005152 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005153 return true;
5154 default:
5155 return false;
5156 }
5157 }
5158
Daniel Dunbar020daa92009-09-12 01:00:39 +00005159 ABIKind getABIKind() const { return Kind; }
5160
Tim Northovera484bc02013-10-01 14:34:25 +00005161private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005162 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005163 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005164 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005165
Reid Klecknere9f6a712014-10-31 17:10:41 +00005166 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5167 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5168 uint64_t Members) const override;
5169
Craig Topper4f12f102014-03-12 06:41:41 +00005170 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005171
John McCall7f416cc2015-09-08 08:05:57 +00005172 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5173 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005174
5175 llvm::CallingConv::ID getLLVMDefaultCC() const;
5176 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005177 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005178
5179 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5180 ArrayRef<llvm::Type*> scalars,
5181 bool asReturnValue) const override {
5182 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5183 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005184};
5185
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005186class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5187public:
Chris Lattner2b037972010-07-29 02:01:43 +00005188 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5189 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005190
John McCall3480ef22011-08-30 01:42:09 +00005191 const ARMABIInfo &getABIInfo() const {
5192 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5193 }
5194
Craig Topper4f12f102014-03-12 06:41:41 +00005195 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005196 return 13;
5197 }
Roman Divackyc1617352011-05-18 19:36:54 +00005198
Craig Topper4f12f102014-03-12 06:41:41 +00005199 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005200 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5201 }
5202
Roman Divackyc1617352011-05-18 19:36:54 +00005203 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005204 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005205 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005206
5207 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005208 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005209 return false;
5210 }
John McCall3480ef22011-08-30 01:42:09 +00005211
Craig Topper4f12f102014-03-12 06:41:41 +00005212 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005213 if (getABIInfo().isEABI()) return 88;
5214 return TargetCodeGenInfo::getSizeOfUnwindException();
5215 }
Tim Northovera484bc02013-10-01 14:34:25 +00005216
Eric Christopher162c91c2015-06-05 22:03:00 +00005217 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005218 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005219 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005220 if (!FD)
5221 return;
5222
5223 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5224 if (!Attr)
5225 return;
5226
5227 const char *Kind;
5228 switch (Attr->getInterrupt()) {
5229 case ARMInterruptAttr::Generic: Kind = ""; break;
5230 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5231 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5232 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5233 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5234 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5235 }
5236
5237 llvm::Function *Fn = cast<llvm::Function>(GV);
5238
5239 Fn->addFnAttr("interrupt", Kind);
5240
Tim Northover5627d392015-10-30 16:30:45 +00005241 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5242 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005243 return;
5244
5245 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5246 // however this is not necessarily true on taking any interrupt. Instruct
5247 // the backend to perform a realignment as part of the function prologue.
5248 llvm::AttrBuilder B;
5249 B.addStackAlignmentAttr(8);
5250 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5251 llvm::AttributeSet::get(CGM.getLLVMContext(),
5252 llvm::AttributeSet::FunctionIndex,
5253 B));
5254 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005255};
5256
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005257class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005258public:
5259 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5260 : ARMTargetCodeGenInfo(CGT, K) {}
5261
Eric Christopher162c91c2015-06-05 22:03:00 +00005262 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005263 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005264
5265 void getDependentLibraryOption(llvm::StringRef Lib,
5266 llvm::SmallString<24> &Opt) const override {
5267 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5268 }
5269
5270 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5271 llvm::SmallString<32> &Opt) const override {
5272 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5273 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005274};
5275
Eric Christopher162c91c2015-06-05 22:03:00 +00005276void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005277 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005278 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005279 addStackProbeSizeTargetAttribute(D, GV, CGM);
5280}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005281}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005282
Chris Lattner22326a12010-07-29 02:31:05 +00005283void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005284 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005285 FI.getReturnInfo() =
5286 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005287
Tim Northoverbc784d12015-02-24 17:22:40 +00005288 for (auto &I : FI.arguments())
5289 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005290
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005291 // Always honor user-specified calling convention.
5292 if (FI.getCallingConvention() != llvm::CallingConv::C)
5293 return;
5294
John McCall882987f2013-02-28 19:01:20 +00005295 llvm::CallingConv::ID cc = getRuntimeCC();
5296 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005297 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005298}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005299
John McCall882987f2013-02-28 19:01:20 +00005300/// Return the default calling convention that LLVM will use.
5301llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5302 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005303 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005304 return llvm::CallingConv::ARM_AAPCS_VFP;
5305 else if (isEABI())
5306 return llvm::CallingConv::ARM_AAPCS;
5307 else
5308 return llvm::CallingConv::ARM_APCS;
5309}
5310
5311/// Return the calling convention that our ABI would like us to use
5312/// as the C calling convention.
5313llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005314 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005315 case APCS: return llvm::CallingConv::ARM_APCS;
5316 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5317 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005318 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005319 }
John McCall882987f2013-02-28 19:01:20 +00005320 llvm_unreachable("bad ABI kind");
5321}
5322
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005323void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005324 assert(getRuntimeCC() == llvm::CallingConv::C);
5325
5326 // Don't muddy up the IR with a ton of explicit annotations if
5327 // they'd just match what LLVM will infer from the triple.
5328 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5329 if (abiCC != getLLVMDefaultCC())
5330 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005331
Tim Northover5627d392015-10-30 16:30:45 +00005332 // AAPCS apparently requires runtime support functions to be soft-float, but
5333 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5334 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5335 switch (getABIKind()) {
5336 case APCS:
5337 case AAPCS16_VFP:
5338 if (abiCC != getLLVMDefaultCC())
5339 BuiltinCC = abiCC;
5340 break;
5341 case AAPCS:
5342 case AAPCS_VFP:
5343 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5344 break;
5345 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005346}
5347
Tim Northoverbc784d12015-02-24 17:22:40 +00005348ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5349 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005350 // 6.1.2.1 The following argument types are VFP CPRCs:
5351 // A single-precision floating-point type (including promoted
5352 // half-precision types); A double-precision floating-point type;
5353 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5354 // with a Base Type of a single- or double-precision floating-point type,
5355 // 64-bit containerized vectors or 128-bit containerized vectors with one
5356 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005357 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005358
Reid Klecknerb1be6832014-11-15 01:41:41 +00005359 Ty = useFirstFieldIfTransparentUnion(Ty);
5360
Manman Renfef9e312012-10-16 19:18:39 +00005361 // Handle illegal vector types here.
5362 if (isIllegalVectorType(Ty)) {
5363 uint64_t Size = getContext().getTypeSize(Ty);
5364 if (Size <= 32) {
5365 llvm::Type *ResType =
5366 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005367 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005368 }
5369 if (Size == 64) {
5370 llvm::Type *ResType = llvm::VectorType::get(
5371 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005372 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005373 }
5374 if (Size == 128) {
5375 llvm::Type *ResType = llvm::VectorType::get(
5376 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005377 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005378 }
John McCall7f416cc2015-09-08 08:05:57 +00005379 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005380 }
5381
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005382 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5383 // unspecified. This is not done for OpenCL as it handles the half type
5384 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005385 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005386 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5387 llvm::Type::getFloatTy(getVMContext()) :
5388 llvm::Type::getInt32Ty(getVMContext());
5389 return ABIArgInfo::getDirect(ResType);
5390 }
5391
John McCalla1dee5302010-08-22 10:59:02 +00005392 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005393 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005394 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005395 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005396 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005397
Tim Northover5a1558e2014-11-07 22:30:50 +00005398 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5399 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005400 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005401
Oliver Stannard405bded2014-02-11 09:25:50 +00005402 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005403 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005404 }
Tim Northover1060eae2013-06-21 22:49:34 +00005405
Daniel Dunbar09d33622009-09-14 21:54:03 +00005406 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005407 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005408 return ABIArgInfo::getIgnore();
5409
Tim Northover5a1558e2014-11-07 22:30:50 +00005410 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005411 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5412 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005413 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005414 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005415 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005416 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005417 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005418 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005419 }
Tim Northover5627d392015-10-30 16:30:45 +00005420 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5421 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5422 // this convention even for a variadic function: the backend will use GPRs
5423 // if needed.
5424 const Type *Base = nullptr;
5425 uint64_t Members = 0;
5426 if (isHomogeneousAggregate(Ty, Base, Members)) {
5427 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5428 llvm::Type *Ty =
5429 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5430 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5431 }
5432 }
5433
5434 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5435 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5436 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5437 // bigger than 128-bits, they get placed in space allocated by the caller,
5438 // and a pointer is passed.
5439 return ABIArgInfo::getIndirect(
5440 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005441 }
5442
Manman Ren6c30e132012-08-13 21:23:55 +00005443 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005444 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5445 // most 8-byte. We realign the indirect argument if type alignment is bigger
5446 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005447 uint64_t ABIAlign = 4;
5448 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5449 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005450 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005451 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005452
Manman Ren8cd99812012-11-06 04:58:01 +00005453 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005454 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005455 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5456 /*ByVal=*/true,
5457 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005458 }
5459
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005460 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5461 // same size and alignment.
5462 if (getTarget().isRenderScriptTarget()) {
5463 return coerceToIntArray(Ty, getContext(), getVMContext());
5464 }
5465
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005466 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005467 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005468 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005469 // FIXME: Try to match the types of the arguments more accurately where
5470 // we can.
5471 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005472 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5473 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005474 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005475 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5476 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005477 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005478
Tim Northover5a1558e2014-11-07 22:30:50 +00005479 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005480}
5481
Chris Lattner458b2aa2010-07-29 02:16:43 +00005482static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005483 llvm::LLVMContext &VMContext) {
5484 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5485 // is called integer-like if its size is less than or equal to one word, and
5486 // the offset of each of its addressable sub-fields is zero.
5487
5488 uint64_t Size = Context.getTypeSize(Ty);
5489
5490 // Check that the type fits in a word.
5491 if (Size > 32)
5492 return false;
5493
5494 // FIXME: Handle vector types!
5495 if (Ty->isVectorType())
5496 return false;
5497
Daniel Dunbard53bac72009-09-14 02:20:34 +00005498 // Float types are never treated as "integer like".
5499 if (Ty->isRealFloatingType())
5500 return false;
5501
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005502 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005503 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005504 return true;
5505
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005506 // Small complex integer types are "integer like".
5507 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5508 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005509
5510 // Single element and zero sized arrays should be allowed, by the definition
5511 // above, but they are not.
5512
5513 // Otherwise, it must be a record type.
5514 const RecordType *RT = Ty->getAs<RecordType>();
5515 if (!RT) return false;
5516
5517 // Ignore records with flexible arrays.
5518 const RecordDecl *RD = RT->getDecl();
5519 if (RD->hasFlexibleArrayMember())
5520 return false;
5521
5522 // Check that all sub-fields are at offset 0, and are themselves "integer
5523 // like".
5524 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5525
5526 bool HadField = false;
5527 unsigned idx = 0;
5528 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5529 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005530 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005531
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005532 // Bit-fields are not addressable, we only need to verify they are "integer
5533 // like". We still have to disallow a subsequent non-bitfield, for example:
5534 // struct { int : 0; int x }
5535 // is non-integer like according to gcc.
5536 if (FD->isBitField()) {
5537 if (!RD->isUnion())
5538 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005539
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005540 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5541 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005542
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005543 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005544 }
5545
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005546 // Check if this field is at offset 0.
5547 if (Layout.getFieldOffset(idx) != 0)
5548 return false;
5549
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005550 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5551 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005552
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005553 // Only allow at most one field in a structure. This doesn't match the
5554 // wording above, but follows gcc in situations with a field following an
5555 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005556 if (!RD->isUnion()) {
5557 if (HadField)
5558 return false;
5559
5560 HadField = true;
5561 }
5562 }
5563
5564 return true;
5565}
5566
Oliver Stannard405bded2014-02-11 09:25:50 +00005567ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5568 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005569 bool IsEffectivelyAAPCS_VFP =
5570 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005571
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005572 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005573 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005574
Daniel Dunbar19964db2010-09-23 01:54:32 +00005575 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005576 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005577 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005578 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005579
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005580 // __fp16 gets returned as if it were an int or float, but with the top 16
5581 // bits unspecified. This is not done for OpenCL as it handles the half type
5582 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005583 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005584 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5585 llvm::Type::getFloatTy(getVMContext()) :
5586 llvm::Type::getInt32Ty(getVMContext());
5587 return ABIArgInfo::getDirect(ResType);
5588 }
5589
John McCalla1dee5302010-08-22 10:59:02 +00005590 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005591 // Treat an enum type as its underlying type.
5592 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5593 RetTy = EnumTy->getDecl()->getIntegerType();
5594
Tim Northover5a1558e2014-11-07 22:30:50 +00005595 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5596 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005597 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005598
5599 // Are we following APCS?
5600 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005601 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005602 return ABIArgInfo::getIgnore();
5603
Daniel Dunbareedf1512010-02-01 23:31:19 +00005604 // Complex types are all returned as packed integers.
5605 //
5606 // FIXME: Consider using 2 x vector types if the back end handles them
5607 // correctly.
5608 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005609 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5610 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005611
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005612 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005613 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005614 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005615 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005616 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005617 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005618 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005619 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5620 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005621 }
5622
5623 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005624 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005625 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005626
5627 // Otherwise this is an AAPCS variant.
5628
Chris Lattner458b2aa2010-07-29 02:16:43 +00005629 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005630 return ABIArgInfo::getIgnore();
5631
Bob Wilson1d9269a2011-11-02 04:51:36 +00005632 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005633 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005634 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005635 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005636 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005637 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005638 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005639 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005640 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005641 }
5642
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005643 // Aggregates <= 4 bytes are returned in r0; other aggregates
5644 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005645 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005646 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005647 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5648 // same size and alignment.
5649 if (getTarget().isRenderScriptTarget()) {
5650 return coerceToIntArray(RetTy, getContext(), getVMContext());
5651 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005652 if (getDataLayout().isBigEndian())
5653 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005654 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005655
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005656 // Return in the smallest viable integer type.
5657 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005658 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005659 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005660 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5661 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005662 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5663 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5664 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005665 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005666 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005667 }
5668
John McCall7f416cc2015-09-08 08:05:57 +00005669 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005670}
5671
Manman Renfef9e312012-10-16 19:18:39 +00005672/// isIllegalVector - check whether Ty is an illegal vector type.
5673bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005674 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5675 if (isAndroid()) {
5676 // Android shipped using Clang 3.1, which supported a slightly different
5677 // vector ABI. The primary differences were that 3-element vector types
5678 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5679 // accepts that legacy behavior for Android only.
5680 // Check whether VT is legal.
5681 unsigned NumElements = VT->getNumElements();
5682 // NumElements should be power of 2 or equal to 3.
5683 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5684 return true;
5685 } else {
5686 // Check whether VT is legal.
5687 unsigned NumElements = VT->getNumElements();
5688 uint64_t Size = getContext().getTypeSize(VT);
5689 // NumElements should be power of 2.
5690 if (!llvm::isPowerOf2_32(NumElements))
5691 return true;
5692 // Size should be greater than 32 bits.
5693 return Size <= 32;
5694 }
Manman Renfef9e312012-10-16 19:18:39 +00005695 }
5696 return false;
5697}
5698
Reid Klecknere9f6a712014-10-31 17:10:41 +00005699bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5700 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5701 // double, or 64-bit or 128-bit vectors.
5702 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5703 if (BT->getKind() == BuiltinType::Float ||
5704 BT->getKind() == BuiltinType::Double ||
5705 BT->getKind() == BuiltinType::LongDouble)
5706 return true;
5707 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5708 unsigned VecSize = getContext().getTypeSize(VT);
5709 if (VecSize == 64 || VecSize == 128)
5710 return true;
5711 }
5712 return false;
5713}
5714
5715bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5716 uint64_t Members) const {
5717 return Members <= 4;
5718}
5719
John McCall7f416cc2015-09-08 08:05:57 +00005720Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5721 QualType Ty) const {
5722 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005723
John McCall7f416cc2015-09-08 08:05:57 +00005724 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005725 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005726 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5727 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5728 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005729 }
5730
John McCall7f416cc2015-09-08 08:05:57 +00005731 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5732 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005733
John McCall7f416cc2015-09-08 08:05:57 +00005734 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5735 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005736 const Type *Base = nullptr;
5737 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005738 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5739 IsIndirect = true;
5740
Tim Northover5627d392015-10-30 16:30:45 +00005741 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5742 // allocated by the caller.
5743 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5744 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5745 !isHomogeneousAggregate(Ty, Base, Members)) {
5746 IsIndirect = true;
5747
John McCall7f416cc2015-09-08 08:05:57 +00005748 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005749 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5750 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005751 // Our callers should be prepared to handle an under-aligned address.
5752 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5753 getABIKind() == ARMABIInfo::AAPCS) {
5754 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5755 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005756 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5757 // ARMv7k allows type alignment up to 16 bytes.
5758 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5759 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005760 } else {
5761 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005762 }
John McCall7f416cc2015-09-08 08:05:57 +00005763 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005764
John McCall7f416cc2015-09-08 08:05:57 +00005765 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5766 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005767}
5768
Chris Lattner0cf24192010-06-28 20:05:43 +00005769//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005770// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005771//===----------------------------------------------------------------------===//
5772
5773namespace {
5774
Justin Holewinski83e96682012-05-24 17:43:12 +00005775class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005776public:
Justin Holewinski36837432013-03-30 14:38:24 +00005777 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005778
5779 ABIArgInfo classifyReturnType(QualType RetTy) const;
5780 ABIArgInfo classifyArgumentType(QualType Ty) const;
5781
Craig Topper4f12f102014-03-12 06:41:41 +00005782 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005783 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5784 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005785};
5786
Justin Holewinski83e96682012-05-24 17:43:12 +00005787class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005788public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005789 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5790 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005791
Eric Christopher162c91c2015-06-05 22:03:00 +00005792 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005793 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005794private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005795 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5796 // resulting MDNode to the nvvm.annotations MDNode.
5797 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005798};
5799
Justin Holewinski83e96682012-05-24 17:43:12 +00005800ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005801 if (RetTy->isVoidType())
5802 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005803
5804 // note: this is different from default ABI
5805 if (!RetTy->isScalarType())
5806 return ABIArgInfo::getDirect();
5807
5808 // Treat an enum type as its underlying type.
5809 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5810 RetTy = EnumTy->getDecl()->getIntegerType();
5811
5812 return (RetTy->isPromotableIntegerType() ?
5813 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005814}
5815
Justin Holewinski83e96682012-05-24 17:43:12 +00005816ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005817 // Treat an enum type as its underlying type.
5818 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5819 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005820
Eli Bendersky95338a02014-10-29 13:43:21 +00005821 // Return aggregates type as indirect by value
5822 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005823 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005824
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005825 return (Ty->isPromotableIntegerType() ?
5826 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005827}
5828
Justin Holewinski83e96682012-05-24 17:43:12 +00005829void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005830 if (!getCXXABI().classifyReturnType(FI))
5831 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005832 for (auto &I : FI.arguments())
5833 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005834
5835 // Always honor user-specified calling convention.
5836 if (FI.getCallingConvention() != llvm::CallingConv::C)
5837 return;
5838
John McCall882987f2013-02-28 19:01:20 +00005839 FI.setEffectiveCallingConvention(getRuntimeCC());
5840}
5841
John McCall7f416cc2015-09-08 08:05:57 +00005842Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5843 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005844 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005845}
5846
Justin Holewinski83e96682012-05-24 17:43:12 +00005847void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005848setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005849 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005850 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005851 if (!FD) return;
5852
5853 llvm::Function *F = cast<llvm::Function>(GV);
5854
5855 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005856 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005857 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005858 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005859 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005860 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005861 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5862 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005863 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005864 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005865 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005866 }
Justin Holewinski38031972011-10-05 17:58:44 +00005867
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005868 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005869 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005870 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005871 // __global__ functions cannot be called from the device, we do not
5872 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005873 if (FD->hasAttr<CUDAGlobalAttr>()) {
5874 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5875 addNVVMMetadata(F, "kernel", 1);
5876 }
Artem Belevich7093e402015-04-21 22:55:54 +00005877 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005878 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005879 llvm::APSInt MaxThreads(32);
5880 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5881 if (MaxThreads > 0)
5882 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5883
5884 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5885 // not specified in __launch_bounds__ or if the user specified a 0 value,
5886 // we don't have to add a PTX directive.
5887 if (Attr->getMinBlocks()) {
5888 llvm::APSInt MinBlocks(32);
5889 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5890 if (MinBlocks > 0)
5891 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5892 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005893 }
5894 }
Justin Holewinski38031972011-10-05 17:58:44 +00005895 }
5896}
5897
Eli Benderskye06a2c42014-04-15 16:57:05 +00005898void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5899 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005900 llvm::Module *M = F->getParent();
5901 llvm::LLVMContext &Ctx = M->getContext();
5902
5903 // Get "nvvm.annotations" metadata node
5904 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5905
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005906 llvm::Metadata *MDVals[] = {
5907 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5908 llvm::ConstantAsMetadata::get(
5909 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005910 // Append metadata to nvvm.annotations
5911 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5912}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005913}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005914
5915//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005916// SystemZ ABI Implementation
5917//===----------------------------------------------------------------------===//
5918
5919namespace {
5920
Bryan Chane3f1ed52016-04-28 13:56:43 +00005921class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005922 bool HasVector;
5923
Ulrich Weigand47445072013-05-06 16:26:41 +00005924public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005925 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00005926 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005927
5928 bool isPromotableIntegerType(QualType Ty) const;
5929 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005930 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005931 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005932 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005933
5934 ABIArgInfo classifyReturnType(QualType RetTy) const;
5935 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5936
Craig Topper4f12f102014-03-12 06:41:41 +00005937 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005938 if (!getCXXABI().classifyReturnType(FI))
5939 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005940 for (auto &I : FI.arguments())
5941 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005942 }
5943
John McCall7f416cc2015-09-08 08:05:57 +00005944 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5945 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00005946
5947 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5948 ArrayRef<llvm::Type*> scalars,
5949 bool asReturnValue) const override {
5950 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5951 }
Ulrich Weigand47445072013-05-06 16:26:41 +00005952};
5953
5954class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5955public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005956 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5957 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005958};
5959
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005960}
Ulrich Weigand47445072013-05-06 16:26:41 +00005961
5962bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5963 // Treat an enum type as its underlying type.
5964 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5965 Ty = EnumTy->getDecl()->getIntegerType();
5966
5967 // Promotable integer types are required to be promoted by the ABI.
5968 if (Ty->isPromotableIntegerType())
5969 return true;
5970
5971 // 32-bit values must also be promoted.
5972 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5973 switch (BT->getKind()) {
5974 case BuiltinType::Int:
5975 case BuiltinType::UInt:
5976 return true;
5977 default:
5978 return false;
5979 }
5980 return false;
5981}
5982
5983bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005984 return (Ty->isAnyComplexType() ||
5985 Ty->isVectorType() ||
5986 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005987}
5988
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005989bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5990 return (HasVector &&
5991 Ty->isVectorType() &&
5992 getContext().getTypeSize(Ty) <= 128);
5993}
5994
Ulrich Weigand47445072013-05-06 16:26:41 +00005995bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5996 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5997 switch (BT->getKind()) {
5998 case BuiltinType::Float:
5999 case BuiltinType::Double:
6000 return true;
6001 default:
6002 return false;
6003 }
6004
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006005 return false;
6006}
6007
6008QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006009 if (const RecordType *RT = Ty->getAsStructureType()) {
6010 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006011 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006012
6013 // If this is a C++ record, check the bases first.
6014 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006015 for (const auto &I : CXXRD->bases()) {
6016 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006017
6018 // Empty bases don't affect things either way.
6019 if (isEmptyRecord(getContext(), Base, true))
6020 continue;
6021
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006022 if (!Found.isNull())
6023 return Ty;
6024 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006025 }
6026
6027 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006028 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006029 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006030 // Unlike isSingleElementStruct(), empty structure and array fields
6031 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006032 if (getContext().getLangOpts().CPlusPlus &&
6033 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6034 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006035
6036 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006037 // Nested structures still do though.
6038 if (!Found.isNull())
6039 return Ty;
6040 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006041 }
6042
6043 // Unlike isSingleElementStruct(), trailing padding is allowed.
6044 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006045 if (!Found.isNull())
6046 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006047 }
6048
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006049 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006050}
6051
John McCall7f416cc2015-09-08 08:05:57 +00006052Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6053 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006054 // Assume that va_list type is correct; should be pointer to LLVM type:
6055 // struct {
6056 // i64 __gpr;
6057 // i64 __fpr;
6058 // i8 *__overflow_arg_area;
6059 // i8 *__reg_save_area;
6060 // };
6061
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006062 // Every non-vector argument occupies 8 bytes and is passed by preference
6063 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6064 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006065 Ty = getContext().getCanonicalType(Ty);
6066 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006067 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006068 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006069 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006070 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006071 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006072 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006073 CharUnits UnpaddedSize;
6074 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006075 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006076 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6077 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006078 } else {
6079 if (AI.getCoerceToType())
6080 ArgTy = AI.getCoerceToType();
6081 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006082 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006083 UnpaddedSize = TyInfo.first;
6084 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006085 }
John McCall7f416cc2015-09-08 08:05:57 +00006086 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6087 if (IsVector && UnpaddedSize > PaddedSize)
6088 PaddedSize = CharUnits::fromQuantity(16);
6089 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006090
John McCall7f416cc2015-09-08 08:05:57 +00006091 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006092
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006093 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006094 llvm::Value *PaddedSizeV =
6095 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006096
6097 if (IsVector) {
6098 // Work out the address of a vector argument on the stack.
6099 // Vector arguments are always passed in the high bits of a
6100 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006101 Address OverflowArgAreaPtr =
6102 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006103 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006104 Address OverflowArgArea =
6105 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6106 TyInfo.second);
6107 Address MemAddr =
6108 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006109
6110 // Update overflow_arg_area_ptr pointer
6111 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006112 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6113 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006114 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6115
6116 return MemAddr;
6117 }
6118
John McCall7f416cc2015-09-08 08:05:57 +00006119 assert(PaddedSize.getQuantity() == 8);
6120
6121 unsigned MaxRegs, RegCountField, RegSaveIndex;
6122 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006123 if (InFPRs) {
6124 MaxRegs = 4; // Maximum of 4 FPR arguments
6125 RegCountField = 1; // __fpr
6126 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006127 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006128 } else {
6129 MaxRegs = 5; // Maximum of 5 GPR arguments
6130 RegCountField = 0; // __gpr
6131 RegSaveIndex = 2; // save offset for r2
6132 RegPadding = Padding; // values are passed in the low bits of a GPR
6133 }
6134
John McCall7f416cc2015-09-08 08:05:57 +00006135 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6136 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6137 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006138 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006139 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6140 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006141 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006142
6143 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6144 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6145 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6146 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6147
6148 // Emit code to load the value if it was passed in registers.
6149 CGF.EmitBlock(InRegBlock);
6150
6151 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006152 llvm::Value *ScaledRegCount =
6153 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6154 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006155 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6156 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006157 llvm::Value *RegOffset =
6158 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006159 Address RegSaveAreaPtr =
6160 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6161 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006162 llvm::Value *RegSaveArea =
6163 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006164 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6165 "raw_reg_addr"),
6166 PaddedSize);
6167 Address RegAddr =
6168 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006169
6170 // Update the register count
6171 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6172 llvm::Value *NewRegCount =
6173 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6174 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6175 CGF.EmitBranch(ContBlock);
6176
6177 // Emit code to load the value if it was passed in memory.
6178 CGF.EmitBlock(InMemBlock);
6179
6180 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006181 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6182 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6183 Address OverflowArgArea =
6184 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6185 PaddedSize);
6186 Address RawMemAddr =
6187 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6188 Address MemAddr =
6189 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006190
6191 // Update overflow_arg_area_ptr pointer
6192 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006193 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6194 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006195 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6196 CGF.EmitBranch(ContBlock);
6197
6198 // Return the appropriate result.
6199 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006200 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6201 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006202
6203 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006204 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6205 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006206
6207 return ResAddr;
6208}
6209
Ulrich Weigand47445072013-05-06 16:26:41 +00006210ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6211 if (RetTy->isVoidType())
6212 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006213 if (isVectorArgumentType(RetTy))
6214 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006215 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006216 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006217 return (isPromotableIntegerType(RetTy) ?
6218 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6219}
6220
6221ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6222 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006223 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006224 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006225
6226 // Integers and enums are extended to full register width.
6227 if (isPromotableIntegerType(Ty))
6228 return ABIArgInfo::getExtend();
6229
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006230 // Handle vector types and vector-like structure types. Note that
6231 // as opposed to float-like structure types, we do not allow any
6232 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006233 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006234 QualType SingleElementTy = GetSingleElementType(Ty);
6235 if (isVectorArgumentType(SingleElementTy) &&
6236 getContext().getTypeSize(SingleElementTy) == Size)
6237 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6238
6239 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006240 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006241 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006242
6243 // Handle small structures.
6244 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6245 // Structures with flexible arrays have variable length, so really
6246 // fail the size test above.
6247 const RecordDecl *RD = RT->getDecl();
6248 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006249 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006250
6251 // The structure is passed as an unextended integer, a float, or a double.
6252 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006253 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006254 assert(Size == 32 || Size == 64);
6255 if (Size == 32)
6256 PassTy = llvm::Type::getFloatTy(getVMContext());
6257 else
6258 PassTy = llvm::Type::getDoubleTy(getVMContext());
6259 } else
6260 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6261 return ABIArgInfo::getDirect(PassTy);
6262 }
6263
6264 // Non-structure compounds are passed indirectly.
6265 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006266 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006267
Craig Topper8a13c412014-05-21 05:09:00 +00006268 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006269}
6270
6271//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006272// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006273//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006274
6275namespace {
6276
6277class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6278public:
Chris Lattner2b037972010-07-29 02:01:43 +00006279 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6280 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006281 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006282 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006283};
6284
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006285}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006286
Eric Christopher162c91c2015-06-05 22:03:00 +00006287void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006288 llvm::GlobalValue *GV,
6289 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006290 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006291 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6292 // Handle 'interrupt' attribute:
6293 llvm::Function *F = cast<llvm::Function>(GV);
6294
6295 // Step 1: Set ISR calling convention.
6296 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6297
6298 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006299 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006300
6301 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006302 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006303 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6304 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006305 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006306 }
6307}
6308
Chris Lattner0cf24192010-06-28 20:05:43 +00006309//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006310// MIPS ABI Implementation. This works for both little-endian and
6311// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006312//===----------------------------------------------------------------------===//
6313
John McCall943fae92010-05-27 06:19:26 +00006314namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006315class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006316 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006317 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6318 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006319 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006320 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006321 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006322 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006323public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006324 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006325 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006326 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006327
6328 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006329 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006330 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006331 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6332 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006333 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006334};
6335
John McCall943fae92010-05-27 06:19:26 +00006336class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006337 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006338public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006339 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6340 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006341 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006342
Craig Topper4f12f102014-03-12 06:41:41 +00006343 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006344 return 29;
6345 }
6346
Eric Christopher162c91c2015-06-05 22:03:00 +00006347 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006348 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006349 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006350 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006351 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006352 if (FD->hasAttr<Mips16Attr>()) {
6353 Fn->addFnAttr("mips16");
6354 }
6355 else if (FD->hasAttr<NoMips16Attr>()) {
6356 Fn->addFnAttr("nomips16");
6357 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006358
6359 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6360 if (!Attr)
6361 return;
6362
6363 const char *Kind;
6364 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006365 case MipsInterruptAttr::eic: Kind = "eic"; break;
6366 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6367 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6368 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6369 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6370 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6371 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6372 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6373 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6374 }
6375
6376 Fn->addFnAttr("interrupt", Kind);
6377
Reed Kotler373feca2013-01-16 17:10:28 +00006378 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006379
John McCall943fae92010-05-27 06:19:26 +00006380 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006381 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006382
Craig Topper4f12f102014-03-12 06:41:41 +00006383 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006384 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006385 }
John McCall943fae92010-05-27 06:19:26 +00006386};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006387}
John McCall943fae92010-05-27 06:19:26 +00006388
Eric Christopher7565e0d2015-05-29 23:09:49 +00006389void MipsABIInfo::CoerceToIntArgs(
6390 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006391 llvm::IntegerType *IntTy =
6392 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006393
6394 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6395 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6396 ArgList.push_back(IntTy);
6397
6398 // If necessary, add one more integer type to ArgList.
6399 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6400
6401 if (R)
6402 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006403}
6404
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006405// In N32/64, an aligned double precision floating point field is passed in
6406// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006407llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006408 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6409
6410 if (IsO32) {
6411 CoerceToIntArgs(TySize, ArgList);
6412 return llvm::StructType::get(getVMContext(), ArgList);
6413 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006414
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006415 if (Ty->isComplexType())
6416 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006417
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006418 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006419
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006420 // Unions/vectors are passed in integer registers.
6421 if (!RT || !RT->isStructureOrClassType()) {
6422 CoerceToIntArgs(TySize, ArgList);
6423 return llvm::StructType::get(getVMContext(), ArgList);
6424 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006425
6426 const RecordDecl *RD = RT->getDecl();
6427 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006428 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006429
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006430 uint64_t LastOffset = 0;
6431 unsigned idx = 0;
6432 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6433
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006434 // Iterate over fields in the struct/class and check if there are any aligned
6435 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006436 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6437 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006438 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006439 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6440
6441 if (!BT || BT->getKind() != BuiltinType::Double)
6442 continue;
6443
6444 uint64_t Offset = Layout.getFieldOffset(idx);
6445 if (Offset % 64) // Ignore doubles that are not aligned.
6446 continue;
6447
6448 // Add ((Offset - LastOffset) / 64) args of type i64.
6449 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6450 ArgList.push_back(I64);
6451
6452 // Add double type.
6453 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6454 LastOffset = Offset + 64;
6455 }
6456
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006457 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6458 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006459
6460 return llvm::StructType::get(getVMContext(), ArgList);
6461}
6462
Akira Hatanakaddd66342013-10-29 18:41:15 +00006463llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6464 uint64_t Offset) const {
6465 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006466 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006467
Akira Hatanakaddd66342013-10-29 18:41:15 +00006468 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006469}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006470
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006471ABIArgInfo
6472MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006473 Ty = useFirstFieldIfTransparentUnion(Ty);
6474
Akira Hatanaka1632af62012-01-09 19:31:25 +00006475 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006476 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006477 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006478
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006479 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6480 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006481 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6482 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006483
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006484 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006485 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006486 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006487 return ABIArgInfo::getIgnore();
6488
Mark Lacey3825e832013-10-06 01:33:34 +00006489 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006490 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006491 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006492 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006493
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006494 // If we have reached here, aggregates are passed directly by coercing to
6495 // another structure type. Padding is inserted if the offset of the
6496 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006497 ABIArgInfo ArgInfo =
6498 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6499 getPaddingType(OrigOffset, CurrOffset));
6500 ArgInfo.setInReg(true);
6501 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006502 }
6503
6504 // Treat an enum type as its underlying type.
6505 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6506 Ty = EnumTy->getDecl()->getIntegerType();
6507
Daniel Sanders5b445b32014-10-24 14:42:42 +00006508 // All integral types are promoted to the GPR width.
6509 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006510 return ABIArgInfo::getExtend();
6511
Akira Hatanakaddd66342013-10-29 18:41:15 +00006512 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006513 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006514}
6515
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006516llvm::Type*
6517MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006518 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006519 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006520
Akira Hatanakab6f74432012-02-09 18:49:26 +00006521 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006522 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006523 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6524 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006525
Akira Hatanakab6f74432012-02-09 18:49:26 +00006526 // N32/64 returns struct/classes in floating point registers if the
6527 // following conditions are met:
6528 // 1. The size of the struct/class is no larger than 128-bit.
6529 // 2. The struct/class has one or two fields all of which are floating
6530 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006531 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006532 //
6533 // Any other composite results are returned in integer registers.
6534 //
6535 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6536 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6537 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006538 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006539
Akira Hatanakab6f74432012-02-09 18:49:26 +00006540 if (!BT || !BT->isFloatingPoint())
6541 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006542
David Blaikie2d7c57e2012-04-30 02:36:29 +00006543 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006544 }
6545
6546 if (b == e)
6547 return llvm::StructType::get(getVMContext(), RTList,
6548 RD->hasAttr<PackedAttr>());
6549
6550 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006551 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006552 }
6553
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006554 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006555 return llvm::StructType::get(getVMContext(), RTList);
6556}
6557
Akira Hatanakab579fe52011-06-02 00:09:17 +00006558ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006559 uint64_t Size = getContext().getTypeSize(RetTy);
6560
Daniel Sandersed39f582014-09-04 13:28:14 +00006561 if (RetTy->isVoidType())
6562 return ABIArgInfo::getIgnore();
6563
6564 // O32 doesn't treat zero-sized structs differently from other structs.
6565 // However, N32/N64 ignores zero sized return values.
6566 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006567 return ABIArgInfo::getIgnore();
6568
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006569 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006570 if (Size <= 128) {
6571 if (RetTy->isAnyComplexType())
6572 return ABIArgInfo::getDirect();
6573
Daniel Sanderse5018b62014-09-04 15:05:39 +00006574 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006575 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006576 if (!IsO32 ||
6577 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6578 ABIArgInfo ArgInfo =
6579 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6580 ArgInfo.setInReg(true);
6581 return ArgInfo;
6582 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006583 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006584
John McCall7f416cc2015-09-08 08:05:57 +00006585 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006586 }
6587
6588 // Treat an enum type as its underlying type.
6589 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6590 RetTy = EnumTy->getDecl()->getIntegerType();
6591
6592 return (RetTy->isPromotableIntegerType() ?
6593 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6594}
6595
6596void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006597 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006598 if (!getCXXABI().classifyReturnType(FI))
6599 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006600
Eric Christopher7565e0d2015-05-29 23:09:49 +00006601 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006602 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006603
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006604 for (auto &I : FI.arguments())
6605 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006606}
6607
John McCall7f416cc2015-09-08 08:05:57 +00006608Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6609 QualType OrigTy) const {
6610 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006611
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006612 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6613 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006614 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006615 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006616 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006617 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006618 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006619 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006620 DidPromote = true;
6621 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6622 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006623 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006624
John McCall7f416cc2015-09-08 08:05:57 +00006625 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006626
John McCall7f416cc2015-09-08 08:05:57 +00006627 // The alignment of things in the argument area is never larger than
6628 // StackAlignInBytes.
6629 TyInfo.second =
6630 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6631
6632 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6633 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6634
6635 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6636 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6637
6638
6639 // If there was a promotion, "unpromote" into a temporary.
6640 // TODO: can we just use a pointer into a subset of the original slot?
6641 if (DidPromote) {
6642 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6643 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6644
6645 // Truncate down to the right width.
6646 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6647 : CGF.IntPtrTy);
6648 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6649 if (OrigTy->isPointerType())
6650 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6651
6652 CGF.Builder.CreateStore(V, Temp);
6653 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006654 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006655
John McCall7f416cc2015-09-08 08:05:57 +00006656 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006657}
6658
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006659bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6660 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006661
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006662 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6663 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6664 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006665
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006666 return false;
6667}
6668
John McCall943fae92010-05-27 06:19:26 +00006669bool
6670MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6671 llvm::Value *Address) const {
6672 // This information comes from gcc's implementation, which seems to
6673 // as canonical as it gets.
6674
John McCall943fae92010-05-27 06:19:26 +00006675 // Everything on MIPS is 4 bytes. Double-precision FP registers
6676 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006677 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006678
6679 // 0-31 are the general purpose registers, $0 - $31.
6680 // 32-63 are the floating-point registers, $f0 - $f31.
6681 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6682 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006683 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006684
6685 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6686 // They are one bit wide and ignored here.
6687
6688 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6689 // (coprocessor 1 is the FP unit)
6690 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6691 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6692 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006693 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006694 return false;
6695}
6696
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006697//===----------------------------------------------------------------------===//
6698// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006699// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006700// handling.
6701//===----------------------------------------------------------------------===//
6702
6703namespace {
6704
6705class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6706public:
6707 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6708 : DefaultTargetCodeGenInfo(CGT) {}
6709
Eric Christopher162c91c2015-06-05 22:03:00 +00006710 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006711 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006712};
6713
Eric Christopher162c91c2015-06-05 22:03:00 +00006714void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006715 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006716 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006717 if (!FD) return;
6718
6719 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006720
David Blaikiebbafb8a2012-03-11 07:00:24 +00006721 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006722 if (FD->hasAttr<OpenCLKernelAttr>()) {
6723 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006724 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006725 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6726 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006727 // Convert the reqd_work_group_size() attributes to metadata.
6728 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006729 llvm::NamedMDNode *OpenCLMetadata =
6730 M.getModule().getOrInsertNamedMetadata(
6731 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006732
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006733 SmallVector<llvm::Metadata *, 5> Operands;
6734 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006735
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006736 Operands.push_back(
6737 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6738 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6739 Operands.push_back(
6740 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6741 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6742 Operands.push_back(
6743 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6744 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006745
Eric Christopher7565e0d2015-05-29 23:09:49 +00006746 // Add a boolean constant operand for "required" (true) or "hint"
6747 // (false) for implementing the work_group_size_hint attr later.
6748 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006749 Operands.push_back(
6750 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006751 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6752 }
6753 }
6754 }
6755}
6756
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006757}
John McCall943fae92010-05-27 06:19:26 +00006758
Tony Linthicum76329bf2011-12-12 21:14:55 +00006759//===----------------------------------------------------------------------===//
6760// Hexagon ABI Implementation
6761//===----------------------------------------------------------------------===//
6762
6763namespace {
6764
6765class HexagonABIInfo : public ABIInfo {
6766
6767
6768public:
6769 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6770
6771private:
6772
6773 ABIArgInfo classifyReturnType(QualType RetTy) const;
6774 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6775
Craig Topper4f12f102014-03-12 06:41:41 +00006776 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006777
John McCall7f416cc2015-09-08 08:05:57 +00006778 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6779 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006780};
6781
6782class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6783public:
6784 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6785 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6786
Craig Topper4f12f102014-03-12 06:41:41 +00006787 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006788 return 29;
6789 }
6790};
6791
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006792}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006793
6794void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006795 if (!getCXXABI().classifyReturnType(FI))
6796 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006797 for (auto &I : FI.arguments())
6798 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006799}
6800
6801ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6802 if (!isAggregateTypeForABI(Ty)) {
6803 // Treat an enum type as its underlying type.
6804 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6805 Ty = EnumTy->getDecl()->getIntegerType();
6806
6807 return (Ty->isPromotableIntegerType() ?
6808 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6809 }
6810
6811 // Ignore empty records.
6812 if (isEmptyRecord(getContext(), Ty, true))
6813 return ABIArgInfo::getIgnore();
6814
Mark Lacey3825e832013-10-06 01:33:34 +00006815 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006816 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006817
6818 uint64_t Size = getContext().getTypeSize(Ty);
6819 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006820 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006821 // Pass in the smallest viable integer type.
6822 else if (Size > 32)
6823 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6824 else if (Size > 16)
6825 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6826 else if (Size > 8)
6827 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6828 else
6829 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6830}
6831
6832ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6833 if (RetTy->isVoidType())
6834 return ABIArgInfo::getIgnore();
6835
6836 // Large vector types should be returned via memory.
6837 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006838 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006839
6840 if (!isAggregateTypeForABI(RetTy)) {
6841 // Treat an enum type as its underlying type.
6842 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6843 RetTy = EnumTy->getDecl()->getIntegerType();
6844
6845 return (RetTy->isPromotableIntegerType() ?
6846 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6847 }
6848
Tony Linthicum76329bf2011-12-12 21:14:55 +00006849 if (isEmptyRecord(getContext(), RetTy, true))
6850 return ABIArgInfo::getIgnore();
6851
6852 // Aggregates <= 8 bytes are returned in r0; other aggregates
6853 // are returned indirectly.
6854 uint64_t Size = getContext().getTypeSize(RetTy);
6855 if (Size <= 64) {
6856 // Return in the smallest viable integer type.
6857 if (Size <= 8)
6858 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6859 if (Size <= 16)
6860 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6861 if (Size <= 32)
6862 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6863 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6864 }
6865
John McCall7f416cc2015-09-08 08:05:57 +00006866 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006867}
6868
John McCall7f416cc2015-09-08 08:05:57 +00006869Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6870 QualType Ty) const {
6871 // FIXME: Someone needs to audit that this handle alignment correctly.
6872 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6873 getContext().getTypeInfoInChars(Ty),
6874 CharUnits::fromQuantity(4),
6875 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006876}
6877
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006878//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006879// Lanai ABI Implementation
6880//===----------------------------------------------------------------------===//
6881
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006882namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006883class LanaiABIInfo : public DefaultABIInfo {
6884public:
6885 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6886
6887 bool shouldUseInReg(QualType Ty, CCState &State) const;
6888
6889 void computeInfo(CGFunctionInfo &FI) const override {
6890 CCState State(FI.getCallingConvention());
6891 // Lanai uses 4 registers to pass arguments unless the function has the
6892 // regparm attribute set.
6893 if (FI.getHasRegParm()) {
6894 State.FreeRegs = FI.getRegParm();
6895 } else {
6896 State.FreeRegs = 4;
6897 }
6898
6899 if (!getCXXABI().classifyReturnType(FI))
6900 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6901 for (auto &I : FI.arguments())
6902 I.info = classifyArgumentType(I.type, State);
6903 }
6904
Jacques Pienaare74d9132016-04-26 00:09:29 +00006905 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006906 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6907};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006908} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006909
6910bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6911 unsigned Size = getContext().getTypeSize(Ty);
6912 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6913
6914 if (SizeInRegs == 0)
6915 return false;
6916
6917 if (SizeInRegs > State.FreeRegs) {
6918 State.FreeRegs = 0;
6919 return false;
6920 }
6921
6922 State.FreeRegs -= SizeInRegs;
6923
6924 return true;
6925}
6926
Jacques Pienaare74d9132016-04-26 00:09:29 +00006927ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6928 CCState &State) const {
6929 if (!ByVal) {
6930 if (State.FreeRegs) {
6931 --State.FreeRegs; // Non-byval indirects just use one pointer.
6932 return getNaturalAlignIndirectInReg(Ty);
6933 }
6934 return getNaturalAlignIndirect(Ty, false);
6935 }
6936
6937 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00006938 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00006939 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6940 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6941 /*Realign=*/TypeAlign >
6942 MinABIStackAlignInBytes);
6943}
6944
Jacques Pienaard964cc22016-03-28 21:02:54 +00006945ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6946 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006947 // Check with the C++ ABI first.
6948 const RecordType *RT = Ty->getAs<RecordType>();
6949 if (RT) {
6950 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6951 if (RAA == CGCXXABI::RAA_Indirect) {
6952 return getIndirectResult(Ty, /*ByVal=*/false, State);
6953 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6954 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6955 }
6956 }
6957
6958 if (isAggregateTypeForABI(Ty)) {
6959 // Structures with flexible arrays are always indirect.
6960 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6961 return getIndirectResult(Ty, /*ByVal=*/true, State);
6962
6963 // Ignore empty structs/unions.
6964 if (isEmptyRecord(getContext(), Ty, true))
6965 return ABIArgInfo::getIgnore();
6966
6967 llvm::LLVMContext &LLVMContext = getVMContext();
6968 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6969 if (SizeInRegs <= State.FreeRegs) {
6970 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6971 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6972 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6973 State.FreeRegs -= SizeInRegs;
6974 return ABIArgInfo::getDirectInReg(Result);
6975 } else {
6976 State.FreeRegs = 0;
6977 }
6978 return getIndirectResult(Ty, true, State);
6979 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00006980
6981 // Treat an enum type as its underlying type.
6982 if (const auto *EnumTy = Ty->getAs<EnumType>())
6983 Ty = EnumTy->getDecl()->getIntegerType();
6984
Jacques Pienaare74d9132016-04-26 00:09:29 +00006985 bool InReg = shouldUseInReg(Ty, State);
6986 if (Ty->isPromotableIntegerType()) {
6987 if (InReg)
6988 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006989 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00006990 }
6991 if (InReg)
6992 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006993 return ABIArgInfo::getDirect();
6994}
6995
6996namespace {
6997class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6998public:
6999 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7000 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7001};
7002}
7003
7004//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007005// AMDGPU ABI Implementation
7006//===----------------------------------------------------------------------===//
7007
7008namespace {
7009
Matt Arsenault88d7da02016-08-22 19:25:59 +00007010class AMDGPUABIInfo final : public DefaultABIInfo {
7011public:
7012 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7013
7014private:
7015 ABIArgInfo classifyArgumentType(QualType Ty) const;
7016
7017 void computeInfo(CGFunctionInfo &FI) const override;
7018};
7019
7020void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7021 if (!getCXXABI().classifyReturnType(FI))
7022 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7023
7024 unsigned CC = FI.getCallingConvention();
7025 for (auto &Arg : FI.arguments())
7026 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7027 Arg.info = classifyArgumentType(Arg.type);
7028 else
7029 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7030}
7031
7032/// \brief Classify argument of given type \p Ty.
7033ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7034 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7035 if (!StrTy) {
7036 return DefaultABIInfo::classifyArgumentType(Ty);
7037 }
7038
7039 // Coerce single element structs to its element.
7040 if (StrTy->getNumElements() == 1) {
7041 return ABIArgInfo::getDirect();
7042 }
7043
7044 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7045 // individual elements, which confuses the Clover OpenCL backend; therefore we
7046 // have to set it to false here. Other args of getDirect() are just defaults.
7047 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7048}
7049
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007050class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7051public:
7052 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007053 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007054 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007055 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007056 unsigned getOpenCLKernelCallingConv() const override;
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007057};
7058
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007059}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007060
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007061static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7062
Eric Christopher162c91c2015-06-05 22:03:00 +00007063void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007064 const Decl *D,
7065 llvm::GlobalValue *GV,
7066 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007067 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007068 if (!FD)
7069 return;
7070
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007071 llvm::Function *F = cast<llvm::Function>(GV);
7072
7073 if (const auto *Attr = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7074 unsigned Min = Attr->getMin();
7075 unsigned Max = Attr->getMax();
7076
7077 if (Min != 0) {
7078 assert(Min <= Max && "Min must be less than or equal Max");
7079
7080 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7081 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7082 } else
7083 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007084 }
7085
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007086 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7087 unsigned Min = Attr->getMin();
7088 unsigned Max = Attr->getMax();
7089
7090 if (Min != 0) {
7091 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7092
7093 std::string AttrVal = llvm::utostr(Min);
7094 if (Max != 0)
7095 AttrVal = AttrVal + "," + llvm::utostr(Max);
7096 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7097 } else
7098 assert(Max == 0 && "Max must be zero");
7099 }
7100
7101 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007102 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007103
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007104 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007105 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7106 }
7107
7108 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7109 uint32_t NumVGPR = Attr->getNumVGPR();
7110
7111 if (NumVGPR != 0)
7112 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007113 }
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007114
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007115 appendOpenCLVersionMD(M);
7116}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007117
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007118unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7119 return llvm::CallingConv::AMDGPU_KERNEL;
7120}
7121
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007122//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007123// SPARC v8 ABI Implementation.
7124// Based on the SPARC Compliance Definition version 2.4.1.
7125//
7126// Ensures that complex values are passed in registers.
7127//
7128namespace {
7129class SparcV8ABIInfo : public DefaultABIInfo {
7130public:
7131 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7132
7133private:
7134 ABIArgInfo classifyReturnType(QualType RetTy) const;
7135 void computeInfo(CGFunctionInfo &FI) const override;
7136};
7137} // end anonymous namespace
7138
7139
7140ABIArgInfo
7141SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7142 if (Ty->isAnyComplexType()) {
7143 return ABIArgInfo::getDirect();
7144 }
7145 else {
7146 return DefaultABIInfo::classifyReturnType(Ty);
7147 }
7148}
7149
7150void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7151
7152 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7153 for (auto &Arg : FI.arguments())
7154 Arg.info = classifyArgumentType(Arg.type);
7155}
7156
7157namespace {
7158class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7159public:
7160 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7161 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7162};
7163} // end anonymous namespace
7164
7165//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007166// SPARC v9 ABI Implementation.
7167// Based on the SPARC Compliance Definition version 2.4.1.
7168//
7169// Function arguments a mapped to a nominal "parameter array" and promoted to
7170// registers depending on their type. Each argument occupies 8 or 16 bytes in
7171// the array, structs larger than 16 bytes are passed indirectly.
7172//
7173// One case requires special care:
7174//
7175// struct mixed {
7176// int i;
7177// float f;
7178// };
7179//
7180// When a struct mixed is passed by value, it only occupies 8 bytes in the
7181// parameter array, but the int is passed in an integer register, and the float
7182// is passed in a floating point register. This is represented as two arguments
7183// with the LLVM IR inreg attribute:
7184//
7185// declare void f(i32 inreg %i, float inreg %f)
7186//
7187// The code generator will only allocate 4 bytes from the parameter array for
7188// the inreg arguments. All other arguments are allocated a multiple of 8
7189// bytes.
7190//
7191namespace {
7192class SparcV9ABIInfo : public ABIInfo {
7193public:
7194 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7195
7196private:
7197 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007198 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007199 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7200 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007201
7202 // Coercion type builder for structs passed in registers. The coercion type
7203 // serves two purposes:
7204 //
7205 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7206 // in registers.
7207 // 2. Expose aligned floating point elements as first-level elements, so the
7208 // code generator knows to pass them in floating point registers.
7209 //
7210 // We also compute the InReg flag which indicates that the struct contains
7211 // aligned 32-bit floats.
7212 //
7213 struct CoerceBuilder {
7214 llvm::LLVMContext &Context;
7215 const llvm::DataLayout &DL;
7216 SmallVector<llvm::Type*, 8> Elems;
7217 uint64_t Size;
7218 bool InReg;
7219
7220 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7221 : Context(c), DL(dl), Size(0), InReg(false) {}
7222
7223 // Pad Elems with integers until Size is ToSize.
7224 void pad(uint64_t ToSize) {
7225 assert(ToSize >= Size && "Cannot remove elements");
7226 if (ToSize == Size)
7227 return;
7228
7229 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007230 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007231 if (Aligned > Size && Aligned <= ToSize) {
7232 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7233 Size = Aligned;
7234 }
7235
7236 // Add whole 64-bit words.
7237 while (Size + 64 <= ToSize) {
7238 Elems.push_back(llvm::Type::getInt64Ty(Context));
7239 Size += 64;
7240 }
7241
7242 // Final in-word padding.
7243 if (Size < ToSize) {
7244 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7245 Size = ToSize;
7246 }
7247 }
7248
7249 // Add a floating point element at Offset.
7250 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7251 // Unaligned floats are treated as integers.
7252 if (Offset % Bits)
7253 return;
7254 // The InReg flag is only required if there are any floats < 64 bits.
7255 if (Bits < 64)
7256 InReg = true;
7257 pad(Offset);
7258 Elems.push_back(Ty);
7259 Size = Offset + Bits;
7260 }
7261
7262 // Add a struct type to the coercion type, starting at Offset (in bits).
7263 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7264 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7265 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7266 llvm::Type *ElemTy = StrTy->getElementType(i);
7267 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7268 switch (ElemTy->getTypeID()) {
7269 case llvm::Type::StructTyID:
7270 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7271 break;
7272 case llvm::Type::FloatTyID:
7273 addFloat(ElemOffset, ElemTy, 32);
7274 break;
7275 case llvm::Type::DoubleTyID:
7276 addFloat(ElemOffset, ElemTy, 64);
7277 break;
7278 case llvm::Type::FP128TyID:
7279 addFloat(ElemOffset, ElemTy, 128);
7280 break;
7281 case llvm::Type::PointerTyID:
7282 if (ElemOffset % 64 == 0) {
7283 pad(ElemOffset);
7284 Elems.push_back(ElemTy);
7285 Size += 64;
7286 }
7287 break;
7288 default:
7289 break;
7290 }
7291 }
7292 }
7293
7294 // Check if Ty is a usable substitute for the coercion type.
7295 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007296 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007297 }
7298
7299 // Get the coercion type as a literal struct type.
7300 llvm::Type *getType() const {
7301 if (Elems.size() == 1)
7302 return Elems.front();
7303 else
7304 return llvm::StructType::get(Context, Elems);
7305 }
7306 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007307};
7308} // end anonymous namespace
7309
7310ABIArgInfo
7311SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7312 if (Ty->isVoidType())
7313 return ABIArgInfo::getIgnore();
7314
7315 uint64_t Size = getContext().getTypeSize(Ty);
7316
7317 // Anything too big to fit in registers is passed with an explicit indirect
7318 // pointer / sret pointer.
7319 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007320 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007321
7322 // Treat an enum type as its underlying type.
7323 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7324 Ty = EnumTy->getDecl()->getIntegerType();
7325
7326 // Integer types smaller than a register are extended.
7327 if (Size < 64 && Ty->isIntegerType())
7328 return ABIArgInfo::getExtend();
7329
7330 // Other non-aggregates go in registers.
7331 if (!isAggregateTypeForABI(Ty))
7332 return ABIArgInfo::getDirect();
7333
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007334 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7335 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7336 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007337 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007338
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007339 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007340 // Build a coercion type from the LLVM struct type.
7341 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7342 if (!StrTy)
7343 return ABIArgInfo::getDirect();
7344
7345 CoerceBuilder CB(getVMContext(), getDataLayout());
7346 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007347 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007348
7349 // Try to use the original type for coercion.
7350 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7351
7352 if (CB.InReg)
7353 return ABIArgInfo::getDirectInReg(CoerceTy);
7354 else
7355 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007356}
7357
John McCall7f416cc2015-09-08 08:05:57 +00007358Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7359 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007360 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7361 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7362 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7363 AI.setCoerceToType(ArgTy);
7364
John McCall7f416cc2015-09-08 08:05:57 +00007365 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007366
John McCall7f416cc2015-09-08 08:05:57 +00007367 CGBuilderTy &Builder = CGF.Builder;
7368 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7369 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7370
7371 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7372
7373 Address ArgAddr = Address::invalid();
7374 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007375 switch (AI.getKind()) {
7376 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007377 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007378 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007379 llvm_unreachable("Unsupported ABI kind for va_arg");
7380
John McCall7f416cc2015-09-08 08:05:57 +00007381 case ABIArgInfo::Extend: {
7382 Stride = SlotSize;
7383 CharUnits Offset = SlotSize - TypeInfo.first;
7384 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007385 break;
John McCall7f416cc2015-09-08 08:05:57 +00007386 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007387
John McCall7f416cc2015-09-08 08:05:57 +00007388 case ABIArgInfo::Direct: {
7389 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007390 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007391 ArgAddr = Addr;
7392 break;
John McCall7f416cc2015-09-08 08:05:57 +00007393 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007394
7395 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007396 Stride = SlotSize;
7397 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7398 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7399 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007400 break;
7401
7402 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007403 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007404 }
7405
7406 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007407 llvm::Value *NextPtr =
7408 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7409 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007410
John McCall7f416cc2015-09-08 08:05:57 +00007411 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007412}
7413
7414void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7415 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007416 for (auto &I : FI.arguments())
7417 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007418}
7419
7420namespace {
7421class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7422public:
7423 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7424 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007425
Craig Topper4f12f102014-03-12 06:41:41 +00007426 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007427 return 14;
7428 }
7429
7430 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007431 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007432};
7433} // end anonymous namespace
7434
Roman Divackyf02c9942014-02-24 18:46:27 +00007435bool
7436SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7437 llvm::Value *Address) const {
7438 // This is calculated from the LLVM and GCC tables and verified
7439 // against gcc output. AFAIK all ABIs use the same encoding.
7440
7441 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7442
7443 llvm::IntegerType *i8 = CGF.Int8Ty;
7444 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7445 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7446
7447 // 0-31: the 8-byte general-purpose registers
7448 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7449
7450 // 32-63: f0-31, the 4-byte floating-point registers
7451 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7452
7453 // Y = 64
7454 // PSR = 65
7455 // WIM = 66
7456 // TBR = 67
7457 // PC = 68
7458 // NPC = 69
7459 // FSR = 70
7460 // CSR = 71
7461 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007462
Roman Divackyf02c9942014-02-24 18:46:27 +00007463 // 72-87: d0-15, the 8-byte floating-point registers
7464 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7465
7466 return false;
7467}
7468
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007469
Robert Lytton0e076492013-08-13 09:43:10 +00007470//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007471// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007472//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007473
Robert Lytton0e076492013-08-13 09:43:10 +00007474namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007475
7476/// A SmallStringEnc instance is used to build up the TypeString by passing
7477/// it by reference between functions that append to it.
7478typedef llvm::SmallString<128> SmallStringEnc;
7479
7480/// TypeStringCache caches the meta encodings of Types.
7481///
7482/// The reason for caching TypeStrings is two fold:
7483/// 1. To cache a type's encoding for later uses;
7484/// 2. As a means to break recursive member type inclusion.
7485///
7486/// A cache Entry can have a Status of:
7487/// NonRecursive: The type encoding is not recursive;
7488/// Recursive: The type encoding is recursive;
7489/// Incomplete: An incomplete TypeString;
7490/// IncompleteUsed: An incomplete TypeString that has been used in a
7491/// Recursive type encoding.
7492///
7493/// A NonRecursive entry will have all of its sub-members expanded as fully
7494/// as possible. Whilst it may contain types which are recursive, the type
7495/// itself is not recursive and thus its encoding may be safely used whenever
7496/// the type is encountered.
7497///
7498/// A Recursive entry will have all of its sub-members expanded as fully as
7499/// possible. The type itself is recursive and it may contain other types which
7500/// are recursive. The Recursive encoding must not be used during the expansion
7501/// of a recursive type's recursive branch. For simplicity the code uses
7502/// IncompleteCount to reject all usage of Recursive encodings for member types.
7503///
7504/// An Incomplete entry is always a RecordType and only encodes its
7505/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7506/// are placed into the cache during type expansion as a means to identify and
7507/// handle recursive inclusion of types as sub-members. If there is recursion
7508/// the entry becomes IncompleteUsed.
7509///
7510/// During the expansion of a RecordType's members:
7511///
7512/// If the cache contains a NonRecursive encoding for the member type, the
7513/// cached encoding is used;
7514///
7515/// If the cache contains a Recursive encoding for the member type, the
7516/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7517///
7518/// If the member is a RecordType, an Incomplete encoding is placed into the
7519/// cache to break potential recursive inclusion of itself as a sub-member;
7520///
7521/// Once a member RecordType has been expanded, its temporary incomplete
7522/// entry is removed from the cache. If a Recursive encoding was swapped out
7523/// it is swapped back in;
7524///
7525/// If an incomplete entry is used to expand a sub-member, the incomplete
7526/// entry is marked as IncompleteUsed. The cache keeps count of how many
7527/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7528///
7529/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7530/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7531/// Else the member is part of a recursive type and thus the recursion has
7532/// been exited too soon for the encoding to be correct for the member.
7533///
7534class TypeStringCache {
7535 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7536 struct Entry {
7537 std::string Str; // The encoded TypeString for the type.
7538 enum Status State; // Information about the encoding in 'Str'.
7539 std::string Swapped; // A temporary place holder for a Recursive encoding
7540 // during the expansion of RecordType's members.
7541 };
7542 std::map<const IdentifierInfo *, struct Entry> Map;
7543 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7544 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7545public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007546 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007547 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7548 bool removeIncomplete(const IdentifierInfo *ID);
7549 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7550 bool IsRecursive);
7551 StringRef lookupStr(const IdentifierInfo *ID);
7552};
7553
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007554/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007555/// FieldEncoding is a helper for this ordering process.
7556class FieldEncoding {
7557 bool HasName;
7558 std::string Enc;
7559public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007560 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007561 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007562 bool operator<(const FieldEncoding &rhs) const {
7563 if (HasName != rhs.HasName) return HasName;
7564 return Enc < rhs.Enc;
7565 }
7566};
7567
Robert Lytton7d1db152013-08-19 09:46:39 +00007568class XCoreABIInfo : public DefaultABIInfo {
7569public:
7570 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007571 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7572 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007573};
7574
Robert Lyttond21e2d72014-03-03 13:45:29 +00007575class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007576 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007577public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007578 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007579 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007580 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7581 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007582};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007583
Robert Lytton2d196952013-10-11 10:29:34 +00007584} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007585
James Y Knight29b5f082016-02-24 02:59:33 +00007586// TODO: this implementation is likely now redundant with the default
7587// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007588Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7589 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007590 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007591
Robert Lytton2d196952013-10-11 10:29:34 +00007592 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007593 CharUnits SlotSize = CharUnits::fromQuantity(4);
7594 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007595
Robert Lytton2d196952013-10-11 10:29:34 +00007596 // Handle the argument.
7597 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007598 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007599 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7600 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7601 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007602 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007603
7604 Address Val = Address::invalid();
7605 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007606 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007607 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007608 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007609 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007610 llvm_unreachable("Unsupported ABI kind for va_arg");
7611 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007612 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7613 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007614 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007615 case ABIArgInfo::Extend:
7616 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007617 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7618 ArgSize = CharUnits::fromQuantity(
7619 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007620 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007621 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007622 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007623 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7624 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7625 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007626 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007627 }
Robert Lytton2d196952013-10-11 10:29:34 +00007628
7629 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007630 if (!ArgSize.isZero()) {
7631 llvm::Value *APN =
7632 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7633 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007634 }
John McCall7f416cc2015-09-08 08:05:57 +00007635
Robert Lytton2d196952013-10-11 10:29:34 +00007636 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007637}
Robert Lytton0e076492013-08-13 09:43:10 +00007638
Robert Lytton844aeeb2014-05-02 09:33:20 +00007639/// During the expansion of a RecordType, an incomplete TypeString is placed
7640/// into the cache as a means to identify and break recursion.
7641/// If there is a Recursive encoding in the cache, it is swapped out and will
7642/// be reinserted by removeIncomplete().
7643/// All other types of encoding should have been used rather than arriving here.
7644void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7645 std::string StubEnc) {
7646 if (!ID)
7647 return;
7648 Entry &E = Map[ID];
7649 assert( (E.Str.empty() || E.State == Recursive) &&
7650 "Incorrectly use of addIncomplete");
7651 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7652 E.Swapped.swap(E.Str); // swap out the Recursive
7653 E.Str.swap(StubEnc);
7654 E.State = Incomplete;
7655 ++IncompleteCount;
7656}
7657
7658/// Once the RecordType has been expanded, the temporary incomplete TypeString
7659/// must be removed from the cache.
7660/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7661/// Returns true if the RecordType was defined recursively.
7662bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7663 if (!ID)
7664 return false;
7665 auto I = Map.find(ID);
7666 assert(I != Map.end() && "Entry not present");
7667 Entry &E = I->second;
7668 assert( (E.State == Incomplete ||
7669 E.State == IncompleteUsed) &&
7670 "Entry must be an incomplete type");
7671 bool IsRecursive = false;
7672 if (E.State == IncompleteUsed) {
7673 // We made use of our Incomplete encoding, thus we are recursive.
7674 IsRecursive = true;
7675 --IncompleteUsedCount;
7676 }
7677 if (E.Swapped.empty())
7678 Map.erase(I);
7679 else {
7680 // Swap the Recursive back.
7681 E.Swapped.swap(E.Str);
7682 E.Swapped.clear();
7683 E.State = Recursive;
7684 }
7685 --IncompleteCount;
7686 return IsRecursive;
7687}
7688
7689/// Add the encoded TypeString to the cache only if it is NonRecursive or
7690/// Recursive (viz: all sub-members were expanded as fully as possible).
7691void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7692 bool IsRecursive) {
7693 if (!ID || IncompleteUsedCount)
7694 return; // No key or it is is an incomplete sub-type so don't add.
7695 Entry &E = Map[ID];
7696 if (IsRecursive && !E.Str.empty()) {
7697 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7698 "This is not the same Recursive entry");
7699 // The parent container was not recursive after all, so we could have used
7700 // this Recursive sub-member entry after all, but we assumed the worse when
7701 // we started viz: IncompleteCount!=0.
7702 return;
7703 }
7704 assert(E.Str.empty() && "Entry already present");
7705 E.Str = Str.str();
7706 E.State = IsRecursive? Recursive : NonRecursive;
7707}
7708
7709/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7710/// are recursively expanding a type (IncompleteCount != 0) and the cached
7711/// encoding is Recursive, return an empty StringRef.
7712StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7713 if (!ID)
7714 return StringRef(); // We have no key.
7715 auto I = Map.find(ID);
7716 if (I == Map.end())
7717 return StringRef(); // We have no encoding.
7718 Entry &E = I->second;
7719 if (E.State == Recursive && IncompleteCount)
7720 return StringRef(); // We don't use Recursive encodings for member types.
7721
7722 if (E.State == Incomplete) {
7723 // The incomplete type is being used to break out of recursion.
7724 E.State = IncompleteUsed;
7725 ++IncompleteUsedCount;
7726 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007727 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007728}
7729
7730/// The XCore ABI includes a type information section that communicates symbol
7731/// type information to the linker. The linker uses this information to verify
7732/// safety/correctness of things such as array bound and pointers et al.
7733/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7734/// This type information (TypeString) is emitted into meta data for all global
7735/// symbols: definitions, declarations, functions & variables.
7736///
7737/// The TypeString carries type, qualifier, name, size & value details.
7738/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007739/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007740/// The output is tested by test/CodeGen/xcore-stringtype.c.
7741///
7742static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7743 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7744
7745/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7746void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7747 CodeGen::CodeGenModule &CGM) const {
7748 SmallStringEnc Enc;
7749 if (getTypeString(Enc, D, CGM, TSC)) {
7750 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00007751 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
7752 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007753 llvm::NamedMDNode *MD =
7754 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7755 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7756 }
7757}
7758
Xiuli Pan972bea82016-03-24 03:57:17 +00007759//===----------------------------------------------------------------------===//
7760// SPIR ABI Implementation
7761//===----------------------------------------------------------------------===//
7762
7763namespace {
7764class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7765public:
7766 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7767 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7768 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7769 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007770 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00007771};
7772} // End anonymous namespace.
7773
7774/// Emit SPIR specific metadata: OpenCL and SPIR version.
7775void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7776 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00007777 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7778 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7779 llvm::Module &M = CGM.getModule();
7780 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7781 // opencl.spir.version named metadata.
7782 llvm::Metadata *SPIRVerElts[] = {
7783 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7784 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7785 llvm::NamedMDNode *SPIRVerMD =
7786 M.getOrInsertNamedMetadata("opencl.spir.version");
7787 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007788 appendOpenCLVersionMD(CGM);
7789}
7790
Matt Arsenault8afb5cd2016-09-07 07:07:59 +00007791static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007792 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7793 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7794 llvm::Module &M = CGM.getModule();
Xiuli Pan972bea82016-03-24 03:57:17 +00007795 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7796 // opencl.ocl.version named metadata node.
7797 llvm::Metadata *OCLVerElts[] = {
7798 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7799 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7800 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7801 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7802 llvm::NamedMDNode *OCLVerMD =
7803 M.getOrInsertNamedMetadata("opencl.ocl.version");
7804 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7805}
7806
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007807unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7808 return llvm::CallingConv::SPIR_KERNEL;
7809}
7810
Robert Lytton844aeeb2014-05-02 09:33:20 +00007811static bool appendType(SmallStringEnc &Enc, QualType QType,
7812 const CodeGen::CodeGenModule &CGM,
7813 TypeStringCache &TSC);
7814
7815/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007816/// Builds a SmallVector containing the encoded field types in declaration
7817/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007818static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7819 const RecordDecl *RD,
7820 const CodeGen::CodeGenModule &CGM,
7821 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007822 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007823 SmallStringEnc Enc;
7824 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007825 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007826 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007827 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007828 Enc += "b(";
7829 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007830 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007831 Enc += ':';
7832 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007833 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007834 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007835 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007836 Enc += ')';
7837 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007838 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007839 }
7840 return true;
7841}
7842
7843/// Appends structure and union types to Enc and adds encoding to cache.
7844/// Recursively calls appendType (via extractFieldType) for each field.
7845/// Union types have their fields ordered according to the ABI.
7846static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7847 const CodeGen::CodeGenModule &CGM,
7848 TypeStringCache &TSC, const IdentifierInfo *ID) {
7849 // Append the cached TypeString if we have one.
7850 StringRef TypeString = TSC.lookupStr(ID);
7851 if (!TypeString.empty()) {
7852 Enc += TypeString;
7853 return true;
7854 }
7855
7856 // Start to emit an incomplete TypeString.
7857 size_t Start = Enc.size();
7858 Enc += (RT->isUnionType()? 'u' : 's');
7859 Enc += '(';
7860 if (ID)
7861 Enc += ID->getName();
7862 Enc += "){";
7863
7864 // We collect all encoded fields and order as necessary.
7865 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007866 const RecordDecl *RD = RT->getDecl()->getDefinition();
7867 if (RD && !RD->field_empty()) {
7868 // An incomplete TypeString stub is placed in the cache for this RecordType
7869 // so that recursive calls to this RecordType will use it whilst building a
7870 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007871 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007872 std::string StubEnc(Enc.substr(Start).str());
7873 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7874 TSC.addIncomplete(ID, std::move(StubEnc));
7875 if (!extractFieldType(FE, RD, CGM, TSC)) {
7876 (void) TSC.removeIncomplete(ID);
7877 return false;
7878 }
7879 IsRecursive = TSC.removeIncomplete(ID);
7880 // The ABI requires unions to be sorted but not structures.
7881 // See FieldEncoding::operator< for sort algorithm.
7882 if (RT->isUnionType())
7883 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007884 // We can now complete the TypeString.
7885 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007886 for (unsigned I = 0; I != E; ++I) {
7887 if (I)
7888 Enc += ',';
7889 Enc += FE[I].str();
7890 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007891 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007892 Enc += '}';
7893 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7894 return true;
7895}
7896
7897/// Appends enum types to Enc and adds the encoding to the cache.
7898static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7899 TypeStringCache &TSC,
7900 const IdentifierInfo *ID) {
7901 // Append the cached TypeString if we have one.
7902 StringRef TypeString = TSC.lookupStr(ID);
7903 if (!TypeString.empty()) {
7904 Enc += TypeString;
7905 return true;
7906 }
7907
7908 size_t Start = Enc.size();
7909 Enc += "e(";
7910 if (ID)
7911 Enc += ID->getName();
7912 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007913
7914 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007915 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007916 SmallVector<FieldEncoding, 16> FE;
7917 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7918 ++I) {
7919 SmallStringEnc EnumEnc;
7920 EnumEnc += "m(";
7921 EnumEnc += I->getName();
7922 EnumEnc += "){";
7923 I->getInitVal().toString(EnumEnc);
7924 EnumEnc += '}';
7925 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7926 }
7927 std::sort(FE.begin(), FE.end());
7928 unsigned E = FE.size();
7929 for (unsigned I = 0; I != E; ++I) {
7930 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007931 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007932 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007933 }
7934 }
7935 Enc += '}';
7936 TSC.addIfComplete(ID, Enc.substr(Start), false);
7937 return true;
7938}
7939
7940/// Appends type's qualifier to Enc.
7941/// This is done prior to appending the type's encoding.
7942static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7943 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007944 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007945 int Lookup = 0;
7946 if (QT.isConstQualified())
7947 Lookup += 1<<0;
7948 if (QT.isRestrictQualified())
7949 Lookup += 1<<1;
7950 if (QT.isVolatileQualified())
7951 Lookup += 1<<2;
7952 Enc += Table[Lookup];
7953}
7954
7955/// Appends built-in types to Enc.
7956static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7957 const char *EncType;
7958 switch (BT->getKind()) {
7959 case BuiltinType::Void:
7960 EncType = "0";
7961 break;
7962 case BuiltinType::Bool:
7963 EncType = "b";
7964 break;
7965 case BuiltinType::Char_U:
7966 EncType = "uc";
7967 break;
7968 case BuiltinType::UChar:
7969 EncType = "uc";
7970 break;
7971 case BuiltinType::SChar:
7972 EncType = "sc";
7973 break;
7974 case BuiltinType::UShort:
7975 EncType = "us";
7976 break;
7977 case BuiltinType::Short:
7978 EncType = "ss";
7979 break;
7980 case BuiltinType::UInt:
7981 EncType = "ui";
7982 break;
7983 case BuiltinType::Int:
7984 EncType = "si";
7985 break;
7986 case BuiltinType::ULong:
7987 EncType = "ul";
7988 break;
7989 case BuiltinType::Long:
7990 EncType = "sl";
7991 break;
7992 case BuiltinType::ULongLong:
7993 EncType = "ull";
7994 break;
7995 case BuiltinType::LongLong:
7996 EncType = "sll";
7997 break;
7998 case BuiltinType::Float:
7999 EncType = "ft";
8000 break;
8001 case BuiltinType::Double:
8002 EncType = "d";
8003 break;
8004 case BuiltinType::LongDouble:
8005 EncType = "ld";
8006 break;
8007 default:
8008 return false;
8009 }
8010 Enc += EncType;
8011 return true;
8012}
8013
8014/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8015static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8016 const CodeGen::CodeGenModule &CGM,
8017 TypeStringCache &TSC) {
8018 Enc += "p(";
8019 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8020 return false;
8021 Enc += ')';
8022 return true;
8023}
8024
8025/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008026static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8027 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008028 const CodeGen::CodeGenModule &CGM,
8029 TypeStringCache &TSC, StringRef NoSizeEnc) {
8030 if (AT->getSizeModifier() != ArrayType::Normal)
8031 return false;
8032 Enc += "a(";
8033 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8034 CAT->getSize().toStringUnsigned(Enc);
8035 else
8036 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8037 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008038 // The Qualifiers should be attached to the type rather than the array.
8039 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008040 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8041 return false;
8042 Enc += ')';
8043 return true;
8044}
8045
8046/// Appends a function encoding to Enc, calling appendType for the return type
8047/// and the arguments.
8048static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8049 const CodeGen::CodeGenModule &CGM,
8050 TypeStringCache &TSC) {
8051 Enc += "f{";
8052 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8053 return false;
8054 Enc += "}(";
8055 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8056 // N.B. we are only interested in the adjusted param types.
8057 auto I = FPT->param_type_begin();
8058 auto E = FPT->param_type_end();
8059 if (I != E) {
8060 do {
8061 if (!appendType(Enc, *I, CGM, TSC))
8062 return false;
8063 ++I;
8064 if (I != E)
8065 Enc += ',';
8066 } while (I != E);
8067 if (FPT->isVariadic())
8068 Enc += ",va";
8069 } else {
8070 if (FPT->isVariadic())
8071 Enc += "va";
8072 else
8073 Enc += '0';
8074 }
8075 }
8076 Enc += ')';
8077 return true;
8078}
8079
8080/// Handles the type's qualifier before dispatching a call to handle specific
8081/// type encodings.
8082static bool appendType(SmallStringEnc &Enc, QualType QType,
8083 const CodeGen::CodeGenModule &CGM,
8084 TypeStringCache &TSC) {
8085
8086 QualType QT = QType.getCanonicalType();
8087
Robert Lytton6adb20f2014-06-05 09:06:21 +00008088 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8089 // The Qualifiers should be attached to the type rather than the array.
8090 // Thus we don't call appendQualifier() here.
8091 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8092
Robert Lytton844aeeb2014-05-02 09:33:20 +00008093 appendQualifier(Enc, QT);
8094
8095 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8096 return appendBuiltinType(Enc, BT);
8097
Robert Lytton844aeeb2014-05-02 09:33:20 +00008098 if (const PointerType *PT = QT->getAs<PointerType>())
8099 return appendPointerType(Enc, PT, CGM, TSC);
8100
8101 if (const EnumType *ET = QT->getAs<EnumType>())
8102 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8103
8104 if (const RecordType *RT = QT->getAsStructureType())
8105 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8106
8107 if (const RecordType *RT = QT->getAsUnionType())
8108 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8109
8110 if (const FunctionType *FT = QT->getAs<FunctionType>())
8111 return appendFunctionType(Enc, FT, CGM, TSC);
8112
8113 return false;
8114}
8115
8116static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8117 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8118 if (!D)
8119 return false;
8120
8121 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8122 if (FD->getLanguageLinkage() != CLanguageLinkage)
8123 return false;
8124 return appendType(Enc, FD->getType(), CGM, TSC);
8125 }
8126
8127 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8128 if (VD->getLanguageLinkage() != CLanguageLinkage)
8129 return false;
8130 QualType QT = VD->getType().getCanonicalType();
8131 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8132 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008133 // The Qualifiers should be attached to the type rather than the array.
8134 // Thus we don't call appendQualifier() here.
8135 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008136 }
8137 return appendType(Enc, QT, CGM, TSC);
8138 }
8139 return false;
8140}
8141
8142
Robert Lytton0e076492013-08-13 09:43:10 +00008143//===----------------------------------------------------------------------===//
8144// Driver code
8145//===----------------------------------------------------------------------===//
8146
Rafael Espindola9f834732014-09-19 01:54:22 +00008147bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008148 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008149}
8150
Chris Lattner2b037972010-07-29 02:01:43 +00008151const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008152 if (TheTargetCodeGenInfo)
8153 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008154
Reid Kleckner9305fd12016-04-13 23:37:17 +00008155 // Helper to set the unique_ptr while still keeping the return value.
8156 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8157 this->TheTargetCodeGenInfo.reset(P);
8158 return *P;
8159 };
8160
John McCallc8e01702013-04-16 22:48:15 +00008161 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008162 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008163 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008164 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008165
Derek Schuff09338a22012-09-06 17:37:28 +00008166 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008167 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008168 case llvm::Triple::mips:
8169 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008170 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008171 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8172 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008173
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008174 case llvm::Triple::mips64:
8175 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008176 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008177
Tim Northover25e8a672014-05-24 12:51:25 +00008178 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008179 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008180 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008181 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008182 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00008183
Reid Kleckner9305fd12016-04-13 23:37:17 +00008184 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008185 }
8186
Dan Gohmanc2853072015-09-03 22:51:53 +00008187 case llvm::Triple::wasm32:
8188 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008189 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008190
Daniel Dunbard59655c2009-09-12 00:59:49 +00008191 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008192 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008193 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008194 case llvm::Triple::thumbeb: {
8195 if (Triple.getOS() == llvm::Triple::Win32) {
8196 return SetCGInfo(
8197 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008198 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008199
Reid Kleckner9305fd12016-04-13 23:37:17 +00008200 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8201 StringRef ABIStr = getTarget().getABI();
8202 if (ABIStr == "apcs-gnu")
8203 Kind = ARMABIInfo::APCS;
8204 else if (ABIStr == "aapcs16")
8205 Kind = ARMABIInfo::AAPCS16_VFP;
8206 else if (CodeGenOpts.FloatABI == "hard" ||
8207 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008208 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008209 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008210 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008211 Kind = ARMABIInfo::AAPCS_VFP;
8212
8213 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8214 }
8215
John McCallea8d8bb2010-03-11 00:10:12 +00008216 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008217 return SetCGInfo(
8218 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008219 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008220 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008221 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008222 if (getTarget().getABI() == "elfv2")
8223 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008224 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008225 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008226
Hal Finkel415c2a32016-10-02 02:10:45 +00008227 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8228 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008229 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008230 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008231 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008232 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008233 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008234 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008235 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008236 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008237 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008238
Hal Finkel415c2a32016-10-02 02:10:45 +00008239 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8240 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008241 }
John McCallea8d8bb2010-03-11 00:10:12 +00008242
Peter Collingbournec947aae2012-05-20 23:28:41 +00008243 case llvm::Triple::nvptx:
8244 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008245 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008246
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008247 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008248 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008249
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008250 case llvm::Triple::systemz: {
8251 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008252 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008253 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008254
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008255 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008256 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008257 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008258
Eli Friedman33465822011-07-08 23:31:17 +00008259 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008260 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008261 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008262 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008263 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008264
John McCall1fe2a8c2013-06-18 02:46:29 +00008265 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008266 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8267 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8268 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008269 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008270 return SetCGInfo(new X86_32TargetCodeGenInfo(
8271 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8272 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8273 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008274 }
Eli Friedman33465822011-07-08 23:31:17 +00008275 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008276
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008277 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008278 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008279 X86AVXABILevel AVXLevel =
8280 (ABI == "avx512"
8281 ? X86AVXABILevel::AVX512
8282 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008283
Chris Lattner04dc9572010-08-31 16:44:54 +00008284 switch (Triple.getOS()) {
8285 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008286 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008287 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008288 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008289 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008290 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008291 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008292 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008293 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008294 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008295 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008296 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008297 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008298 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008299 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008300 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008301 case llvm::Triple::sparc:
8302 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008303 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008304 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008305 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008306 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008307 case llvm::Triple::spir:
8308 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008309 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008310 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008311}