blob: e3f3ba1be49fd2bbecfd7429408d3045c83dae14 [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"
Yaxun Liuc2a87a02017-10-14 12:23:50 +000017#include "CGBlocks.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000018#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000019#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000020#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000022#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000023#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000024#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000025#include "llvm/ADT/StringExtras.h"
Coby Tayree7b49dc92017-08-24 09:07:34 +000026#include "llvm/ADT/StringSwitch.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000027#include "llvm/ADT/Triple.h"
Yaxun Liu98f0c432017-10-14 12:51:52 +000028#include "llvm/ADT/Twine.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000031#include "llvm/Support/raw_ostream.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000032#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000033
Anton Korobeynikov244360d2009-06-05 22:08:42 +000034using namespace clang;
35using namespace CodeGen;
36
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +000037// Helper for coercing an aggregate argument or return value into an integer
38// array of the same size (including padding) and alignment. This alternate
39// coercion happens only for the RenderScript ABI and can be removed after
40// runtimes that rely on it are no longer supported.
41//
42// RenderScript assumes that the size of the argument / return value in the IR
43// is the same as the size of the corresponding qualified type. This helper
44// coerces the aggregate type into an array of the same size (including
45// padding). This coercion is used in lieu of expansion of struct members or
46// other canonical coercions that return a coerced-type of larger size.
47//
48// Ty - The argument / return value type
49// Context - The associated ASTContext
50// LLVMContext - The associated LLVMContext
51static ABIArgInfo coerceToIntArray(QualType Ty,
52 ASTContext &Context,
53 llvm::LLVMContext &LLVMContext) {
54 // Alignment and Size are measured in bits.
55 const uint64_t Size = Context.getTypeSize(Ty);
56 const uint64_t Alignment = Context.getTypeAlign(Ty);
57 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
58 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
59 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
60}
61
John McCall943fae92010-05-27 06:19:26 +000062static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
63 llvm::Value *Array,
64 llvm::Value *Value,
65 unsigned FirstIndex,
66 unsigned LastIndex) {
67 // Alternatively, we could emit this as a loop in the source.
68 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000069 llvm::Value *Cell =
70 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000071 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000072 }
73}
74
John McCalla1dee5302010-08-22 10:59:02 +000075static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000076 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000077 T->isMemberFunctionPointerType();
78}
79
John McCall7f416cc2015-09-08 08:05:57 +000080ABIArgInfo
81ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
82 llvm::Type *Padding) const {
83 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
84 ByRef, Realign, Padding);
85}
86
87ABIArgInfo
88ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
89 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
90 /*ByRef*/ false, Realign);
91}
92
Charles Davisc7d5c942015-09-17 20:55:33 +000093Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
94 QualType Ty) const {
95 return Address::invalid();
96}
97
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000098ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000099
John McCall12f23522016-04-04 18:33:08 +0000100/// Does the given lowering require more than the given number of
101/// registers when expanded?
102///
103/// This is intended to be the basis of a reasonable basic implementation
104/// of should{Pass,Return}IndirectlyForSwift.
105///
106/// For most targets, a limit of four total registers is reasonable; this
107/// limits the amount of code required in order to move around the value
108/// in case it wasn't produced immediately prior to the call by the caller
109/// (or wasn't produced in exactly the right registers) or isn't used
110/// immediately within the callee. But some targets may need to further
111/// limit the register count due to an inability to support that many
112/// return registers.
113static bool occupiesMoreThan(CodeGenTypes &cgt,
114 ArrayRef<llvm::Type*> scalarTypes,
115 unsigned maxAllRegisters) {
116 unsigned intCount = 0, fpCount = 0;
117 for (llvm::Type *type : scalarTypes) {
118 if (type->isPointerTy()) {
119 intCount++;
120 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
121 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
122 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
123 } else {
124 assert(type->isVectorTy() || type->isFloatingPointTy());
125 fpCount++;
126 }
127 }
128
129 return (intCount + fpCount > maxAllRegisters);
130}
131
132bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
133 llvm::Type *eltTy,
134 unsigned numElts) const {
135 // The default implementation of this assumes that the target guarantees
136 // 128-bit SIMD support but nothing more.
137 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
138}
139
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000140static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000141 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000142 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
143 if (!RD)
144 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000145 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000146}
147
148static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000149 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000150 const RecordType *RT = T->getAs<RecordType>();
151 if (!RT)
152 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000153 return getRecordArgABI(RT, CXXABI);
154}
155
Reid Klecknerb1be6832014-11-15 01:41:41 +0000156/// Pass transparent unions as if they were the type of the first element. Sema
157/// should ensure that all elements of the union have the same "machine type".
158static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
159 if (const RecordType *UT = Ty->getAsUnionType()) {
160 const RecordDecl *UD = UT->getDecl();
161 if (UD->hasAttr<TransparentUnionAttr>()) {
162 assert(!UD->field_empty() && "sema created an empty transparent union");
163 return UD->field_begin()->getType();
164 }
165 }
166 return Ty;
167}
168
Mark Lacey3825e832013-10-06 01:33:34 +0000169CGCXXABI &ABIInfo::getCXXABI() const {
170 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000171}
172
Chris Lattner2b037972010-07-29 02:01:43 +0000173ASTContext &ABIInfo::getContext() const {
174 return CGT.getContext();
175}
176
177llvm::LLVMContext &ABIInfo::getVMContext() const {
178 return CGT.getLLVMContext();
179}
180
Micah Villmowdd31ca12012-10-08 16:25:52 +0000181const llvm::DataLayout &ABIInfo::getDataLayout() const {
182 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000183}
184
John McCallc8e01702013-04-16 22:48:15 +0000185const TargetInfo &ABIInfo::getTarget() const {
186 return CGT.getTarget();
187}
Chris Lattner2b037972010-07-29 02:01:43 +0000188
Richard Smithf667ad52017-08-26 01:04:35 +0000189const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
190 return CGT.getCodeGenOpts();
191}
192
193bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000194
Reid Klecknere9f6a712014-10-31 17:10:41 +0000195bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
196 return false;
197}
198
199bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
200 uint64_t Members) const {
201 return false;
202}
203
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000204bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
205 return false;
206}
207
Yaron Kerencdae9412016-01-29 19:38:18 +0000208LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000209 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000210 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000211 switch (TheKind) {
212 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000213 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000214 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000215 Ty->print(OS);
216 else
217 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000218 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000219 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000220 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000221 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000222 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000223 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000224 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000225 case InAlloca:
226 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
227 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000228 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000229 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000230 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000231 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000232 break;
233 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000234 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000235 break;
John McCallf26e73d2016-03-11 04:30:43 +0000236 case CoerceAndExpand:
237 OS << "CoerceAndExpand Type=";
238 getCoerceAndExpandType()->print(OS);
239 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000240 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000241 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000242}
243
Petar Jovanovic402257b2015-12-04 00:26:47 +0000244// Dynamically round a pointer up to a multiple of the given alignment.
245static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
246 llvm::Value *Ptr,
247 CharUnits Align) {
248 llvm::Value *PtrAsInt = Ptr;
249 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
250 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
251 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
252 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
253 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
254 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
255 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
256 Ptr->getType(),
257 Ptr->getName() + ".aligned");
258 return PtrAsInt;
259}
260
John McCall7f416cc2015-09-08 08:05:57 +0000261/// Emit va_arg for a platform using the common void* representation,
262/// where arguments are simply emitted in an array of slots on the stack.
263///
264/// This version implements the core direct-value passing rules.
265///
266/// \param SlotSize - The size and alignment of a stack slot.
267/// Each argument will be allocated to a multiple of this number of
268/// slots, and all the slots will be aligned to this value.
269/// \param AllowHigherAlign - The slot alignment is not a cap;
270/// an argument type with an alignment greater than the slot size
271/// will be emitted on a higher-alignment address, potentially
272/// leaving one or more empty slots behind as padding. If this
273/// is false, the returned address might be less-aligned than
274/// DirectAlign.
275static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
276 Address VAListAddr,
277 llvm::Type *DirectTy,
278 CharUnits DirectSize,
279 CharUnits DirectAlign,
280 CharUnits SlotSize,
281 bool AllowHigherAlign) {
282 // Cast the element type to i8* if necessary. Some platforms define
283 // va_list as a struct containing an i8* instead of just an i8*.
284 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
285 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
286
287 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
288
289 // If the CC aligns values higher than the slot size, do so if needed.
290 Address Addr = Address::invalid();
291 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000292 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
293 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000294 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000295 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000296 }
297
298 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000299 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000300 llvm::Value *NextPtr =
301 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
302 "argp.next");
303 CGF.Builder.CreateStore(NextPtr, VAListAddr);
304
305 // If the argument is smaller than a slot, and this is a big-endian
306 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000307 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
308 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000309 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
310 }
311
312 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
313 return Addr;
314}
315
316/// Emit va_arg for a platform using the common void* representation,
317/// where arguments are simply emitted in an array of slots on the stack.
318///
319/// \param IsIndirect - Values of this type are passed indirectly.
320/// \param ValueInfo - The size and alignment of this type, generally
321/// computed with getContext().getTypeInfoInChars(ValueTy).
322/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
323/// Each argument will be allocated to a multiple of this number of
324/// slots, and all the slots will be aligned to this value.
325/// \param AllowHigherAlign - The slot alignment is not a cap;
326/// an argument type with an alignment greater than the slot size
327/// will be emitted on a higher-alignment address, potentially
328/// leaving one or more empty slots behind as padding.
329static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
330 QualType ValueTy, bool IsIndirect,
331 std::pair<CharUnits, CharUnits> ValueInfo,
332 CharUnits SlotSizeAndAlign,
333 bool AllowHigherAlign) {
334 // The size and alignment of the value that was passed directly.
335 CharUnits DirectSize, DirectAlign;
336 if (IsIndirect) {
337 DirectSize = CGF.getPointerSize();
338 DirectAlign = CGF.getPointerAlign();
339 } else {
340 DirectSize = ValueInfo.first;
341 DirectAlign = ValueInfo.second;
342 }
343
344 // Cast the address we've calculated to the right type.
345 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
346 if (IsIndirect)
347 DirectTy = DirectTy->getPointerTo(0);
348
349 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
350 DirectSize, DirectAlign,
351 SlotSizeAndAlign,
352 AllowHigherAlign);
353
354 if (IsIndirect) {
355 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
356 }
357
358 return Addr;
359
360}
361
362static Address emitMergePHI(CodeGenFunction &CGF,
363 Address Addr1, llvm::BasicBlock *Block1,
364 Address Addr2, llvm::BasicBlock *Block2,
365 const llvm::Twine &Name = "") {
366 assert(Addr1.getType() == Addr2.getType());
367 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
368 PHI->addIncoming(Addr1.getPointer(), Block1);
369 PHI->addIncoming(Addr2.getPointer(), Block2);
370 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
371 return Address(PHI, Align);
372}
373
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000374TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
375
John McCall3480ef22011-08-30 01:42:09 +0000376// If someone can figure out a general rule for this, that would be great.
377// It's probably just doomed to be platform-dependent, though.
378unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
379 // Verified for:
380 // x86-64 FreeBSD, Linux, Darwin
381 // x86-32 FreeBSD, Linux, Darwin
382 // PowerPC Linux, Darwin
383 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000384 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000385 return 32;
386}
387
John McCalla729c622012-02-17 03:33:10 +0000388bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
389 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000390 // The following conventions are known to require this to be false:
391 // x86_stdcall
392 // MIPS
393 // For everything else, we just prefer false unless we opt out.
394 return false;
395}
396
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000397void
398TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
399 llvm::SmallString<24> &Opt) const {
400 // This assumes the user is passing a library name like "rt" instead of a
401 // filename like "librt.a/so", and that they don't care whether it's static or
402 // dynamic.
403 Opt = "-l";
404 Opt += Lib;
405}
406
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000407unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000408 // OpenCL kernels are called via an explicit runtime API with arguments
409 // set with clSetKernelArg(), not as normal sub-functions.
410 // Return SPIR_KERNEL by default as the kernel calling convention to
411 // ensure the fingerprint is fixed such way that each OpenCL argument
412 // gets one matching argument in the produced kernel function argument
413 // list to enable feasible implementation of clSetKernelArg() with
414 // aggregates etc. In case we would use the default C calling conv here,
415 // clSetKernelArg() might break depending on the target-specific
416 // conventions; different targets might split structs passed as values
417 // to multiple function arguments etc.
418 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000419}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000420
Yaxun Liu402804b2016-12-15 08:09:08 +0000421llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
422 llvm::PointerType *T, QualType QT) const {
423 return llvm::ConstantPointerNull::get(T);
424}
425
Alexander Richardson6d989432017-10-15 18:48:14 +0000426LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
427 const VarDecl *D) const {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000428 assert(!CGM.getLangOpts().OpenCL &&
429 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
430 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +0000431 return D ? D->getType().getAddressSpace() : LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000432}
433
Yaxun Liu402804b2016-12-15 08:09:08 +0000434llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Alexander Richardson6d989432017-10-15 18:48:14 +0000435 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
436 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000437 // Since target may map different address spaces in AST to the same address
438 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000439 if (auto *C = dyn_cast<llvm::Constant>(Src))
440 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000441 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000442}
443
Yaxun Liucbf647c2017-07-08 13:24:52 +0000444llvm::Constant *
445TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
Alexander Richardson6d989432017-10-15 18:48:14 +0000446 LangAS SrcAddr, LangAS DestAddr,
Yaxun Liucbf647c2017-07-08 13:24:52 +0000447 llvm::Type *DestTy) const {
448 // Since target may map different address spaces in AST to the same address
449 // space, an address space conversion may end up as a bitcast.
450 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
451}
452
Yaxun Liu39195062017-08-04 18:16:31 +0000453llvm::SyncScope::ID
454TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
455 return C.getOrInsertSyncScopeID(""); /* default sync scope */
456}
457
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000458static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000459
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000460/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000461/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000462static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
463 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000464 if (FD->isUnnamedBitfield())
465 return true;
466
467 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000468
Eli Friedman0b3f2012011-11-18 03:47:20 +0000469 // Constant arrays of empty records count as empty, strip them off.
470 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000471 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000472 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
473 if (AT->getSize() == 0)
474 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000475 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000476 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000477
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000478 const RecordType *RT = FT->getAs<RecordType>();
479 if (!RT)
480 return false;
481
482 // C++ record fields are never empty, at least in the Itanium ABI.
483 //
484 // FIXME: We should use a predicate for whether this behavior is true in the
485 // current ABI.
486 if (isa<CXXRecordDecl>(RT->getDecl()))
487 return false;
488
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000489 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000490}
491
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000492/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000493/// fields. Note that a structure with a flexible array member is not
494/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000495static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000496 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000497 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000498 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000499 const RecordDecl *RD = RT->getDecl();
500 if (RD->hasFlexibleArrayMember())
501 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000502
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000503 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000504 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 for (const auto &I : CXXRD->bases())
506 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000507 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000508
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000509 for (const auto *I : RD->fields())
510 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000511 return false;
512 return true;
513}
514
515/// isSingleElementStruct - Determine if a structure is a "single
516/// element struct", i.e. it has exactly one non-empty field or
517/// exactly one field which is itself a single element
518/// struct. Structures with flexible array members are never
519/// considered single element structs.
520///
521/// \return The field declaration for the single non-empty field, if
522/// it exists.
523static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000524 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000525 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000526 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000527
528 const RecordDecl *RD = RT->getDecl();
529 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000530 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000531
Craig Topper8a13c412014-05-21 05:09:00 +0000532 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000533
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000534 // If this is a C++ record, check the bases first.
535 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000536 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000537 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000538 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000539 continue;
540
541 // If we already found an element then this isn't a single-element struct.
542 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000543 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000544
545 // If this is non-empty and not a single element struct, the composite
546 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000547 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000548 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000549 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000550 }
551 }
552
553 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000554 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000555 QualType FT = FD->getType();
556
557 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000558 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000559 continue;
560
561 // If we already found an element then this isn't a single-element
562 // struct.
563 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000564 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000565
566 // Treat single element arrays as the element.
567 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
568 if (AT->getSize().getZExtValue() != 1)
569 break;
570 FT = AT->getElementType();
571 }
572
John McCalla1dee5302010-08-22 10:59:02 +0000573 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000574 Found = FT.getTypePtr();
575 } else {
576 Found = isSingleElementStruct(FT, Context);
577 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000578 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000579 }
580 }
581
Eli Friedmanee945342011-11-18 01:25:50 +0000582 // We don't consider a struct a single-element struct if it has
583 // padding beyond the element type.
584 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000585 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000586
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000587 return Found;
588}
589
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000590namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000591Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
592 const ABIArgInfo &AI) {
593 // This default implementation defers to the llvm backend's va_arg
594 // instruction. It can handle only passing arguments directly
595 // (typically only handled in the backend for primitive types), or
596 // aggregates passed indirectly by pointer (NOTE: if the "byval"
597 // flag has ABI impact in the callee, this implementation cannot
598 // work.)
599
600 // Only a few cases are covered here at the moment -- those needed
601 // by the default abi.
602 llvm::Value *Val;
603
604 if (AI.isIndirect()) {
605 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000606 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000607 assert(
608 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000609 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000610
611 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
612 CharUnits TyAlignForABI = TyInfo.second;
613
614 llvm::Type *BaseTy =
615 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
616 llvm::Value *Addr =
617 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
618 return Address(Addr, TyAlignForABI);
619 } else {
620 assert((AI.isDirect() || AI.isExtend()) &&
621 "Unexpected ArgInfo Kind in generic VAArg emitter!");
622
623 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000624 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000625 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000626 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000627 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000628 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000629 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000630 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000631
632 Address Temp = CGF.CreateMemTemp(Ty, "varet");
633 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
634 CGF.Builder.CreateStore(Val, Temp);
635 return Temp;
636 }
637}
638
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000639/// DefaultABIInfo - The default implementation for ABI specific
640/// details. This implementation provides information which results in
641/// self-consistent and sensible LLVM IR generation, but does not
642/// conform to any particular ABI.
643class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000644public:
645 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000646
Chris Lattner458b2aa2010-07-29 02:16:43 +0000647 ABIArgInfo classifyReturnType(QualType RetTy) const;
648 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000649
Craig Topper4f12f102014-03-12 06:41:41 +0000650 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000651 if (!getCXXABI().classifyReturnType(FI))
652 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000653 for (auto &I : FI.arguments())
654 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000655 }
656
John McCall7f416cc2015-09-08 08:05:57 +0000657 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000658 QualType Ty) const override {
659 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
660 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000661};
662
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000663class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
664public:
Chris Lattner2b037972010-07-29 02:01:43 +0000665 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
666 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000667};
668
Chris Lattner458b2aa2010-07-29 02:16:43 +0000669ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000670 Ty = useFirstFieldIfTransparentUnion(Ty);
671
672 if (isAggregateTypeForABI(Ty)) {
673 // Records with non-trivial destructors/copy-constructors should not be
674 // passed by value.
675 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000676 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000677
John McCall7f416cc2015-09-08 08:05:57 +0000678 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000679 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000680
Chris Lattner9723d6c2010-03-11 18:19:55 +0000681 // Treat an enum type as its underlying type.
682 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
683 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000684
Chris Lattner9723d6c2010-03-11 18:19:55 +0000685 return (Ty->isPromotableIntegerType() ?
686 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000687}
688
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000689ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
690 if (RetTy->isVoidType())
691 return ABIArgInfo::getIgnore();
692
693 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000694 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000695
696 // Treat an enum type as its underlying type.
697 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
698 RetTy = EnumTy->getDecl()->getIntegerType();
699
700 return (RetTy->isPromotableIntegerType() ?
701 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
702}
703
Derek Schuff09338a22012-09-06 17:37:28 +0000704//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000705// WebAssembly ABI Implementation
706//
707// This is a very simple ABI that relies a lot on DefaultABIInfo.
708//===----------------------------------------------------------------------===//
709
710class WebAssemblyABIInfo final : public DefaultABIInfo {
711public:
712 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
713 : DefaultABIInfo(CGT) {}
714
715private:
716 ABIArgInfo classifyReturnType(QualType RetTy) const;
717 ABIArgInfo classifyArgumentType(QualType Ty) const;
718
719 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000720 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000721 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000722 void computeInfo(CGFunctionInfo &FI) const override {
723 if (!getCXXABI().classifyReturnType(FI))
724 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
725 for (auto &Arg : FI.arguments())
726 Arg.info = classifyArgumentType(Arg.type);
727 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000728
729 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
730 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000731};
732
733class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
734public:
735 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
736 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
737};
738
739/// \brief Classify argument of given type \p Ty.
740ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
741 Ty = useFirstFieldIfTransparentUnion(Ty);
742
743 if (isAggregateTypeForABI(Ty)) {
744 // Records with non-trivial destructors/copy-constructors should not be
745 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000746 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000747 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000748 // Ignore empty structs/unions.
749 if (isEmptyRecord(getContext(), Ty, true))
750 return ABIArgInfo::getIgnore();
751 // Lower single-element structs to just pass a regular value. TODO: We
752 // could do reasonable-size multiple-element structs too, using getExpand(),
753 // though watch out for things like bitfields.
754 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
755 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000756 }
757
758 // Otherwise just do the default thing.
759 return DefaultABIInfo::classifyArgumentType(Ty);
760}
761
762ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
763 if (isAggregateTypeForABI(RetTy)) {
764 // Records with non-trivial destructors/copy-constructors should not be
765 // returned by value.
766 if (!getRecordArgABI(RetTy, getCXXABI())) {
767 // Ignore empty structs/unions.
768 if (isEmptyRecord(getContext(), RetTy, true))
769 return ABIArgInfo::getIgnore();
770 // Lower single-element structs to just return a regular value. TODO: We
771 // could do reasonable-size multiple-element structs too, using
772 // ABIArgInfo::getDirect().
773 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
774 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
775 }
776 }
777
778 // Otherwise just do the default thing.
779 return DefaultABIInfo::classifyReturnType(RetTy);
780}
781
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000782Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
783 QualType Ty) const {
784 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
785 getContext().getTypeInfoInChars(Ty),
786 CharUnits::fromQuantity(4),
787 /*AllowHigherAlign=*/ true);
788}
789
Dan Gohmanc2853072015-09-03 22:51:53 +0000790//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000791// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000792//
793// This is a simplified version of the x86_32 ABI. Arguments and return values
794// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000795//===----------------------------------------------------------------------===//
796
797class PNaClABIInfo : public ABIInfo {
798 public:
799 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
800
801 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000802 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000803
Craig Topper4f12f102014-03-12 06:41:41 +0000804 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000805 Address EmitVAArg(CodeGenFunction &CGF,
806 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000807};
808
809class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
810 public:
811 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
812 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
813};
814
815void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000816 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000817 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
818
Reid Kleckner40ca9132014-05-13 22:05:45 +0000819 for (auto &I : FI.arguments())
820 I.info = classifyArgumentType(I.type);
821}
Derek Schuff09338a22012-09-06 17:37:28 +0000822
John McCall7f416cc2015-09-08 08:05:57 +0000823Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
824 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000825 // The PNaCL ABI is a bit odd, in that varargs don't use normal
826 // function classification. Structs get passed directly for varargs
827 // functions, through a rewriting transform in
828 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
829 // this target to actually support a va_arg instructions with an
830 // aggregate type, unlike other targets.
831 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000832}
833
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000834/// \brief Classify argument of given type \p Ty.
835ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000836 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000837 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000838 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
839 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000840 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
841 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000842 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000843 } else if (Ty->isFloatingType()) {
844 // Floating-point types don't go inreg.
845 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000846 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000847
848 return (Ty->isPromotableIntegerType() ?
849 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000850}
851
852ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
853 if (RetTy->isVoidType())
854 return ABIArgInfo::getIgnore();
855
Eli Benderskye20dad62013-04-04 22:49:35 +0000856 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000857 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000858 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000859
860 // Treat an enum type as its underlying type.
861 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
862 RetTy = EnumTy->getDecl()->getIntegerType();
863
864 return (RetTy->isPromotableIntegerType() ?
865 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
866}
867
Chad Rosier651c1832013-03-25 21:00:27 +0000868/// IsX86_MMXType - Return true if this is an MMX type.
869bool IsX86_MMXType(llvm::Type *IRType) {
870 // 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 +0000871 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
872 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
873 IRType->getScalarSizeInBits() != 64;
874}
875
Jay Foad7c57be32011-07-11 09:56:20 +0000876static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000877 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000878 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000879 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
880 .Cases("y", "&y", "^Ym", true)
881 .Default(false);
882 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000883 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
884 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000885 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000886 }
887
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000888 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000889 }
890
891 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000892 return Ty;
893}
894
Reid Kleckner80944df2014-10-31 22:00:51 +0000895/// Returns true if this type can be passed in SSE registers with the
896/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
897static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
898 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000899 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
900 if (BT->getKind() == BuiltinType::LongDouble) {
901 if (&Context.getTargetInfo().getLongDoubleFormat() ==
902 &llvm::APFloat::x87DoubleExtended())
903 return false;
904 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000905 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000906 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000907 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
908 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
909 // registers specially.
910 unsigned VecSize = Context.getTypeSize(VT);
911 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
912 return true;
913 }
914 return false;
915}
916
917/// Returns true if this aggregate is small enough to be passed in SSE registers
918/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
919static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
920 return NumMembers <= 4;
921}
922
Erich Keane521ed962017-01-05 00:20:51 +0000923/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
924static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
925 auto AI = ABIArgInfo::getDirect(T);
926 AI.setInReg(true);
927 AI.setCanBeFlattened(false);
928 return AI;
929}
930
Chris Lattner0cf24192010-06-28 20:05:43 +0000931//===----------------------------------------------------------------------===//
932// X86-32 ABI Implementation
933//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000934
Reid Kleckner661f35b2014-01-18 01:12:41 +0000935/// \brief Similar to llvm::CCState, but for Clang.
936struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000937 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000938
939 unsigned CC;
940 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000941 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000942};
943
Erich Keane521ed962017-01-05 00:20:51 +0000944enum {
945 // Vectorcall only allows the first 6 parameters to be passed in registers.
946 VectorcallMaxParamNumAsReg = 6
947};
948
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000949/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000950class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000951 enum Class {
952 Integer,
953 Float
954 };
955
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000956 static const unsigned MinABIStackAlignInBytes = 4;
957
David Chisnallde3a0692009-08-17 23:08:21 +0000958 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000959 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000960 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000961 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000962 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000963 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000964
965 static bool isRegisterSize(unsigned Size) {
966 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
967 }
968
Reid Kleckner80944df2014-10-31 22:00:51 +0000969 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
970 // FIXME: Assumes vectorcall is in use.
971 return isX86VectorTypeForVectorCall(getContext(), Ty);
972 }
973
974 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
975 uint64_t NumMembers) const override {
976 // FIXME: Assumes vectorcall is in use.
977 return isX86VectorCallAggregateSmallEnough(NumMembers);
978 }
979
Reid Kleckner40ca9132014-05-13 22:05:45 +0000980 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000981
Daniel Dunbar557893d2010-04-21 19:10:51 +0000982 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
983 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000984 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
985
John McCall7f416cc2015-09-08 08:05:57 +0000986 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000987
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000988 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000989 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000990
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000991 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000992 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000993 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +0000994
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000995 /// \brief Updates the number of available free registers, returns
996 /// true if any registers were allocated.
997 bool updateFreeRegs(QualType Ty, CCState &State) const;
998
999 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1000 bool &NeedsPadding) const;
1001 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001002
Reid Kleckner04046052016-05-02 17:41:07 +00001003 bool canExpandIndirectArgument(QualType Ty) const;
1004
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001005 /// \brief Rewrite the function info so that all memory arguments use
1006 /// inalloca.
1007 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1008
1009 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001010 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001011 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001012 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1013 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001014
Rafael Espindola75419dc2012-07-23 23:30:29 +00001015public:
1016
Craig Topper4f12f102014-03-12 06:41:41 +00001017 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001018 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1019 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001020
Michael Kupersteindc745202015-10-19 07:52:25 +00001021 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1022 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001023 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001024 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001025 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1026 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001027 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001028 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001029 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001030
John McCall56331e22018-01-07 06:28:49 +00001031 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00001032 bool asReturnValue) const override {
1033 // LLVM's x86-32 lowering currently only assigns up to three
1034 // integer registers and three fp registers. Oddly, it'll use up to
1035 // four vector registers for vectors, but those can overlap with the
1036 // scalar registers.
1037 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1038 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001039
1040 bool isSwiftErrorInRegister() const override {
1041 // x86-32 lowering does not support passing swifterror in a register.
1042 return false;
1043 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001044};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001045
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001046class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1047public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001048 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1049 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001050 unsigned NumRegisterParameters, bool SoftFloatABI)
1051 : TargetCodeGenInfo(new X86_32ABIInfo(
1052 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1053 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001054
John McCall1fe2a8c2013-06-18 02:46:29 +00001055 static bool isStructReturnInRegABI(
1056 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1057
Eric Christopher162c91c2015-06-05 22:03:00 +00001058 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001059 CodeGen::CodeGenModule &CGM,
1060 ForDefinition_t IsForDefinition) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001061
Craig Topper4f12f102014-03-12 06:41:41 +00001062 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001063 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001064 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001065 return 4;
1066 }
1067
1068 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001069 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001070
Jay Foad7c57be32011-07-11 09:56:20 +00001071 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001072 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001073 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001074 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1075 }
1076
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001077 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1078 std::string &Constraints,
1079 std::vector<llvm::Type *> &ResultRegTypes,
1080 std::vector<llvm::Type *> &ResultTruncRegTypes,
1081 std::vector<LValue> &ResultRegDests,
1082 std::string &AsmString,
1083 unsigned NumOutputs) const override;
1084
Craig Topper4f12f102014-03-12 06:41:41 +00001085 llvm::Constant *
1086 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001087 unsigned Sig = (0xeb << 0) | // jmp rel8
1088 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001089 ('v' << 16) |
1090 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001091 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1092 }
John McCall01391782016-02-05 21:37:38 +00001093
1094 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1095 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001096 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001097 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001098};
1099
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001100}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001102/// Rewrite input constraint references after adding some output constraints.
1103/// In the case where there is one output and one input and we add one output,
1104/// we need to replace all operand references greater than or equal to 1:
1105/// mov $0, $1
1106/// mov eax, $1
1107/// The result will be:
1108/// mov $0, $2
1109/// mov eax, $2
1110static void rewriteInputConstraintReferences(unsigned FirstIn,
1111 unsigned NumNewOuts,
1112 std::string &AsmString) {
1113 std::string Buf;
1114 llvm::raw_string_ostream OS(Buf);
1115 size_t Pos = 0;
1116 while (Pos < AsmString.size()) {
1117 size_t DollarStart = AsmString.find('$', Pos);
1118 if (DollarStart == std::string::npos)
1119 DollarStart = AsmString.size();
1120 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1121 if (DollarEnd == std::string::npos)
1122 DollarEnd = AsmString.size();
1123 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1124 Pos = DollarEnd;
1125 size_t NumDollars = DollarEnd - DollarStart;
1126 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1127 // We have an operand reference.
1128 size_t DigitStart = Pos;
1129 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1130 if (DigitEnd == std::string::npos)
1131 DigitEnd = AsmString.size();
1132 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1133 unsigned OperandIndex;
1134 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1135 if (OperandIndex >= FirstIn)
1136 OperandIndex += NumNewOuts;
1137 OS << OperandIndex;
1138 } else {
1139 OS << OperandStr;
1140 }
1141 Pos = DigitEnd;
1142 }
1143 }
1144 AsmString = std::move(OS.str());
1145}
1146
1147/// Add output constraints for EAX:EDX because they are return registers.
1148void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1149 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1150 std::vector<llvm::Type *> &ResultRegTypes,
1151 std::vector<llvm::Type *> &ResultTruncRegTypes,
1152 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1153 unsigned NumOutputs) const {
1154 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1155
1156 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1157 // larger.
1158 if (!Constraints.empty())
1159 Constraints += ',';
1160 if (RetWidth <= 32) {
1161 Constraints += "={eax}";
1162 ResultRegTypes.push_back(CGF.Int32Ty);
1163 } else {
1164 // Use the 'A' constraint for EAX:EDX.
1165 Constraints += "=A";
1166 ResultRegTypes.push_back(CGF.Int64Ty);
1167 }
1168
1169 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1170 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1171 ResultTruncRegTypes.push_back(CoerceTy);
1172
1173 // Coerce the integer by bitcasting the return slot pointer.
1174 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1175 CoerceTy->getPointerTo()));
1176 ResultRegDests.push_back(ReturnSlot);
1177
1178 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1179}
1180
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001181/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001182/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001183bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1184 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001185 uint64_t Size = Context.getTypeSize(Ty);
1186
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001187 // For i386, type must be register sized.
1188 // For the MCU ABI, it only needs to be <= 8-byte
1189 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1190 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001191
1192 if (Ty->isVectorType()) {
1193 // 64- and 128- bit vectors inside structures are not returned in
1194 // registers.
1195 if (Size == 64 || Size == 128)
1196 return false;
1197
1198 return true;
1199 }
1200
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001201 // If this is a builtin, pointer, enum, complex type, member pointer, or
1202 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001203 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001204 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001205 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001206 return true;
1207
1208 // Arrays are treated like records.
1209 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001210 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001211
1212 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001213 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001214 if (!RT) return false;
1215
Anders Carlsson40446e82010-01-27 03:25:19 +00001216 // FIXME: Traverse bases here too.
1217
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001218 // Structure types are passed in register if all fields would be
1219 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001220 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001221 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001222 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001223 continue;
1224
1225 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001226 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001227 return false;
1228 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001229 return true;
1230}
1231
Reid Kleckner04046052016-05-02 17:41:07 +00001232static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1233 // Treat complex types as the element type.
1234 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1235 Ty = CTy->getElementType();
1236
1237 // Check for a type which we know has a simple scalar argument-passing
1238 // convention without any padding. (We're specifically looking for 32
1239 // and 64-bit integer and integer-equivalents, float, and double.)
1240 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1241 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1242 return false;
1243
1244 uint64_t Size = Context.getTypeSize(Ty);
1245 return Size == 32 || Size == 64;
1246}
1247
Reid Kleckner791bbf62017-01-13 17:18:19 +00001248static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1249 uint64_t &Size) {
1250 for (const auto *FD : RD->fields()) {
1251 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1252 // argument is smaller than 32-bits, expanding the struct will create
1253 // alignment padding.
1254 if (!is32Or64BitBasicType(FD->getType(), Context))
1255 return false;
1256
1257 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1258 // how to expand them yet, and the predicate for telling if a bitfield still
1259 // counts as "basic" is more complicated than what we were doing previously.
1260 if (FD->isBitField())
1261 return false;
1262
1263 Size += Context.getTypeSize(FD->getType());
1264 }
1265 return true;
1266}
1267
1268static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1269 uint64_t &Size) {
1270 // Don't do this if there are any non-empty bases.
1271 for (const CXXBaseSpecifier &Base : RD->bases()) {
1272 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1273 Size))
1274 return false;
1275 }
1276 if (!addFieldSizes(Context, RD, Size))
1277 return false;
1278 return true;
1279}
1280
Reid Kleckner04046052016-05-02 17:41:07 +00001281/// Test whether an argument type which is to be passed indirectly (on the
1282/// stack) would have the equivalent layout if it was expanded into separate
1283/// arguments. If so, we prefer to do the latter to avoid inhibiting
1284/// optimizations.
1285bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1286 // We can only expand structure types.
1287 const RecordType *RT = Ty->getAs<RecordType>();
1288 if (!RT)
1289 return false;
1290 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001291 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001292 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001293 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001294 // On non-Windows, we have to conservatively match our old bitcode
1295 // prototypes in order to be ABI-compatible at the bitcode level.
1296 if (!CXXRD->isCLike())
1297 return false;
1298 } else {
1299 // Don't do this for dynamic classes.
1300 if (CXXRD->isDynamicClass())
1301 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001302 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001303 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001304 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001305 } else {
1306 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001307 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001308 }
1309
1310 // We can do this if there was no alignment padding.
1311 return Size == getContext().getTypeSize(Ty);
1312}
1313
John McCall7f416cc2015-09-08 08:05:57 +00001314ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001315 // If the return value is indirect, then the hidden argument is consuming one
1316 // integer register.
1317 if (State.FreeRegs) {
1318 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001319 if (!IsMCUABI)
1320 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001321 }
John McCall7f416cc2015-09-08 08:05:57 +00001322 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001323}
1324
Eric Christopher7565e0d2015-05-29 23:09:49 +00001325ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1326 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001327 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001328 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001329
Reid Kleckner80944df2014-10-31 22:00:51 +00001330 const Type *Base = nullptr;
1331 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001332 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1333 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001334 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1335 // The LLVM struct type for such an aggregate should lower properly.
1336 return ABIArgInfo::getDirect();
1337 }
1338
Chris Lattner458b2aa2010-07-29 02:16:43 +00001339 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001340 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001341 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001342 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001343
1344 // 128-bit vectors are a special case; they are returned in
1345 // registers and we need to make sure to pick a type the LLVM
1346 // backend will like.
1347 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001348 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001349 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001350
1351 // Always return in register if it fits in a general purpose
1352 // register, or if it is 64 bits and has a single element.
1353 if ((Size == 8 || Size == 16 || Size == 32) ||
1354 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001355 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001356 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001357
John McCall7f416cc2015-09-08 08:05:57 +00001358 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001359 }
1360
1361 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001362 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001363
John McCalla1dee5302010-08-22 10:59:02 +00001364 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001365 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001366 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001367 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001368 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001369 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001370
David Chisnallde3a0692009-08-17 23:08:21 +00001371 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001372 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001373 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001374
Denis Zobnin380b2242016-02-11 11:26:03 +00001375 // Ignore empty structs/unions.
1376 if (isEmptyRecord(getContext(), RetTy, true))
1377 return ABIArgInfo::getIgnore();
1378
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001379 // Small structures which are register sized are generally returned
1380 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001381 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001382 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001383
1384 // As a special-case, if the struct is a "single-element" struct, and
1385 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001386 // floating-point register. (MSVC does not apply this special case.)
1387 // We apply a similar transformation for pointer types to improve the
1388 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001389 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001390 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001391 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001392 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1393
1394 // FIXME: We should be able to narrow this integer in cases with dead
1395 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001396 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001397 }
1398
John McCall7f416cc2015-09-08 08:05:57 +00001399 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001400 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001401
Chris Lattner458b2aa2010-07-29 02:16:43 +00001402 // Treat an enum type as its underlying type.
1403 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1404 RetTy = EnumTy->getDecl()->getIntegerType();
1405
1406 return (RetTy->isPromotableIntegerType() ?
1407 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001408}
1409
Eli Friedman7919bea2012-06-05 19:40:46 +00001410static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1411 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1412}
1413
Daniel Dunbared23de32010-09-16 20:42:00 +00001414static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1415 const RecordType *RT = Ty->getAs<RecordType>();
1416 if (!RT)
1417 return 0;
1418 const RecordDecl *RD = RT->getDecl();
1419
1420 // If this is a C++ record, check the bases first.
1421 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001422 for (const auto &I : CXXRD->bases())
1423 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001424 return false;
1425
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001426 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001427 QualType FT = i->getType();
1428
Eli Friedman7919bea2012-06-05 19:40:46 +00001429 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001430 return true;
1431
1432 if (isRecordWithSSEVectorType(Context, FT))
1433 return true;
1434 }
1435
1436 return false;
1437}
1438
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001439unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1440 unsigned Align) const {
1441 // Otherwise, if the alignment is less than or equal to the minimum ABI
1442 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001443 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001444 return 0; // Use default alignment.
1445
1446 // On non-Darwin, the stack type alignment is always 4.
1447 if (!IsDarwinVectorABI) {
1448 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001449 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001450 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001451
Daniel Dunbared23de32010-09-16 20:42:00 +00001452 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001453 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1454 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001455 return 16;
1456
1457 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001458}
1459
Rafael Espindola703c47f2012-10-19 05:04:37 +00001460ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001461 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001462 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001463 if (State.FreeRegs) {
1464 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001465 if (!IsMCUABI)
1466 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001467 }
John McCall7f416cc2015-09-08 08:05:57 +00001468 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001469 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001470
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001471 // Compute the byval alignment.
1472 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1473 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1474 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001475 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001476
1477 // If the stack alignment is less than the type alignment, realign the
1478 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001479 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001480 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1481 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001482}
1483
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001484X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1485 const Type *T = isSingleElementStruct(Ty, getContext());
1486 if (!T)
1487 T = Ty.getTypePtr();
1488
1489 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1490 BuiltinType::Kind K = BT->getKind();
1491 if (K == BuiltinType::Float || K == BuiltinType::Double)
1492 return Float;
1493 }
1494 return Integer;
1495}
1496
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001497bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001498 if (!IsSoftFloatABI) {
1499 Class C = classify(Ty);
1500 if (C == Float)
1501 return false;
1502 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001503
Rafael Espindola077dd592012-10-24 01:58:58 +00001504 unsigned Size = getContext().getTypeSize(Ty);
1505 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001506
1507 if (SizeInRegs == 0)
1508 return false;
1509
Michael Kuperstein68901882015-10-25 08:18:20 +00001510 if (!IsMCUABI) {
1511 if (SizeInRegs > State.FreeRegs) {
1512 State.FreeRegs = 0;
1513 return false;
1514 }
1515 } else {
1516 // The MCU psABI allows passing parameters in-reg even if there are
1517 // earlier parameters that are passed on the stack. Also,
1518 // it does not allow passing >8-byte structs in-register,
1519 // even if there are 3 free registers available.
1520 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1521 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001522 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001523
Reid Kleckner661f35b2014-01-18 01:12:41 +00001524 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001525 return true;
1526}
1527
1528bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1529 bool &InReg,
1530 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001531 // On Windows, aggregates other than HFAs are never passed in registers, and
1532 // they do not consume register slots. Homogenous floating-point aggregates
1533 // (HFAs) have already been dealt with at this point.
1534 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1535 return false;
1536
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001537 NeedsPadding = false;
1538 InReg = !IsMCUABI;
1539
1540 if (!updateFreeRegs(Ty, State))
1541 return false;
1542
1543 if (IsMCUABI)
1544 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001545
Reid Kleckner80944df2014-10-31 22:00:51 +00001546 if (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) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001549 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001550 NeedsPadding = true;
1551
Rafael Espindola077dd592012-10-24 01:58:58 +00001552 return false;
1553 }
1554
Rafael Espindola703c47f2012-10-19 05:04:37 +00001555 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001556}
1557
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001558bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1559 if (!updateFreeRegs(Ty, State))
1560 return false;
1561
1562 if (IsMCUABI)
1563 return false;
1564
1565 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001566 State.CC == llvm::CallingConv::X86_VectorCall ||
1567 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001568 if (getContext().getTypeSize(Ty) > 32)
1569 return false;
1570
1571 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1572 Ty->isReferenceType());
1573 }
1574
1575 return true;
1576}
1577
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001578ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1579 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001580 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001581
Reid Klecknerb1be6832014-11-15 01:41:41 +00001582 Ty = useFirstFieldIfTransparentUnion(Ty);
1583
Reid Kleckner80944df2014-10-31 22:00:51 +00001584 // Check with the C++ ABI first.
1585 const RecordType *RT = Ty->getAs<RecordType>();
1586 if (RT) {
1587 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1588 if (RAA == CGCXXABI::RAA_Indirect) {
1589 return getIndirectResult(Ty, false, State);
1590 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1591 // The field index doesn't matter, we'll fix it up later.
1592 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1593 }
1594 }
1595
Erich Keane4bd39302017-06-21 16:37:22 +00001596 // Regcall uses the concept of a homogenous vector aggregate, similar
1597 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001598 const Type *Base = nullptr;
1599 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001600 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001601 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001602
Erich Keane4bd39302017-06-21 16:37:22 +00001603 if (State.FreeSSERegs >= NumElts) {
1604 State.FreeSSERegs -= NumElts;
1605 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001606 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001607 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001608 }
Erich Keane4bd39302017-06-21 16:37:22 +00001609 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001610 }
1611
1612 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001613 // Structures with flexible arrays are always indirect.
1614 // FIXME: This should not be byval!
1615 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1616 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001617
Reid Kleckner04046052016-05-02 17:41:07 +00001618 // Ignore empty structs/unions on non-Windows.
1619 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001620 return ABIArgInfo::getIgnore();
1621
Rafael Espindolafad28de2012-10-24 01:59:00 +00001622 llvm::LLVMContext &LLVMContext = getVMContext();
1623 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001624 bool NeedsPadding = false;
1625 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001626 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001627 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001628 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001629 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001630 if (InReg)
1631 return ABIArgInfo::getDirectInReg(Result);
1632 else
1633 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001634 }
Craig Topper8a13c412014-05-21 05:09:00 +00001635 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001636
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001637 // Expand small (<= 128-bit) record types when we know that the stack layout
1638 // of those arguments will match the struct. This is important because the
1639 // LLVM backend isn't smart enough to remove byval, which inhibits many
1640 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001641 // Don't do this for the MCU if there are still free integer registers
1642 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001643 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1644 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001645 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001646 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001647 State.CC == llvm::CallingConv::X86_VectorCall ||
1648 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001649 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001650
Reid Kleckner661f35b2014-01-18 01:12:41 +00001651 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001652 }
1653
Chris Lattnerd774ae92010-08-26 20:05:13 +00001654 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001655 // On Darwin, some vectors are passed in memory, we handle this by passing
1656 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001657 if (IsDarwinVectorABI) {
1658 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001659 if ((Size == 8 || Size == 16 || Size == 32) ||
1660 (Size == 64 && VT->getNumElements() == 1))
1661 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1662 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001663 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001664
Chad Rosier651c1832013-03-25 21:00:27 +00001665 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1666 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001667
Chris Lattnerd774ae92010-08-26 20:05:13 +00001668 return ABIArgInfo::getDirect();
1669 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001670
1671
Chris Lattner458b2aa2010-07-29 02:16:43 +00001672 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1673 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001674
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001675 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001676
1677 if (Ty->isPromotableIntegerType()) {
1678 if (InReg)
1679 return ABIArgInfo::getExtendInReg();
1680 return ABIArgInfo::getExtend();
1681 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001682
Rafael Espindola703c47f2012-10-19 05:04:37 +00001683 if (InReg)
1684 return ABIArgInfo::getDirectInReg();
1685 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001686}
1687
Erich Keane521ed962017-01-05 00:20:51 +00001688void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1689 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001690 // Vectorcall x86 works subtly different than in x64, so the format is
1691 // a bit different than the x64 version. First, all vector types (not HVAs)
1692 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1693 // This differs from the x64 implementation, where the first 6 by INDEX get
1694 // registers.
1695 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1696 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1697 // first take up the remaining YMM/XMM registers. If insufficient registers
1698 // remain but an integer register (ECX/EDX) is available, it will be passed
1699 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001700 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001701 // First pass do all the vector types.
1702 const Type *Base = nullptr;
1703 uint64_t NumElts = 0;
1704 const QualType& Ty = I.type;
1705 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1706 isHomogeneousAggregate(Ty, Base, NumElts)) {
1707 if (State.FreeSSERegs >= NumElts) {
1708 State.FreeSSERegs -= NumElts;
1709 I.info = ABIArgInfo::getDirect();
1710 } else {
1711 I.info = classifyArgumentType(Ty, State);
1712 }
1713 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1714 }
Erich Keane521ed962017-01-05 00:20:51 +00001715 }
Erich Keane4bd39302017-06-21 16:37:22 +00001716
Erich Keane521ed962017-01-05 00:20:51 +00001717 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001718 // Second pass, do the rest!
1719 const Type *Base = nullptr;
1720 uint64_t NumElts = 0;
1721 const QualType& Ty = I.type;
1722 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1723
1724 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1725 // Assign true HVAs (non vector/native FP types).
1726 if (State.FreeSSERegs >= NumElts) {
1727 State.FreeSSERegs -= NumElts;
1728 I.info = getDirectX86Hva();
1729 } else {
1730 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1731 }
1732 } else if (!IsHva) {
1733 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1734 I.info = classifyArgumentType(Ty, State);
1735 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1736 }
Erich Keane521ed962017-01-05 00:20:51 +00001737 }
1738}
1739
Rafael Espindolaa6472962012-07-24 00:01:07 +00001740void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001741 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001742 if (IsMCUABI)
1743 State.FreeRegs = 3;
1744 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001745 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001746 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1747 State.FreeRegs = 2;
1748 State.FreeSSERegs = 6;
1749 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001750 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001751 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1752 State.FreeRegs = 5;
1753 State.FreeSSERegs = 8;
1754 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001755 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001756
Reid Kleckner677539d2014-07-10 01:58:55 +00001757 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001758 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001759 } else if (FI.getReturnInfo().isIndirect()) {
1760 // The C++ ABI is not aware of register usage, so we have to check if the
1761 // return value was sret and put it in a register ourselves if appropriate.
1762 if (State.FreeRegs) {
1763 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001764 if (!IsMCUABI)
1765 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001766 }
1767 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001768
Peter Collingbournef7706832014-12-12 23:41:25 +00001769 // The chain argument effectively gives us another free register.
1770 if (FI.isChainCall())
1771 ++State.FreeRegs;
1772
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001773 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001774 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1775 computeVectorCallArgs(FI, State, UsedInAlloca);
1776 } else {
1777 // If not vectorcall, revert to normal behavior.
1778 for (auto &I : FI.arguments()) {
1779 I.info = classifyArgumentType(I.type, State);
1780 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1781 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001782 }
1783
1784 // If we needed to use inalloca for any argument, do a second pass and rewrite
1785 // all the memory arguments to use inalloca.
1786 if (UsedInAlloca)
1787 rewriteWithInAlloca(FI);
1788}
1789
1790void
1791X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001792 CharUnits &StackOffset, ABIArgInfo &Info,
1793 QualType Type) const {
1794 // Arguments are always 4-byte-aligned.
1795 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1796
1797 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001798 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1799 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001800 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001801
John McCall7f416cc2015-09-08 08:05:57 +00001802 // Insert padding bytes to respect alignment.
1803 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001804 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001805 if (StackOffset != FieldEnd) {
1806 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001807 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001808 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001809 FrameFields.push_back(Ty);
1810 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001811}
1812
Reid Kleckner852361d2014-07-26 00:12:26 +00001813static bool isArgInAlloca(const ABIArgInfo &Info) {
1814 // Leave ignored and inreg arguments alone.
1815 switch (Info.getKind()) {
1816 case ABIArgInfo::InAlloca:
1817 return true;
1818 case ABIArgInfo::Indirect:
1819 assert(Info.getIndirectByVal());
1820 return true;
1821 case ABIArgInfo::Ignore:
1822 return false;
1823 case ABIArgInfo::Direct:
1824 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001825 if (Info.getInReg())
1826 return false;
1827 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001828 case ABIArgInfo::Expand:
1829 case ABIArgInfo::CoerceAndExpand:
1830 // These are aggregate types which are never passed in registers when
1831 // inalloca is involved.
1832 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001833 }
1834 llvm_unreachable("invalid enum");
1835}
1836
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001837void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1838 assert(IsWin32StructABI && "inalloca only supported on win32");
1839
1840 // Build a packed struct type for all of the arguments in memory.
1841 SmallVector<llvm::Type *, 6> FrameFields;
1842
John McCall7f416cc2015-09-08 08:05:57 +00001843 // The stack alignment is always 4.
1844 CharUnits StackAlign = CharUnits::fromQuantity(4);
1845
1846 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001847 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1848
1849 // Put 'this' into the struct before 'sret', if necessary.
1850 bool IsThisCall =
1851 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1852 ABIArgInfo &Ret = FI.getReturnInfo();
1853 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1854 isArgInAlloca(I->info)) {
1855 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1856 ++I;
1857 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001858
1859 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001860 if (Ret.isIndirect() && !Ret.getInReg()) {
1861 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1862 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001863 // On Windows, the hidden sret parameter is always returned in eax.
1864 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001865 }
1866
1867 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001868 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001869 ++I;
1870
1871 // Put arguments passed in memory into the struct.
1872 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001873 if (isArgInAlloca(I->info))
1874 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001875 }
1876
1877 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001878 /*isPacked=*/true),
1879 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001880}
1881
John McCall7f416cc2015-09-08 08:05:57 +00001882Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1883 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001884
John McCall7f416cc2015-09-08 08:05:57 +00001885 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001886
John McCall7f416cc2015-09-08 08:05:57 +00001887 // x86-32 changes the alignment of certain arguments on the stack.
1888 //
1889 // Just messing with TypeInfo like this works because we never pass
1890 // anything indirectly.
1891 TypeInfo.second = CharUnits::fromQuantity(
1892 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001893
John McCall7f416cc2015-09-08 08:05:57 +00001894 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1895 TypeInfo, CharUnits::fromQuantity(4),
1896 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001897}
1898
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001899bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1900 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1901 assert(Triple.getArch() == llvm::Triple::x86);
1902
1903 switch (Opts.getStructReturnConvention()) {
1904 case CodeGenOptions::SRCK_Default:
1905 break;
1906 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1907 return false;
1908 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1909 return true;
1910 }
1911
Michael Kupersteind749f232015-10-27 07:46:22 +00001912 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001913 return true;
1914
1915 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001916 case llvm::Triple::DragonFly:
1917 case llvm::Triple::FreeBSD:
1918 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001919 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001920 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001921 default:
1922 return false;
1923 }
1924}
1925
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001926void X86_32TargetCodeGenInfo::setTargetAttributes(
1927 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
1928 ForDefinition_t IsForDefinition) const {
1929 if (!IsForDefinition)
1930 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001931 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001932 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1933 // Get the LLVM function.
1934 llvm::Function *Fn = cast<llvm::Function>(GV);
1935
1936 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001937 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001938 B.addStackAlignmentAttr(16);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001939 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Charles Davis4ea31ab2010-02-13 15:54:06 +00001940 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001941 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1942 llvm::Function *Fn = cast<llvm::Function>(GV);
1943 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1944 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001945 }
1946}
1947
John McCallbeec5a02010-03-06 00:35:14 +00001948bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1949 CodeGen::CodeGenFunction &CGF,
1950 llvm::Value *Address) const {
1951 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001952
Chris Lattnerece04092012-02-07 00:39:47 +00001953 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001954
John McCallbeec5a02010-03-06 00:35:14 +00001955 // 0-7 are the eight integer registers; the order is different
1956 // on Darwin (for EH), but the range is the same.
1957 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001958 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001959
John McCallc8e01702013-04-16 22:48:15 +00001960 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001961 // 12-16 are st(0..4). Not sure why we stop at 4.
1962 // These have size 16, which is sizeof(long double) on
1963 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001964 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001965 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001966
John McCallbeec5a02010-03-06 00:35:14 +00001967 } else {
1968 // 9 is %eflags, which doesn't get a size on Darwin for some
1969 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001970 Builder.CreateAlignedStore(
1971 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1972 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001973
1974 // 11-16 are st(0..5). Not sure why we stop at 5.
1975 // These have size 12, which is sizeof(long double) on
1976 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001977 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001978 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1979 }
John McCallbeec5a02010-03-06 00:35:14 +00001980
1981 return false;
1982}
1983
Chris Lattner0cf24192010-06-28 20:05:43 +00001984//===----------------------------------------------------------------------===//
1985// X86-64 ABI Implementation
1986//===----------------------------------------------------------------------===//
1987
1988
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001989namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001990/// The AVX ABI level for X86 targets.
1991enum class X86AVXABILevel {
1992 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001993 AVX,
1994 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001995};
1996
1997/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1998static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1999 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002000 case X86AVXABILevel::AVX512:
2001 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002002 case X86AVXABILevel::AVX:
2003 return 256;
2004 case X86AVXABILevel::None:
2005 return 128;
2006 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002007 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002008}
2009
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002010/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002011class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002012 enum Class {
2013 Integer = 0,
2014 SSE,
2015 SSEUp,
2016 X87,
2017 X87Up,
2018 ComplexX87,
2019 NoClass,
2020 Memory
2021 };
2022
2023 /// merge - Implement the X86_64 ABI merging algorithm.
2024 ///
2025 /// Merge an accumulating classification \arg Accum with a field
2026 /// classification \arg Field.
2027 ///
2028 /// \param Accum - The accumulating classification. This should
2029 /// always be either NoClass or the result of a previous merge
2030 /// call. In addition, this should never be Memory (the caller
2031 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002032 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002033
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002034 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2035 ///
2036 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2037 /// final MEMORY or SSE classes when necessary.
2038 ///
2039 /// \param AggregateSize - The size of the current aggregate in
2040 /// the classification process.
2041 ///
2042 /// \param Lo - The classification for the parts of the type
2043 /// residing in the low word of the containing object.
2044 ///
2045 /// \param Hi - The classification for the parts of the type
2046 /// residing in the higher words of the containing object.
2047 ///
2048 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2049
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002050 /// classify - Determine the x86_64 register classes in which the
2051 /// given type T should be passed.
2052 ///
2053 /// \param Lo - The classification for the parts of the type
2054 /// residing in the low word of the containing object.
2055 ///
2056 /// \param Hi - The classification for the parts of the type
2057 /// residing in the high word of the containing object.
2058 ///
2059 /// \param OffsetBase - The bit offset of this type in the
2060 /// containing object. Some parameters are classified different
2061 /// depending on whether they straddle an eightbyte boundary.
2062 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002063 /// \param isNamedArg - Whether the argument in question is a "named"
2064 /// argument, as used in AMD64-ABI 3.5.7.
2065 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002066 /// If a word is unused its result will be NoClass; if a type should
2067 /// be passed in Memory then at least the classification of \arg Lo
2068 /// will be Memory.
2069 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002070 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002071 ///
2072 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2073 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002074 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2075 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002076
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002077 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002078 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2079 unsigned IROffset, QualType SourceTy,
2080 unsigned SourceOffset) const;
2081 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2082 unsigned IROffset, QualType SourceTy,
2083 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002084
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002085 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002086 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002087 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002088
2089 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002090 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002091 ///
2092 /// \param freeIntRegs - The number of free integer registers remaining
2093 /// available.
2094 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002095
Chris Lattner458b2aa2010-07-29 02:16:43 +00002096 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002097
Erich Keane757d3172016-11-02 18:29:35 +00002098 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2099 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002100 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002101
Erich Keane757d3172016-11-02 18:29:35 +00002102 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2103 unsigned &NeededSSE) const;
2104
2105 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2106 unsigned &NeededSSE) const;
2107
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002108 bool IsIllegalVectorType(QualType Ty) const;
2109
John McCalle0fda732011-04-21 01:20:55 +00002110 /// The 0.98 ABI revision clarified a lot of ambiguities,
2111 /// unfortunately in ways that were not always consistent with
2112 /// certain previous compilers. In particular, platforms which
2113 /// required strict binary compatibility with older versions of GCC
2114 /// may need to exempt themselves.
2115 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002116 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002117 }
2118
Richard Smithf667ad52017-08-26 01:04:35 +00002119 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2120 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002121 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002122 // Clang <= 3.8 did not do this.
2123 if (getCodeGenOpts().getClangABICompat() <=
2124 CodeGenOptions::ClangABI::Ver3_8)
2125 return false;
2126
David Majnemere2ae2282016-03-04 05:26:16 +00002127 const llvm::Triple &Triple = getTarget().getTriple();
2128 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2129 return false;
2130 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2131 return false;
2132 return true;
2133 }
2134
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002135 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002136 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2137 // 64-bit hardware.
2138 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002139
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002140public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002141 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002142 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002143 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002144 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002145
John McCalla729c622012-02-17 03:33:10 +00002146 bool isPassedUsingAVXType(QualType type) const {
2147 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002148 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002149 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2150 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002151 if (info.isDirect()) {
2152 llvm::Type *ty = info.getCoerceToType();
2153 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2154 return (vectorTy->getBitWidth() > 128);
2155 }
2156 return false;
2157 }
2158
Craig Topper4f12f102014-03-12 06:41:41 +00002159 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002160
John McCall7f416cc2015-09-08 08:05:57 +00002161 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2162 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002163 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2164 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002165
2166 bool has64BitPointers() const {
2167 return Has64BitPointers;
2168 }
John McCall12f23522016-04-04 18:33:08 +00002169
John McCall56331e22018-01-07 06:28:49 +00002170 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00002171 bool asReturnValue) const override {
2172 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2173 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002174 bool isSwiftErrorInRegister() const override {
2175 return true;
2176 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002177};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002178
Chris Lattner04dc9572010-08-31 16:44:54 +00002179/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002180class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002181public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002182 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002183 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002184 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002185
Craig Topper4f12f102014-03-12 06:41:41 +00002186 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002187
John McCall7f416cc2015-09-08 08:05:57 +00002188 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2189 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002190
2191 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2192 // FIXME: Assumes vectorcall is in use.
2193 return isX86VectorTypeForVectorCall(getContext(), Ty);
2194 }
2195
2196 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2197 uint64_t NumMembers) const override {
2198 // FIXME: Assumes vectorcall is in use.
2199 return isX86VectorCallAggregateSmallEnough(NumMembers);
2200 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002201
John McCall56331e22018-01-07 06:28:49 +00002202 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002203 bool asReturnValue) const override {
2204 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2205 }
2206
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002207 bool isSwiftErrorInRegister() const override {
2208 return true;
2209 }
2210
Reid Kleckner11a17192015-10-28 22:29:52 +00002211private:
Erich Keane521ed962017-01-05 00:20:51 +00002212 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2213 bool IsVectorCall, bool IsRegCall) const;
2214 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2215 const ABIArgInfo &current) const;
2216 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2217 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002218
Erich Keane521ed962017-01-05 00:20:51 +00002219 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002220};
2221
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002222class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2223public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002224 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002225 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002226
John McCalla729c622012-02-17 03:33:10 +00002227 const X86_64ABIInfo &getABIInfo() const {
2228 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2229 }
2230
Craig Topper4f12f102014-03-12 06:41:41 +00002231 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002232 return 7;
2233 }
2234
2235 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002236 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002237 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002238
John McCall943fae92010-05-27 06:19:26 +00002239 // 0-15 are the 16 integer registers.
2240 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002241 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002242 return false;
2243 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002244
Jay Foad7c57be32011-07-11 09:56:20 +00002245 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002246 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002247 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002248 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2249 }
2250
John McCalla729c622012-02-17 03:33:10 +00002251 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002252 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002253 // The default CC on x86-64 sets %al to the number of SSA
2254 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002255 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002256 // that when AVX types are involved: the ABI explicitly states it is
2257 // undefined, and it doesn't work in practice because of how the ABI
2258 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002259 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002260 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002261 for (CallArgList::const_iterator
2262 it = args.begin(), ie = args.end(); it != ie; ++it) {
2263 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2264 HasAVXType = true;
2265 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002266 }
2267 }
John McCalla729c622012-02-17 03:33:10 +00002268
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002269 if (!HasAVXType)
2270 return true;
2271 }
John McCallcbc038a2011-09-21 08:08:30 +00002272
John McCalla729c622012-02-17 03:33:10 +00002273 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002274 }
2275
Craig Topper4f12f102014-03-12 06:41:41 +00002276 llvm::Constant *
2277 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002278 unsigned Sig = (0xeb << 0) | // jmp rel8
2279 (0x06 << 8) | // .+0x08
2280 ('v' << 16) |
2281 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002282 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2283 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002284
2285 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002286 CodeGen::CodeGenModule &CGM,
2287 ForDefinition_t IsForDefinition) const override {
2288 if (!IsForDefinition)
2289 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002290 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002291 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2292 // Get the LLVM function.
2293 auto *Fn = cast<llvm::Function>(GV);
2294
2295 // Now add the 'alignstack' attribute with a value of 16.
2296 llvm::AttrBuilder B;
2297 B.addStackAlignmentAttr(16);
2298 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2299 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002300 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2301 llvm::Function *Fn = cast<llvm::Function>(GV);
2302 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2303 }
2304 }
2305 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002306};
2307
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002308class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2309public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002310 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2311 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002312
2313 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002314 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002315 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002316 // If the argument contains a space, enclose it in quotes.
2317 if (Lib.find(" ") != StringRef::npos)
2318 Opt += "\"" + Lib.str() + "\"";
2319 else
2320 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002321 }
2322};
2323
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002324static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002325 // If the argument does not end in .lib, automatically add the suffix.
2326 // If the argument contains a space, enclose it in quotes.
2327 // This matches the behavior of MSVC.
2328 bool Quote = (Lib.find(" ") != StringRef::npos);
2329 std::string ArgStr = Quote ? "\"" : "";
2330 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002331 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002332 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002333 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002334 return ArgStr;
2335}
2336
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002337class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2338public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002339 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002340 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2341 unsigned NumRegisterParameters)
2342 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002343 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002344
Eric Christopher162c91c2015-06-05 22:03:00 +00002345 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002346 CodeGen::CodeGenModule &CGM,
2347 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002348
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002349 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002350 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002351 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002352 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002353 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002354
2355 void getDetectMismatchOption(llvm::StringRef Name,
2356 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002357 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002358 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002359 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002360};
2361
Hans Wennborg77dc2362015-01-20 19:45:50 +00002362static void addStackProbeSizeTargetAttribute(const Decl *D,
2363 llvm::GlobalValue *GV,
2364 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002365 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002366 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2367 llvm::Function *Fn = cast<llvm::Function>(GV);
2368
Eric Christopher7565e0d2015-05-29 23:09:49 +00002369 Fn->addFnAttr("stack-probe-size",
2370 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002371 }
2372 }
2373}
2374
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002375void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2376 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2377 ForDefinition_t IsForDefinition) const {
2378 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2379 if (!IsForDefinition)
2380 return;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002381 addStackProbeSizeTargetAttribute(D, GV, CGM);
2382}
2383
Chris Lattner04dc9572010-08-31 16:44:54 +00002384class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2385public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002386 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2387 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002388 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002389
Eric Christopher162c91c2015-06-05 22:03:00 +00002390 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002391 CodeGen::CodeGenModule &CGM,
2392 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002393
Craig Topper4f12f102014-03-12 06:41:41 +00002394 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002395 return 7;
2396 }
2397
2398 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002399 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002400 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002401
Chris Lattner04dc9572010-08-31 16:44:54 +00002402 // 0-15 are the 16 integer registers.
2403 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002404 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002405 return false;
2406 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002407
2408 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002409 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002410 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002411 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002412 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002413
2414 void getDetectMismatchOption(llvm::StringRef Name,
2415 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002416 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002417 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002418 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002419};
2420
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002421void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2422 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2423 ForDefinition_t IsForDefinition) const {
2424 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2425 if (!IsForDefinition)
2426 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002427 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002428 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2429 // Get the LLVM function.
2430 auto *Fn = cast<llvm::Function>(GV);
2431
2432 // Now add the 'alignstack' attribute with a value of 16.
2433 llvm::AttrBuilder B;
2434 B.addStackAlignmentAttr(16);
2435 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2436 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002437 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2438 llvm::Function *Fn = cast<llvm::Function>(GV);
2439 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2440 }
2441 }
2442
Hans Wennborg77dc2362015-01-20 19:45:50 +00002443 addStackProbeSizeTargetAttribute(D, GV, CGM);
2444}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002445}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002446
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002447void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2448 Class &Hi) const {
2449 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2450 //
2451 // (a) If one of the classes is Memory, the whole argument is passed in
2452 // memory.
2453 //
2454 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2455 // memory.
2456 //
2457 // (c) If the size of the aggregate exceeds two eightbytes and the first
2458 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2459 // argument is passed in memory. NOTE: This is necessary to keep the
2460 // ABI working for processors that don't support the __m256 type.
2461 //
2462 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2463 //
2464 // Some of these are enforced by the merging logic. Others can arise
2465 // only with unions; for example:
2466 // union { _Complex double; unsigned; }
2467 //
2468 // Note that clauses (b) and (c) were added in 0.98.
2469 //
2470 if (Hi == Memory)
2471 Lo = Memory;
2472 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2473 Lo = Memory;
2474 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2475 Lo = Memory;
2476 if (Hi == SSEUp && Lo != SSE)
2477 Hi = SSE;
2478}
2479
Chris Lattnerd776fb12010-06-28 21:43:59 +00002480X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002481 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2482 // classified recursively so that always two fields are
2483 // considered. The resulting class is calculated according to
2484 // the classes of the fields in the eightbyte:
2485 //
2486 // (a) If both classes are equal, this is the resulting class.
2487 //
2488 // (b) If one of the classes is NO_CLASS, the resulting class is
2489 // the other class.
2490 //
2491 // (c) If one of the classes is MEMORY, the result is the MEMORY
2492 // class.
2493 //
2494 // (d) If one of the classes is INTEGER, the result is the
2495 // INTEGER.
2496 //
2497 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2498 // MEMORY is used as class.
2499 //
2500 // (f) Otherwise class SSE is used.
2501
2502 // Accum should never be memory (we should have returned) or
2503 // ComplexX87 (because this cannot be passed in a structure).
2504 assert((Accum != Memory && Accum != ComplexX87) &&
2505 "Invalid accumulated classification during merge.");
2506 if (Accum == Field || Field == NoClass)
2507 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002508 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002509 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002510 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002511 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002512 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002513 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002514 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2515 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002516 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002517 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002518}
2519
Chris Lattner5c740f12010-06-30 19:14:05 +00002520void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002521 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002522 // FIXME: This code can be simplified by introducing a simple value class for
2523 // Class pairs with appropriate constructor methods for the various
2524 // situations.
2525
2526 // FIXME: Some of the split computations are wrong; unaligned vectors
2527 // shouldn't be passed in registers for example, so there is no chance they
2528 // can straddle an eightbyte. Verify & simplify.
2529
2530 Lo = Hi = NoClass;
2531
2532 Class &Current = OffsetBase < 64 ? Lo : Hi;
2533 Current = Memory;
2534
John McCall9dd450b2009-09-21 23:43:11 +00002535 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002536 BuiltinType::Kind k = BT->getKind();
2537
2538 if (k == BuiltinType::Void) {
2539 Current = NoClass;
2540 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2541 Lo = Integer;
2542 Hi = Integer;
2543 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2544 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002545 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002546 Current = SSE;
2547 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002548 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002549 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002550 Lo = SSE;
2551 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002552 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002553 Lo = X87;
2554 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002555 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002556 Current = SSE;
2557 } else
2558 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002559 }
2560 // FIXME: _Decimal32 and _Decimal64 are SSE.
2561 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002562 return;
2563 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002564
Chris Lattnerd776fb12010-06-28 21:43:59 +00002565 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002566 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002567 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002568 return;
2569 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002570
Chris Lattnerd776fb12010-06-28 21:43:59 +00002571 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002572 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002573 return;
2574 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002575
Chris Lattnerd776fb12010-06-28 21:43:59 +00002576 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002577 if (Ty->isMemberFunctionPointerType()) {
2578 if (Has64BitPointers) {
2579 // If Has64BitPointers, this is an {i64, i64}, so classify both
2580 // Lo and Hi now.
2581 Lo = Hi = Integer;
2582 } else {
2583 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2584 // straddles an eightbyte boundary, Hi should be classified as well.
2585 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2586 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2587 if (EB_FuncPtr != EB_ThisAdj) {
2588 Lo = Hi = Integer;
2589 } else {
2590 Current = Integer;
2591 }
2592 }
2593 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002594 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002595 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002596 return;
2597 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002598
Chris Lattnerd776fb12010-06-28 21:43:59 +00002599 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002600 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002601 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2602 // gcc passes the following as integer:
2603 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2604 // 2 bytes - <2 x char>, <1 x short>
2605 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002606 Current = Integer;
2607
2608 // If this type crosses an eightbyte boundary, it should be
2609 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002610 uint64_t EB_Lo = (OffsetBase) / 64;
2611 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2612 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002613 Hi = Lo;
2614 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002615 QualType ElementType = VT->getElementType();
2616
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002617 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002618 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002619 return;
2620
David Majnemere2ae2282016-03-04 05:26:16 +00002621 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2622 // pass them as integer. For platforms where clang is the de facto
2623 // platform compiler, we must continue to use integer.
2624 if (!classifyIntegerMMXAsSSE() &&
2625 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2626 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2627 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2628 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002629 Current = Integer;
2630 else
2631 Current = SSE;
2632
2633 // If this type crosses an eightbyte boundary, it should be
2634 // split.
2635 if (OffsetBase && OffsetBase != 64)
2636 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002637 } else if (Size == 128 ||
2638 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002639 // Arguments of 256-bits are split into four eightbyte chunks. The
2640 // least significant one belongs to class SSE and all the others to class
2641 // SSEUP. The original Lo and Hi design considers that types can't be
2642 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2643 // This design isn't correct for 256-bits, but since there're no cases
2644 // where the upper parts would need to be inspected, avoid adding
2645 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002646 //
2647 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2648 // registers if they are "named", i.e. not part of the "..." of a
2649 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002650 //
2651 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2652 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002653 Lo = SSE;
2654 Hi = SSEUp;
2655 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002656 return;
2657 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002658
Chris Lattnerd776fb12010-06-28 21:43:59 +00002659 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002660 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661
Chris Lattner2b037972010-07-29 02:01:43 +00002662 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002663 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002664 if (Size <= 64)
2665 Current = Integer;
2666 else if (Size <= 128)
2667 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002668 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002669 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002670 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002671 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002672 } else if (ET == getContext().LongDoubleTy) {
2673 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002674 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002675 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002676 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002677 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002678 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002679 Lo = Hi = SSE;
2680 else
2681 llvm_unreachable("unexpected long double representation!");
2682 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002683
2684 // If this complex type crosses an eightbyte boundary then it
2685 // should be split.
2686 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002687 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002688 if (Hi == NoClass && EB_Real != EB_Imag)
2689 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002690
Chris Lattnerd776fb12010-06-28 21:43:59 +00002691 return;
2692 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002693
Chris Lattner2b037972010-07-29 02:01:43 +00002694 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002695 // Arrays are treated like structures.
2696
Chris Lattner2b037972010-07-29 02:01:43 +00002697 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002698
2699 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002700 // than eight eightbytes, ..., it has class MEMORY.
2701 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002702 return;
2703
2704 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2705 // fields, it has class MEMORY.
2706 //
2707 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002708 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002709 return;
2710
2711 // Otherwise implement simplified merge. We could be smarter about
2712 // this, but it isn't worth it and would be harder to verify.
2713 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002714 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002715 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002716
2717 // The only case a 256-bit wide vector could be used is when the array
2718 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2719 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002720 //
2721 if (Size > 128 &&
2722 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002723 return;
2724
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002725 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2726 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002727 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002728 Lo = merge(Lo, FieldLo);
2729 Hi = merge(Hi, FieldHi);
2730 if (Lo == Memory || Hi == Memory)
2731 break;
2732 }
2733
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002734 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002735 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002736 return;
2737 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002738
Chris Lattnerd776fb12010-06-28 21:43:59 +00002739 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002740 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002741
2742 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002743 // than eight eightbytes, ..., it has class MEMORY.
2744 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002745 return;
2746
Anders Carlsson20759ad2009-09-16 15:53:40 +00002747 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2748 // copy constructor or a non-trivial destructor, it is passed by invisible
2749 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002750 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002751 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002752
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002753 const RecordDecl *RD = RT->getDecl();
2754
2755 // Assume variable sized types are passed in memory.
2756 if (RD->hasFlexibleArrayMember())
2757 return;
2758
Chris Lattner2b037972010-07-29 02:01:43 +00002759 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002760
2761 // Reset Lo class, this will be recomputed.
2762 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002763
2764 // If this is a C++ record, classify the bases first.
2765 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002766 for (const auto &I : CXXRD->bases()) {
2767 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002768 "Unexpected base class!");
2769 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002770 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002771
2772 // Classify this field.
2773 //
2774 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2775 // single eightbyte, each is classified separately. Each eightbyte gets
2776 // initialized to class NO_CLASS.
2777 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002778 uint64_t Offset =
2779 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002780 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002781 Lo = merge(Lo, FieldLo);
2782 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002783 if (Lo == Memory || Hi == Memory) {
2784 postMerge(Size, Lo, Hi);
2785 return;
2786 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002787 }
2788 }
2789
2790 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002791 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002792 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002793 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002794 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2795 bool BitField = i->isBitField();
2796
David Majnemerb439dfe2016-08-15 07:20:40 +00002797 // Ignore padding bit-fields.
2798 if (BitField && i->isUnnamedBitfield())
2799 continue;
2800
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002801 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2802 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002803 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002804 // The only case a 256-bit wide vector could be used is when the struct
2805 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2806 // to work for sizes wider than 128, early check and fallback to memory.
2807 //
David Majnemerb229cb02016-08-15 06:39:18 +00002808 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2809 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002810 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002811 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002812 return;
2813 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002814 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002815 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002816 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002817 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002818 return;
2819 }
2820
2821 // Classify this field.
2822 //
2823 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2824 // exceeds a single eightbyte, each is classified
2825 // separately. Each eightbyte gets initialized to class
2826 // NO_CLASS.
2827 Class FieldLo, FieldHi;
2828
2829 // Bit-fields require special handling, they do not force the
2830 // structure to be passed in memory even if unaligned, and
2831 // therefore they can straddle an eightbyte.
2832 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002833 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002834 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002835 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002836
2837 uint64_t EB_Lo = Offset / 64;
2838 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002839
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002840 if (EB_Lo) {
2841 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2842 FieldLo = NoClass;
2843 FieldHi = Integer;
2844 } else {
2845 FieldLo = Integer;
2846 FieldHi = EB_Hi ? Integer : NoClass;
2847 }
2848 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002849 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002850 Lo = merge(Lo, FieldLo);
2851 Hi = merge(Hi, FieldHi);
2852 if (Lo == Memory || Hi == Memory)
2853 break;
2854 }
2855
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002856 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002857 }
2858}
2859
Chris Lattner22a931e2010-06-29 06:01:59 +00002860ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002861 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2862 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002863 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002864 // Treat an enum type as its underlying type.
2865 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2866 Ty = EnumTy->getDecl()->getIntegerType();
2867
2868 return (Ty->isPromotableIntegerType() ?
2869 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2870 }
2871
John McCall7f416cc2015-09-08 08:05:57 +00002872 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002873}
2874
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002875bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2876 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2877 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002878 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002879 if (Size <= 64 || Size > LargestVector)
2880 return true;
2881 }
2882
2883 return false;
2884}
2885
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002886ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2887 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002888 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2889 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002890 //
2891 // This assumption is optimistic, as there could be free registers available
2892 // when we need to pass this argument in memory, and LLVM could try to pass
2893 // the argument in the free register. This does not seem to happen currently,
2894 // but this code would be much safer if we could mark the argument with
2895 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002896 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002897 // Treat an enum type as its underlying type.
2898 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2899 Ty = EnumTy->getDecl()->getIntegerType();
2900
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002901 return (Ty->isPromotableIntegerType() ?
2902 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002903 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002904
Mark Lacey3825e832013-10-06 01:33:34 +00002905 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002906 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002907
Chris Lattner44c2b902011-05-22 23:21:23 +00002908 // Compute the byval alignment. We specify the alignment of the byval in all
2909 // cases so that the mid-level optimizer knows the alignment of the byval.
2910 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002911
2912 // Attempt to avoid passing indirect results using byval when possible. This
2913 // is important for good codegen.
2914 //
2915 // We do this by coercing the value into a scalar type which the backend can
2916 // handle naturally (i.e., without using byval).
2917 //
2918 // For simplicity, we currently only do this when we have exhausted all of the
2919 // free integer registers. Doing this when there are free integer registers
2920 // would require more care, as we would have to ensure that the coerced value
2921 // did not claim the unused register. That would require either reording the
2922 // arguments to the function (so that any subsequent inreg values came first),
2923 // or only doing this optimization when there were no following arguments that
2924 // might be inreg.
2925 //
2926 // We currently expect it to be rare (particularly in well written code) for
2927 // arguments to be passed on the stack when there are still free integer
2928 // registers available (this would typically imply large structs being passed
2929 // by value), so this seems like a fair tradeoff for now.
2930 //
2931 // We can revisit this if the backend grows support for 'onstack' parameter
2932 // attributes. See PR12193.
2933 if (freeIntRegs == 0) {
2934 uint64_t Size = getContext().getTypeSize(Ty);
2935
2936 // If this type fits in an eightbyte, coerce it into the matching integral
2937 // type, which will end up on the stack (with alignment 8).
2938 if (Align == 8 && Size <= 64)
2939 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2940 Size));
2941 }
2942
John McCall7f416cc2015-09-08 08:05:57 +00002943 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002944}
2945
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002946/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2947/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002948llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002949 // Wrapper structs/arrays that only contain vectors are passed just like
2950 // vectors; strip them off if present.
2951 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2952 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002953
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002954 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002955 if (isa<llvm::VectorType>(IRType) ||
2956 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002957 return IRType;
2958
2959 // We couldn't find the preferred IR vector type for 'Ty'.
2960 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002961 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002962
2963 // Return a LLVM IR vector type based on the size of 'Ty'.
2964 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2965 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002966}
2967
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002968/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2969/// is known to either be off the end of the specified type or being in
2970/// alignment padding. The user type specified is known to be at most 128 bits
2971/// in size, and have passed through X86_64ABIInfo::classify with a successful
2972/// classification that put one of the two halves in the INTEGER class.
2973///
2974/// It is conservatively correct to return false.
2975static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2976 unsigned EndBit, ASTContext &Context) {
2977 // If the bytes being queried are off the end of the type, there is no user
2978 // data hiding here. This handles analysis of builtins, vectors and other
2979 // types that don't contain interesting padding.
2980 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2981 if (TySize <= StartBit)
2982 return true;
2983
Chris Lattner98076a22010-07-29 07:43:55 +00002984 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2985 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2986 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2987
2988 // Check each element to see if the element overlaps with the queried range.
2989 for (unsigned i = 0; i != NumElts; ++i) {
2990 // If the element is after the span we care about, then we're done..
2991 unsigned EltOffset = i*EltSize;
2992 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002993
Chris Lattner98076a22010-07-29 07:43:55 +00002994 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2995 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2996 EndBit-EltOffset, Context))
2997 return false;
2998 }
2999 // If it overlaps no elements, then it is safe to process as padding.
3000 return true;
3001 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003002
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003003 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3004 const RecordDecl *RD = RT->getDecl();
3005 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003006
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003007 // If this is a C++ record, check the bases first.
3008 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003009 for (const auto &I : CXXRD->bases()) {
3010 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003011 "Unexpected base class!");
3012 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003013 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003014
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003015 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003016 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003017 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003018
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003019 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003020 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003021 EndBit-BaseOffset, Context))
3022 return false;
3023 }
3024 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003025
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003026 // Verify that no field has data that overlaps the region of interest. Yes
3027 // this could be sped up a lot by being smarter about queried fields,
3028 // however we're only looking at structs up to 16 bytes, so we don't care
3029 // much.
3030 unsigned idx = 0;
3031 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3032 i != e; ++i, ++idx) {
3033 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003034
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003035 // If we found a field after the region we care about, then we're done.
3036 if (FieldOffset >= EndBit) break;
3037
3038 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3039 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3040 Context))
3041 return false;
3042 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003043
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003044 // If nothing in this record overlapped the area of interest, then we're
3045 // clean.
3046 return true;
3047 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003048
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003049 return false;
3050}
3051
Chris Lattnere556a712010-07-29 18:39:32 +00003052/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3053/// float member at the specified offset. For example, {int,{float}} has a
3054/// float at offset 4. It is conservatively correct for this routine to return
3055/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003056static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003057 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003058 // Base case if we find a float.
3059 if (IROffset == 0 && IRType->isFloatTy())
3060 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003061
Chris Lattnere556a712010-07-29 18:39:32 +00003062 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003063 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003064 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3065 unsigned Elt = SL->getElementContainingOffset(IROffset);
3066 IROffset -= SL->getElementOffset(Elt);
3067 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3068 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003069
Chris Lattnere556a712010-07-29 18:39:32 +00003070 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003071 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3072 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003073 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3074 IROffset -= IROffset/EltSize*EltSize;
3075 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3076 }
3077
3078 return false;
3079}
3080
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003081
3082/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3083/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003084llvm::Type *X86_64ABIInfo::
3085GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003086 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003087 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003088 // pass as float if the last 4 bytes is just padding. This happens for
3089 // structs that contain 3 floats.
3090 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3091 SourceOffset*8+64, getContext()))
3092 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003093
Chris Lattnere556a712010-07-29 18:39:32 +00003094 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3095 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3096 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003097 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3098 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003099 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003100
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003101 return llvm::Type::getDoubleTy(getVMContext());
3102}
3103
3104
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003105/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3106/// an 8-byte GPR. This means that we either have a scalar or we are talking
3107/// about the high or low part of an up-to-16-byte struct. This routine picks
3108/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003109/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3110/// etc).
3111///
3112/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3113/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3114/// the 8-byte value references. PrefType may be null.
3115///
Alp Toker9907f082014-07-09 14:06:35 +00003116/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003117/// an offset into this that we're processing (which is always either 0 or 8).
3118///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003119llvm::Type *X86_64ABIInfo::
3120GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003121 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003122 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3123 // returning an 8-byte unit starting with it. See if we can safely use it.
3124 if (IROffset == 0) {
3125 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003126 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3127 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003128 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003129
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003130 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3131 // goodness in the source type is just tail padding. This is allowed to
3132 // kick in for struct {double,int} on the int, but not on
3133 // struct{double,int,int} because we wouldn't return the second int. We
3134 // have to do this analysis on the source type because we can't depend on
3135 // unions being lowered a specific way etc.
3136 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003137 IRType->isIntegerTy(32) ||
3138 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3139 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3140 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003141
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003142 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3143 SourceOffset*8+64, getContext()))
3144 return IRType;
3145 }
3146 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003147
Chris Lattner2192fe52011-07-18 04:24:23 +00003148 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003149 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003150 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003151 if (IROffset < SL->getSizeInBytes()) {
3152 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3153 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003154
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003155 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3156 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003157 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003158 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003159
Chris Lattner2192fe52011-07-18 04:24:23 +00003160 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003161 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003162 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003163 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003164 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3165 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003166 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003167
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003168 // Okay, we don't have any better idea of what to pass, so we pass this in an
3169 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003170 unsigned TySizeInBytes =
3171 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003172
Chris Lattner3f763422010-07-29 17:34:39 +00003173 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003174
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003175 // It is always safe to classify this as an integer type up to i64 that
3176 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003177 return llvm::IntegerType::get(getVMContext(),
3178 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003179}
3180
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003181
3182/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3183/// be used as elements of a two register pair to pass or return, return a
3184/// first class aggregate to represent them. For example, if the low part of
3185/// a by-value argument should be passed as i32* and the high part as float,
3186/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003187static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003188GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003189 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003190 // In order to correctly satisfy the ABI, we need to the high part to start
3191 // at offset 8. If the high and low parts we inferred are both 4-byte types
3192 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3193 // the second element at offset 8. Check for this:
3194 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3195 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003196 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003197 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003198
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003199 // To handle this, we have to increase the size of the low part so that the
3200 // second element will start at an 8 byte offset. We can't increase the size
3201 // of the second element because it might make us access off the end of the
3202 // struct.
3203 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003204 // There are usually two sorts of types the ABI generation code can produce
3205 // for the low part of a pair that aren't 8 bytes in size: float or
3206 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3207 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003208 // Promote these to a larger type.
3209 if (Lo->isFloatTy())
3210 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3211 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003212 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3213 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003214 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3215 }
3216 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003217
Serge Guelton1d993272017-05-09 19:31:30 +00003218 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003219
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003220 // Verify that the second element is at an 8-byte offset.
3221 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3222 "Invalid x86-64 argument pair!");
3223 return Result;
3224}
3225
Chris Lattner31faff52010-07-28 23:06:14 +00003226ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003227classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003228 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3229 // classification algorithm.
3230 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003231 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003232
3233 // Check some invariants.
3234 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003235 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3236
Craig Topper8a13c412014-05-21 05:09:00 +00003237 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003238 switch (Lo) {
3239 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003240 if (Hi == NoClass)
3241 return ABIArgInfo::getIgnore();
3242 // If the low part is just padding, it takes no register, leave ResType
3243 // null.
3244 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3245 "Unknown missing lo part");
3246 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003247
3248 case SSEUp:
3249 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003250 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003251
3252 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3253 // hidden argument.
3254 case Memory:
3255 return getIndirectReturnResult(RetTy);
3256
3257 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3258 // available register of the sequence %rax, %rdx is used.
3259 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003260 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003261
Chris Lattner1f3a0632010-07-29 21:42:50 +00003262 // If we have a sign or zero extended integer, make sure to return Extend
3263 // so that the parameter gets the right LLVM IR attributes.
3264 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3265 // Treat an enum type as its underlying type.
3266 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3267 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003268
Chris Lattner1f3a0632010-07-29 21:42:50 +00003269 if (RetTy->isIntegralOrEnumerationType() &&
3270 RetTy->isPromotableIntegerType())
3271 return ABIArgInfo::getExtend();
3272 }
Chris Lattner31faff52010-07-28 23:06:14 +00003273 break;
3274
3275 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3276 // available SSE register of the sequence %xmm0, %xmm1 is used.
3277 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003278 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003279 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003280
3281 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3282 // returned on the X87 stack in %st0 as 80-bit x87 number.
3283 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003284 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003285 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003286
3287 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3288 // part of the value is returned in %st0 and the imaginary part in
3289 // %st1.
3290 case ComplexX87:
3291 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003292 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003293 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003294 break;
3295 }
3296
Craig Topper8a13c412014-05-21 05:09:00 +00003297 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003298 switch (Hi) {
3299 // Memory was handled previously and X87 should
3300 // never occur as a hi class.
3301 case Memory:
3302 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003303 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003304
3305 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003306 case NoClass:
3307 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003308
Chris Lattner52b3c132010-09-01 00:20:33 +00003309 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003310 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003311 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3312 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003313 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003314 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003315 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003316 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3317 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003318 break;
3319
3320 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003321 // is passed in the next available eightbyte chunk if the last used
3322 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003323 //
Chris Lattner57540c52011-04-15 05:22:18 +00003324 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003325 case SSEUp:
3326 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003327 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003328 break;
3329
3330 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3331 // returned together with the previous X87 value in %st0.
3332 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003333 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003334 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003335 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003336 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003337 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003338 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003339 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3340 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003341 }
Chris Lattner31faff52010-07-28 23:06:14 +00003342 break;
3343 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003344
Chris Lattner52b3c132010-09-01 00:20:33 +00003345 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003346 // known to pass in the high eightbyte of the result. We do this by forming a
3347 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003348 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003349 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003350
Chris Lattner1f3a0632010-07-29 21:42:50 +00003351 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003352}
3353
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003354ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003355 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3356 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003357 const
3358{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003359 Ty = useFirstFieldIfTransparentUnion(Ty);
3360
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003361 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003362 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003363
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003364 // Check some invariants.
3365 // FIXME: Enforce these by construction.
3366 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003367 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3368
3369 neededInt = 0;
3370 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003371 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003372 switch (Lo) {
3373 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003374 if (Hi == NoClass)
3375 return ABIArgInfo::getIgnore();
3376 // If the low part is just padding, it takes no register, leave ResType
3377 // null.
3378 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3379 "Unknown missing lo part");
3380 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003381
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003382 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3383 // on the stack.
3384 case Memory:
3385
3386 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3387 // COMPLEX_X87, it is passed in memory.
3388 case X87:
3389 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003390 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003391 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003392 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003393
3394 case SSEUp:
3395 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003396 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003397
3398 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3399 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3400 // and %r9 is used.
3401 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003402 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003403
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003404 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003405 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003406
3407 // If we have a sign or zero extended integer, make sure to return Extend
3408 // so that the parameter gets the right LLVM IR attributes.
3409 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3410 // Treat an enum type as its underlying type.
3411 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3412 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003413
Chris Lattner1f3a0632010-07-29 21:42:50 +00003414 if (Ty->isIntegralOrEnumerationType() &&
3415 Ty->isPromotableIntegerType())
3416 return ABIArgInfo::getExtend();
3417 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003418
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003419 break;
3420
3421 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3422 // available SSE register is used, the registers are taken in the
3423 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003424 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003425 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003426 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003427 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003428 break;
3429 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003430 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003431
Craig Topper8a13c412014-05-21 05:09:00 +00003432 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003433 switch (Hi) {
3434 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003435 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003436 // which is passed in memory.
3437 case Memory:
3438 case X87:
3439 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003440 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003441
3442 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003443
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003444 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003445 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003446 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003447 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003448
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003449 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3450 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003451 break;
3452
3453 // X87Up generally doesn't occur here (long double is passed in
3454 // memory), except in situations involving unions.
3455 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003456 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003457 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003458
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003459 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3460 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003461
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003462 ++neededSSE;
3463 break;
3464
3465 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3466 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003467 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003468 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003469 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003470 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003471 break;
3472 }
3473
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003474 // If a high part was specified, merge it together with the low part. It is
3475 // known to pass in the high eightbyte of the result. We do this by forming a
3476 // first class struct aggregate with the high and low part: {low, high}
3477 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003478 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003479
Chris Lattner1f3a0632010-07-29 21:42:50 +00003480 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003481}
3482
Erich Keane757d3172016-11-02 18:29:35 +00003483ABIArgInfo
3484X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3485 unsigned &NeededSSE) const {
3486 auto RT = Ty->getAs<RecordType>();
3487 assert(RT && "classifyRegCallStructType only valid with struct types");
3488
3489 if (RT->getDecl()->hasFlexibleArrayMember())
3490 return getIndirectReturnResult(Ty);
3491
3492 // Sum up bases
3493 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3494 if (CXXRD->isDynamicClass()) {
3495 NeededInt = NeededSSE = 0;
3496 return getIndirectReturnResult(Ty);
3497 }
3498
3499 for (const auto &I : CXXRD->bases())
3500 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3501 .isIndirect()) {
3502 NeededInt = NeededSSE = 0;
3503 return getIndirectReturnResult(Ty);
3504 }
3505 }
3506
3507 // Sum up members
3508 for (const auto *FD : RT->getDecl()->fields()) {
3509 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3510 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3511 .isIndirect()) {
3512 NeededInt = NeededSSE = 0;
3513 return getIndirectReturnResult(Ty);
3514 }
3515 } else {
3516 unsigned LocalNeededInt, LocalNeededSSE;
3517 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3518 LocalNeededSSE, true)
3519 .isIndirect()) {
3520 NeededInt = NeededSSE = 0;
3521 return getIndirectReturnResult(Ty);
3522 }
3523 NeededInt += LocalNeededInt;
3524 NeededSSE += LocalNeededSSE;
3525 }
3526 }
3527
3528 return ABIArgInfo::getDirect();
3529}
3530
3531ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3532 unsigned &NeededInt,
3533 unsigned &NeededSSE) const {
3534
3535 NeededInt = 0;
3536 NeededSSE = 0;
3537
3538 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3539}
3540
Chris Lattner22326a12010-07-29 02:31:05 +00003541void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003542
Erich Keane757d3172016-11-02 18:29:35 +00003543 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003544
3545 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003546 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3547 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3548 unsigned NeededInt, NeededSSE;
3549
Erich Keanede1b2a92017-07-21 18:50:36 +00003550 if (!getCXXABI().classifyReturnType(FI)) {
3551 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3552 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3553 FI.getReturnInfo() =
3554 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3555 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3556 FreeIntRegs -= NeededInt;
3557 FreeSSERegs -= NeededSSE;
3558 } else {
3559 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3560 }
3561 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3562 // Complex Long Double Type is passed in Memory when Regcall
3563 // calling convention is used.
3564 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3565 if (getContext().getCanonicalType(CT->getElementType()) ==
3566 getContext().LongDoubleTy)
3567 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3568 } else
3569 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3570 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003571
3572 // If the return value is indirect, then the hidden argument is consuming one
3573 // integer register.
3574 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003575 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003576
Peter Collingbournef7706832014-12-12 23:41:25 +00003577 // The chain argument effectively gives us another free register.
3578 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003579 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003580
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003581 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003582 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3583 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003584 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003585 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003586 it != ie; ++it, ++ArgNo) {
3587 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003588
Erich Keane757d3172016-11-02 18:29:35 +00003589 if (IsRegCall && it->type->isStructureOrClassType())
3590 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3591 else
3592 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3593 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003594
3595 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3596 // eightbyte of an argument, the whole argument is passed on the
3597 // stack. If registers have already been assigned for some
3598 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003599 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3600 FreeIntRegs -= NeededInt;
3601 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003602 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003603 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003604 }
3605 }
3606}
3607
John McCall7f416cc2015-09-08 08:05:57 +00003608static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3609 Address VAListAddr, QualType Ty) {
3610 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3611 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003612 llvm::Value *overflow_arg_area =
3613 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3614
3615 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3616 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003617 // It isn't stated explicitly in the standard, but in practice we use
3618 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003619 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3620 if (Align > CharUnits::fromQuantity(8)) {
3621 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3622 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003623 }
3624
3625 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003626 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003627 llvm::Value *Res =
3628 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003629 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003630
3631 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3632 // l->overflow_arg_area + sizeof(type).
3633 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3634 // an 8 byte boundary.
3635
3636 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003637 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003638 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003639 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3640 "overflow_arg_area.next");
3641 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3642
3643 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003644 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003645}
3646
John McCall7f416cc2015-09-08 08:05:57 +00003647Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3648 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003649 // Assume that va_list type is correct; should be pointer to LLVM type:
3650 // struct {
3651 // i32 gp_offset;
3652 // i32 fp_offset;
3653 // i8* overflow_arg_area;
3654 // i8* reg_save_area;
3655 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003656 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003657
John McCall7f416cc2015-09-08 08:05:57 +00003658 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003659 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003660 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003661
3662 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3663 // in the registers. If not go to step 7.
3664 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003665 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003666
3667 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3668 // general purpose registers needed to pass type and num_fp to hold
3669 // the number of floating point registers needed.
3670
3671 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3672 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3673 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3674 //
3675 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3676 // register save space).
3677
Craig Topper8a13c412014-05-21 05:09:00 +00003678 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003679 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3680 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003681 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003682 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003683 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3684 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003685 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003686 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3687 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003688 }
3689
3690 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003691 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003692 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3693 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003694 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3695 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003696 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3697 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003698 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3699 }
3700
3701 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3702 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3703 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3704 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3705
3706 // Emit code to load the value if it was passed in registers.
3707
3708 CGF.EmitBlock(InRegBlock);
3709
3710 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3711 // an offset of l->gp_offset and/or l->fp_offset. This may require
3712 // copying to a temporary location in case the parameter is passed
3713 // in different register classes or requires an alignment greater
3714 // than 8 for general purpose registers and 16 for XMM registers.
3715 //
3716 // FIXME: This really results in shameful code when we end up needing to
3717 // collect arguments from different places; often what should result in a
3718 // simple assembling of a structure from scattered addresses has many more
3719 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003720 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003721 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3722 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3723 "reg_save_area");
3724
3725 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003726 if (neededInt && neededSSE) {
3727 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003728 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003729 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003730 Address Tmp = CGF.CreateMemTemp(Ty);
3731 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003732 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003733 llvm::Type *TyLo = ST->getElementType(0);
3734 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003735 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003736 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003737 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3738 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003739 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3740 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003741 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3742 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003743
John McCall7f416cc2015-09-08 08:05:57 +00003744 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003745 // FIXME: Our choice of alignment here and below is probably pessimistic.
3746 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3747 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3748 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003749 CGF.Builder.CreateStore(V,
3750 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3751
3752 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003753 V = CGF.Builder.CreateAlignedLoad(
3754 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3755 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003756 CharUnits Offset = CharUnits::fromQuantity(
3757 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3758 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3759
3760 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003761 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003762 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3763 CharUnits::fromQuantity(8));
3764 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003765
3766 // Copy to a temporary if necessary to ensure the appropriate alignment.
3767 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003768 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003769 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003770 CharUnits TyAlign = SizeAlign.second;
3771
3772 // Copy into a temporary if the type is more aligned than the
3773 // register save area.
3774 if (TyAlign.getQuantity() > 8) {
3775 Address Tmp = CGF.CreateMemTemp(Ty);
3776 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003777 RegAddr = Tmp;
3778 }
John McCall7f416cc2015-09-08 08:05:57 +00003779
Chris Lattner0cf24192010-06-28 20:05:43 +00003780 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003781 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3782 CharUnits::fromQuantity(16));
3783 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003784 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003785 assert(neededSSE == 2 && "Invalid number of needed registers!");
3786 // SSE registers are spaced 16 bytes apart in the register save
3787 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003788 // The ABI isn't explicit about this, but it seems reasonable
3789 // to assume that the slots are 16-byte aligned, since the stack is
3790 // naturally 16-byte aligned and the prologue is expected to store
3791 // all the SSE registers to the RSA.
3792 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3793 CharUnits::fromQuantity(16));
3794 Address RegAddrHi =
3795 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3796 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003797 llvm::Type *DoubleTy = CGF.DoubleTy;
Serge Guelton1d993272017-05-09 19:31:30 +00003798 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003799 llvm::Value *V;
3800 Address Tmp = CGF.CreateMemTemp(Ty);
3801 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3802 V = CGF.Builder.CreateLoad(
3803 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3804 CGF.Builder.CreateStore(V,
3805 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3806 V = CGF.Builder.CreateLoad(
3807 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3808 CGF.Builder.CreateStore(V,
3809 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3810
3811 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003812 }
3813
3814 // AMD64-ABI 3.5.7p5: Step 5. Set:
3815 // l->gp_offset = l->gp_offset + num_gp * 8
3816 // l->fp_offset = l->fp_offset + num_fp * 16.
3817 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003818 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003819 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3820 gp_offset_p);
3821 }
3822 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003823 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003824 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3825 fp_offset_p);
3826 }
3827 CGF.EmitBranch(ContBlock);
3828
3829 // Emit code to load the value if it was passed in memory.
3830
3831 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003832 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003833
3834 // Return the appropriate result.
3835
3836 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003837 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3838 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003839 return ResAddr;
3840}
3841
Charles Davisc7d5c942015-09-17 20:55:33 +00003842Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3843 QualType Ty) const {
3844 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3845 CGF.getContext().getTypeInfoInChars(Ty),
3846 CharUnits::fromQuantity(8),
3847 /*allowHigherAlign*/ false);
3848}
3849
Erich Keane521ed962017-01-05 00:20:51 +00003850ABIArgInfo
3851WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3852 const ABIArgInfo &current) const {
3853 // Assumes vectorCall calling convention.
3854 const Type *Base = nullptr;
3855 uint64_t NumElts = 0;
3856
3857 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3858 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3859 FreeSSERegs -= NumElts;
3860 return getDirectX86Hva();
3861 }
3862 return current;
3863}
3864
Reid Kleckner80944df2014-10-31 22:00:51 +00003865ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003866 bool IsReturnType, bool IsVectorCall,
3867 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003868
3869 if (Ty->isVoidType())
3870 return ABIArgInfo::getIgnore();
3871
3872 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3873 Ty = EnumTy->getDecl()->getIntegerType();
3874
Reid Kleckner80944df2014-10-31 22:00:51 +00003875 TypeInfo Info = getContext().getTypeInfo(Ty);
3876 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003877 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003878
Reid Kleckner9005f412014-05-02 00:51:20 +00003879 const RecordType *RT = Ty->getAs<RecordType>();
3880 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003881 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003882 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003883 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003884 }
3885
3886 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003887 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003888
Reid Kleckner9005f412014-05-02 00:51:20 +00003889 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003890
Reid Kleckner80944df2014-10-31 22:00:51 +00003891 const Type *Base = nullptr;
3892 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003893 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3894 // other targets.
3895 if ((IsVectorCall || IsRegCall) &&
3896 isHomogeneousAggregate(Ty, Base, NumElts)) {
3897 if (IsRegCall) {
3898 if (FreeSSERegs >= NumElts) {
3899 FreeSSERegs -= NumElts;
3900 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3901 return ABIArgInfo::getDirect();
3902 return ABIArgInfo::getExpand();
3903 }
3904 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3905 } else if (IsVectorCall) {
3906 if (FreeSSERegs >= NumElts &&
3907 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3908 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003909 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003910 } else if (IsReturnType) {
3911 return ABIArgInfo::getExpand();
3912 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3913 // HVAs are delayed and reclassified in the 2nd step.
3914 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3915 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003916 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003917 }
3918
Reid Klecknerec87fec2014-05-02 01:17:12 +00003919 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003920 // If the member pointer is represented by an LLVM int or ptr, pass it
3921 // directly.
3922 llvm::Type *LLTy = CGT.ConvertType(Ty);
3923 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3924 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003925 }
3926
Michael Kuperstein4f818702015-02-24 09:35:58 +00003927 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003928 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3929 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003930 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003931 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003932
Reid Kleckner9005f412014-05-02 00:51:20 +00003933 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003934 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003935 }
3936
Julien Lerouge10dcff82014-08-27 00:36:55 +00003937 // Bool type is always extended to the ABI, other builtin types are not
3938 // extended.
3939 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3940 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003941 return ABIArgInfo::getExtend();
3942
Reid Kleckner11a17192015-10-28 22:29:52 +00003943 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3944 // passes them indirectly through memory.
3945 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3946 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003947 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003948 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3949 }
3950
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003951 return ABIArgInfo::getDirect();
3952}
3953
Erich Keane521ed962017-01-05 00:20:51 +00003954void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3955 unsigned FreeSSERegs,
3956 bool IsVectorCall,
3957 bool IsRegCall) const {
3958 unsigned Count = 0;
3959 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003960 // Vectorcall in x64 only permits the first 6 arguments to be passed
3961 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003962 if (Count < VectorcallMaxParamNumAsReg)
3963 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3964 else {
3965 // Since these cannot be passed in registers, pretend no registers
3966 // are left.
3967 unsigned ZeroSSERegsAvail = 0;
3968 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3969 IsVectorCall, IsRegCall);
3970 }
3971 ++Count;
3972 }
3973
Erich Keane521ed962017-01-05 00:20:51 +00003974 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003975 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00003976 }
3977}
3978
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003979void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003980 bool IsVectorCall =
3981 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003982 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003983
Erich Keane757d3172016-11-02 18:29:35 +00003984 unsigned FreeSSERegs = 0;
3985 if (IsVectorCall) {
3986 // We can use up to 4 SSE return registers with vectorcall.
3987 FreeSSERegs = 4;
3988 } else if (IsRegCall) {
3989 // RegCall gives us 16 SSE registers.
3990 FreeSSERegs = 16;
3991 }
3992
Reid Kleckner80944df2014-10-31 22:00:51 +00003993 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00003994 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3995 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00003996
Erich Keane757d3172016-11-02 18:29:35 +00003997 if (IsVectorCall) {
3998 // We can use up to 6 SSE register parameters with vectorcall.
3999 FreeSSERegs = 6;
4000 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004001 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004002 FreeSSERegs = 16;
4003 }
4004
Erich Keane521ed962017-01-05 00:20:51 +00004005 if (IsVectorCall) {
4006 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4007 } else {
4008 for (auto &I : FI.arguments())
4009 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4010 }
4011
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004012}
4013
John McCall7f416cc2015-09-08 08:05:57 +00004014Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4015 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004016
4017 bool IsIndirect = false;
4018
4019 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4020 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4021 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4022 uint64_t Width = getContext().getTypeSize(Ty);
4023 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4024 }
4025
4026 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004027 CGF.getContext().getTypeInfoInChars(Ty),
4028 CharUnits::fromQuantity(8),
4029 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004030}
Chris Lattner0cf24192010-06-28 20:05:43 +00004031
John McCallea8d8bb2010-03-11 00:10:12 +00004032// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004033namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004034/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4035class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004036 bool IsSoftFloatABI;
4037
4038 CharUnits getParamTypeAlignment(QualType Ty) const;
4039
John McCallea8d8bb2010-03-11 00:10:12 +00004040public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004041 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4042 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004043
John McCall7f416cc2015-09-08 08:05:57 +00004044 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4045 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004046};
4047
4048class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4049public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004050 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4051 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004052
Craig Topper4f12f102014-03-12 06:41:41 +00004053 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004054 // This is recovered from gcc output.
4055 return 1; // r1 is the dedicated stack pointer
4056 }
4057
4058 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004059 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004060};
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004061}
John McCallea8d8bb2010-03-11 00:10:12 +00004062
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004063CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4064 // Complex types are passed just like their elements
4065 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4066 Ty = CTy->getElementType();
4067
4068 if (Ty->isVectorType())
4069 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4070 : 4);
4071
4072 // For single-element float/vector structs, we consider the whole type
4073 // to have the same alignment requirements as its single element.
4074 const Type *AlignTy = nullptr;
4075 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4076 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4077 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4078 (BT && BT->isFloatingPoint()))
4079 AlignTy = EltType;
4080 }
4081
4082 if (AlignTy)
4083 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4084 return CharUnits::fromQuantity(4);
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004085}
John McCallea8d8bb2010-03-11 00:10:12 +00004086
James Y Knight29b5f082016-02-24 02:59:33 +00004087// TODO: this implementation is now likely redundant with
4088// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004089Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4090 QualType Ty) const {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004091 if (getTarget().getTriple().isOSDarwin()) {
4092 auto TI = getContext().getTypeInfoInChars(Ty);
4093 TI.second = getParamTypeAlignment(Ty);
4094
4095 CharUnits SlotSize = CharUnits::fromQuantity(4);
4096 return emitVoidPtrVAArg(CGF, VAList, Ty,
4097 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4098 /*AllowHigherAlign=*/true);
4099 }
4100
Roman Divacky039b9702016-02-20 08:31:24 +00004101 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004102 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4103 // TODO: Implement this. For now ignore.
4104 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004105 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004106 }
4107
John McCall7f416cc2015-09-08 08:05:57 +00004108 // struct __va_list_tag {
4109 // unsigned char gpr;
4110 // unsigned char fpr;
4111 // unsigned short reserved;
4112 // void *overflow_arg_area;
4113 // void *reg_save_area;
4114 // };
4115
Roman Divacky8a12d842014-11-03 18:32:54 +00004116 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004117 bool isInt =
4118 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004119 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004120
4121 // All aggregates are passed indirectly? That doesn't seem consistent
4122 // with the argument-lowering code.
4123 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004124
4125 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004126
4127 // The calling convention either uses 1-2 GPRs or 1 FPR.
4128 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004129 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004130 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4131 } else {
4132 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004133 }
John McCall7f416cc2015-09-08 08:05:57 +00004134
4135 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4136
4137 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004138 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004139 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4140 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4141 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004142
Eric Christopher7565e0d2015-05-29 23:09:49 +00004143 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004144 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004145
4146 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4147 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4148 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4149
4150 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4151
John McCall7f416cc2015-09-08 08:05:57 +00004152 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4153 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004154
John McCall7f416cc2015-09-08 08:05:57 +00004155 // Case 1: consume registers.
4156 Address RegAddr = Address::invalid();
4157 {
4158 CGF.EmitBlock(UsingRegs);
4159
4160 Address RegSaveAreaPtr =
4161 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4162 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4163 CharUnits::fromQuantity(8));
4164 assert(RegAddr.getElementType() == CGF.Int8Ty);
4165
4166 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004167 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004168 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4169 CharUnits::fromQuantity(32));
4170 }
4171
4172 // Get the address of the saved value by scaling the number of
4173 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004174 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004175 llvm::Value *RegOffset =
4176 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4177 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4178 RegAddr.getPointer(), RegOffset),
4179 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4180 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4181
4182 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004183 NumRegs =
4184 Builder.CreateAdd(NumRegs,
4185 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004186 Builder.CreateStore(NumRegs, NumRegsAddr);
4187
4188 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004189 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004190
John McCall7f416cc2015-09-08 08:05:57 +00004191 // Case 2: consume space in the overflow area.
4192 Address MemAddr = Address::invalid();
4193 {
4194 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004195
Roman Divacky039b9702016-02-20 08:31:24 +00004196 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4197
John McCall7f416cc2015-09-08 08:05:57 +00004198 // Everything in the overflow area is rounded up to a size of at least 4.
4199 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4200
4201 CharUnits Size;
4202 if (!isIndirect) {
4203 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004204 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004205 } else {
4206 Size = CGF.getPointerSize();
4207 }
4208
4209 Address OverflowAreaAddr =
4210 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004211 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004212 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004213 // Round up address of argument to alignment
4214 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4215 if (Align > OverflowAreaAlign) {
4216 llvm::Value *Ptr = OverflowArea.getPointer();
4217 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4218 Align);
4219 }
4220
John McCall7f416cc2015-09-08 08:05:57 +00004221 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4222
4223 // Increase the overflow area.
4224 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4225 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4226 CGF.EmitBranch(Cont);
4227 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004228
4229 CGF.EmitBlock(Cont);
4230
John McCall7f416cc2015-09-08 08:05:57 +00004231 // Merge the cases with a phi.
4232 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4233 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004234
John McCall7f416cc2015-09-08 08:05:57 +00004235 // Load the pointer if the argument was passed indirectly.
4236 if (isIndirect) {
4237 Result = Address(Builder.CreateLoad(Result, "aggr"),
4238 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004239 }
4240
4241 return Result;
4242}
4243
John McCallea8d8bb2010-03-11 00:10:12 +00004244bool
4245PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4246 llvm::Value *Address) const {
4247 // This is calculated from the LLVM and GCC tables and verified
4248 // against gcc output. AFAIK all ABIs use the same encoding.
4249
4250 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004251
Chris Lattnerece04092012-02-07 00:39:47 +00004252 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004253 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4254 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4255 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4256
4257 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004258 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004259
4260 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004261 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004262
4263 // 64-76 are various 4-byte special-purpose registers:
4264 // 64: mq
4265 // 65: lr
4266 // 66: ctr
4267 // 67: ap
4268 // 68-75 cr0-7
4269 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004270 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004271
4272 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004273 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004274
4275 // 109: vrsave
4276 // 110: vscr
4277 // 111: spe_acc
4278 // 112: spefscr
4279 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004280 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004281
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004282 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004283}
4284
Roman Divackyd966e722012-05-09 18:22:46 +00004285// PowerPC-64
4286
4287namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004288/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004289class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004290public:
4291 enum ABIKind {
4292 ELFv1 = 0,
4293 ELFv2
4294 };
4295
4296private:
4297 static const unsigned GPRBits = 64;
4298 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004299 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004300 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004301
4302 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4303 // will be passed in a QPX register.
4304 bool IsQPXVectorTy(const Type *Ty) const {
4305 if (!HasQPX)
4306 return false;
4307
4308 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4309 unsigned NumElements = VT->getNumElements();
4310 if (NumElements == 1)
4311 return false;
4312
4313 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4314 if (getContext().getTypeSize(Ty) <= 256)
4315 return true;
4316 } else if (VT->getElementType()->
4317 isSpecificBuiltinType(BuiltinType::Float)) {
4318 if (getContext().getTypeSize(Ty) <= 128)
4319 return true;
4320 }
4321 }
4322
4323 return false;
4324 }
4325
4326 bool IsQPXVectorTy(QualType Ty) const {
4327 return IsQPXVectorTy(Ty.getTypePtr());
4328 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004329
4330public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004331 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4332 bool SoftFloatABI)
4333 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4334 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004335
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004336 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004337 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004338
4339 ABIArgInfo classifyReturnType(QualType RetTy) const;
4340 ABIArgInfo classifyArgumentType(QualType Ty) const;
4341
Reid Klecknere9f6a712014-10-31 17:10:41 +00004342 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4343 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4344 uint64_t Members) const override;
4345
Bill Schmidt84d37792012-10-12 19:26:17 +00004346 // TODO: We can add more logic to computeInfo to improve performance.
4347 // Example: For aggregate arguments that fit in a register, we could
4348 // use getDirectInReg (as is done below for structs containing a single
4349 // floating-point value) to avoid pushing them to memory on function
4350 // entry. This would require changing the logic in PPCISelLowering
4351 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004352 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004353 if (!getCXXABI().classifyReturnType(FI))
4354 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004355 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004356 // We rely on the default argument classification for the most part.
4357 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004358 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004359 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004360 if (T) {
4361 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004362 if (IsQPXVectorTy(T) ||
4363 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004364 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004365 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004366 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004367 continue;
4368 }
4369 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004370 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004371 }
4372 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004373
John McCall7f416cc2015-09-08 08:05:57 +00004374 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4375 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004376};
4377
4378class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004379
Bill Schmidt25cb3492012-10-03 19:18:57 +00004380public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004381 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004382 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4383 bool SoftFloatABI)
4384 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4385 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004386
Craig Topper4f12f102014-03-12 06:41:41 +00004387 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004388 // This is recovered from gcc output.
4389 return 1; // r1 is the dedicated stack pointer
4390 }
4391
4392 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004393 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004394};
4395
Roman Divackyd966e722012-05-09 18:22:46 +00004396class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4397public:
4398 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4399
Craig Topper4f12f102014-03-12 06:41:41 +00004400 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004401 // This is recovered from gcc output.
4402 return 1; // r1 is the dedicated stack pointer
4403 }
4404
4405 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004406 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004407};
4408
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004409}
Roman Divackyd966e722012-05-09 18:22:46 +00004410
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004411// Return true if the ABI requires Ty to be passed sign- or zero-
4412// extended to 64 bits.
4413bool
4414PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4415 // Treat an enum type as its underlying type.
4416 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4417 Ty = EnumTy->getDecl()->getIntegerType();
4418
4419 // Promotable integer types are required to be promoted by the ABI.
4420 if (Ty->isPromotableIntegerType())
4421 return true;
4422
4423 // In addition to the usual promotable integer types, we also need to
4424 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4425 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4426 switch (BT->getKind()) {
4427 case BuiltinType::Int:
4428 case BuiltinType::UInt:
4429 return true;
4430 default:
4431 break;
4432 }
4433
4434 return false;
4435}
4436
John McCall7f416cc2015-09-08 08:05:57 +00004437/// isAlignedParamType - Determine whether a type requires 16-byte or
4438/// higher alignment in the parameter area. Always returns at least 8.
4439CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004440 // Complex types are passed just like their elements.
4441 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4442 Ty = CTy->getElementType();
4443
4444 // Only vector types of size 16 bytes need alignment (larger types are
4445 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004446 if (IsQPXVectorTy(Ty)) {
4447 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004448 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004449
John McCall7f416cc2015-09-08 08:05:57 +00004450 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004451 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004452 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004453 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004454
4455 // For single-element float/vector structs, we consider the whole type
4456 // to have the same alignment requirements as its single element.
4457 const Type *AlignAsType = nullptr;
4458 const Type *EltType = isSingleElementStruct(Ty, getContext());
4459 if (EltType) {
4460 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004461 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004462 getContext().getTypeSize(EltType) == 128) ||
4463 (BT && BT->isFloatingPoint()))
4464 AlignAsType = EltType;
4465 }
4466
Ulrich Weigandb7122372014-07-21 00:48:09 +00004467 // Likewise for ELFv2 homogeneous aggregates.
4468 const Type *Base = nullptr;
4469 uint64_t Members = 0;
4470 if (!AlignAsType && Kind == ELFv2 &&
4471 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4472 AlignAsType = Base;
4473
Ulrich Weigand581badc2014-07-10 17:20:07 +00004474 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004475 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4476 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004477 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004478
John McCall7f416cc2015-09-08 08:05:57 +00004479 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004480 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004481 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004482 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004483
4484 // Otherwise, we only need alignment for any aggregate type that
4485 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004486 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4487 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004488 return CharUnits::fromQuantity(32);
4489 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004490 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004491
John McCall7f416cc2015-09-08 08:05:57 +00004492 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004493}
4494
Ulrich Weigandb7122372014-07-21 00:48:09 +00004495/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4496/// aggregate. Base is set to the base element type, and Members is set
4497/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004498bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4499 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004500 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4501 uint64_t NElements = AT->getSize().getZExtValue();
4502 if (NElements == 0)
4503 return false;
4504 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4505 return false;
4506 Members *= NElements;
4507 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4508 const RecordDecl *RD = RT->getDecl();
4509 if (RD->hasFlexibleArrayMember())
4510 return false;
4511
4512 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004513
4514 // If this is a C++ record, check the bases first.
4515 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4516 for (const auto &I : CXXRD->bases()) {
4517 // Ignore empty records.
4518 if (isEmptyRecord(getContext(), I.getType(), true))
4519 continue;
4520
4521 uint64_t FldMembers;
4522 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4523 return false;
4524
4525 Members += FldMembers;
4526 }
4527 }
4528
Ulrich Weigandb7122372014-07-21 00:48:09 +00004529 for (const auto *FD : RD->fields()) {
4530 // Ignore (non-zero arrays of) empty records.
4531 QualType FT = FD->getType();
4532 while (const ConstantArrayType *AT =
4533 getContext().getAsConstantArrayType(FT)) {
4534 if (AT->getSize().getZExtValue() == 0)
4535 return false;
4536 FT = AT->getElementType();
4537 }
4538 if (isEmptyRecord(getContext(), FT, true))
4539 continue;
4540
4541 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4542 if (getContext().getLangOpts().CPlusPlus &&
4543 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4544 continue;
4545
4546 uint64_t FldMembers;
4547 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4548 return false;
4549
4550 Members = (RD->isUnion() ?
4551 std::max(Members, FldMembers) : Members + FldMembers);
4552 }
4553
4554 if (!Base)
4555 return false;
4556
4557 // Ensure there is no padding.
4558 if (getContext().getTypeSize(Base) * Members !=
4559 getContext().getTypeSize(Ty))
4560 return false;
4561 } else {
4562 Members = 1;
4563 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4564 Members = 2;
4565 Ty = CT->getElementType();
4566 }
4567
Reid Klecknere9f6a712014-10-31 17:10:41 +00004568 // Most ABIs only support float, double, and some vector type widths.
4569 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004570 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004571
4572 // The base type must be the same for all members. Types that
4573 // agree in both total size and mode (float vs. vector) are
4574 // treated as being equivalent here.
4575 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004576 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004577 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004578 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4579 // so make sure to widen it explicitly.
4580 if (const VectorType *VT = Base->getAs<VectorType>()) {
4581 QualType EltTy = VT->getElementType();
4582 unsigned NumElements =
4583 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4584 Base = getContext()
4585 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4586 .getTypePtr();
4587 }
4588 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004589
4590 if (Base->isVectorType() != TyPtr->isVectorType() ||
4591 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4592 return false;
4593 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004594 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4595}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004596
Reid Klecknere9f6a712014-10-31 17:10:41 +00004597bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4598 // Homogeneous aggregates for ELFv2 must have base types of float,
4599 // double, long double, or 128-bit vectors.
4600 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4601 if (BT->getKind() == BuiltinType::Float ||
4602 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004603 BT->getKind() == BuiltinType::LongDouble) {
4604 if (IsSoftFloatABI)
4605 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004606 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004607 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004608 }
4609 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004610 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004611 return true;
4612 }
4613 return false;
4614}
4615
4616bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4617 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004618 // Vector types require one register, floating point types require one
4619 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004620 uint32_t NumRegs =
4621 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004622
4623 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004624 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004625}
4626
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004627ABIArgInfo
4628PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004629 Ty = useFirstFieldIfTransparentUnion(Ty);
4630
Bill Schmidt90b22c92012-11-27 02:46:43 +00004631 if (Ty->isAnyComplexType())
4632 return ABIArgInfo::getDirect();
4633
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004634 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4635 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004636 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004637 uint64_t Size = getContext().getTypeSize(Ty);
4638 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004639 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004640 else if (Size < 128) {
4641 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4642 return ABIArgInfo::getDirect(CoerceTy);
4643 }
4644 }
4645
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004646 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004647 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004648 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004649
John McCall7f416cc2015-09-08 08:05:57 +00004650 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4651 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004652
4653 // ELFv2 homogeneous aggregates are passed as array types.
4654 const Type *Base = nullptr;
4655 uint64_t Members = 0;
4656 if (Kind == ELFv2 &&
4657 isHomogeneousAggregate(Ty, Base, Members)) {
4658 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4659 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4660 return ABIArgInfo::getDirect(CoerceTy);
4661 }
4662
Ulrich Weigand601957f2014-07-21 00:56:36 +00004663 // If an aggregate may end up fully in registers, we do not
4664 // use the ByVal method, but pass the aggregate as array.
4665 // This is usually beneficial since we avoid forcing the
4666 // back-end to store the argument to memory.
4667 uint64_t Bits = getContext().getTypeSize(Ty);
4668 if (Bits > 0 && Bits <= 8 * GPRBits) {
4669 llvm::Type *CoerceTy;
4670
4671 // Types up to 8 bytes are passed as integer type (which will be
4672 // properly aligned in the argument save area doubleword).
4673 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004674 CoerceTy =
4675 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004676 // Larger types are passed as arrays, with the base type selected
4677 // according to the required alignment in the save area.
4678 else {
4679 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004680 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004681 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4682 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4683 }
4684
4685 return ABIArgInfo::getDirect(CoerceTy);
4686 }
4687
Ulrich Weigandb7122372014-07-21 00:48:09 +00004688 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004689 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4690 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004691 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004692 }
4693
4694 return (isPromotableTypeForABI(Ty) ?
4695 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4696}
4697
4698ABIArgInfo
4699PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4700 if (RetTy->isVoidType())
4701 return ABIArgInfo::getIgnore();
4702
Bill Schmidta3d121c2012-12-17 04:20:17 +00004703 if (RetTy->isAnyComplexType())
4704 return ABIArgInfo::getDirect();
4705
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004706 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4707 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004708 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004709 uint64_t Size = getContext().getTypeSize(RetTy);
4710 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004711 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004712 else if (Size < 128) {
4713 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4714 return ABIArgInfo::getDirect(CoerceTy);
4715 }
4716 }
4717
Ulrich Weigandb7122372014-07-21 00:48:09 +00004718 if (isAggregateTypeForABI(RetTy)) {
4719 // ELFv2 homogeneous aggregates are returned as array types.
4720 const Type *Base = nullptr;
4721 uint64_t Members = 0;
4722 if (Kind == ELFv2 &&
4723 isHomogeneousAggregate(RetTy, Base, Members)) {
4724 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4725 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4726 return ABIArgInfo::getDirect(CoerceTy);
4727 }
4728
4729 // ELFv2 small aggregates are returned in up to two registers.
4730 uint64_t Bits = getContext().getTypeSize(RetTy);
4731 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4732 if (Bits == 0)
4733 return ABIArgInfo::getIgnore();
4734
4735 llvm::Type *CoerceTy;
4736 if (Bits > GPRBits) {
4737 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004738 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004739 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004740 CoerceTy =
4741 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004742 return ABIArgInfo::getDirect(CoerceTy);
4743 }
4744
4745 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004746 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004747 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004748
4749 return (isPromotableTypeForABI(RetTy) ?
4750 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4751}
4752
Bill Schmidt25cb3492012-10-03 19:18:57 +00004753// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004754Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4755 QualType Ty) const {
4756 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4757 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004758
John McCall7f416cc2015-09-08 08:05:57 +00004759 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004760
Bill Schmidt924c4782013-01-14 17:45:36 +00004761 // If we have a complex type and the base type is smaller than 8 bytes,
4762 // the ABI calls for the real and imaginary parts to be right-adjusted
4763 // in separate doublewords. However, Clang expects us to produce a
4764 // pointer to a structure with the two parts packed tightly. So generate
4765 // loads of the real and imaginary parts relative to the va_list pointer,
4766 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004767 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4768 CharUnits EltSize = TypeInfo.first / 2;
4769 if (EltSize < SlotSize) {
4770 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4771 SlotSize * 2, SlotSize,
4772 SlotSize, /*AllowHigher*/ true);
4773
4774 Address RealAddr = Addr;
4775 Address ImagAddr = RealAddr;
4776 if (CGF.CGM.getDataLayout().isBigEndian()) {
4777 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4778 SlotSize - EltSize);
4779 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4780 2 * SlotSize - EltSize);
4781 } else {
4782 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4783 }
4784
4785 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4786 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4787 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4788 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4789 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4790
4791 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4792 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4793 /*init*/ true);
4794 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004795 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004796 }
4797
John McCall7f416cc2015-09-08 08:05:57 +00004798 // Otherwise, just use the general rule.
4799 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4800 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004801}
4802
4803static bool
4804PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4805 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004806 // This is calculated from the LLVM and GCC tables and verified
4807 // against gcc output. AFAIK all ABIs use the same encoding.
4808
4809 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4810
4811 llvm::IntegerType *i8 = CGF.Int8Ty;
4812 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4813 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4814 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4815
4816 // 0-31: r0-31, the 8-byte general-purpose registers
4817 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4818
4819 // 32-63: fp0-31, the 8-byte floating-point registers
4820 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4821
Hal Finkel84832a72016-08-30 02:38:34 +00004822 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004823 // 64: mq
4824 // 65: lr
4825 // 66: ctr
4826 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004827 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4828
4829 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004830 // 68-75 cr0-7
4831 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004832 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004833
4834 // 77-108: v0-31, the 16-byte vector registers
4835 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4836
4837 // 109: vrsave
4838 // 110: vscr
4839 // 111: spe_acc
4840 // 112: spefscr
4841 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004842 // 114: tfhar
4843 // 115: tfiar
4844 // 116: texasr
4845 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004846
4847 return false;
4848}
John McCallea8d8bb2010-03-11 00:10:12 +00004849
Bill Schmidt25cb3492012-10-03 19:18:57 +00004850bool
4851PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4852 CodeGen::CodeGenFunction &CGF,
4853 llvm::Value *Address) const {
4854
4855 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4856}
4857
4858bool
4859PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4860 llvm::Value *Address) const {
4861
4862 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4863}
4864
Chris Lattner0cf24192010-06-28 20:05:43 +00004865//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004866// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004867//===----------------------------------------------------------------------===//
4868
4869namespace {
4870
John McCall12f23522016-04-04 18:33:08 +00004871class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004872public:
4873 enum ABIKind {
4874 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004875 DarwinPCS,
4876 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004877 };
4878
4879private:
4880 ABIKind Kind;
4881
4882public:
John McCall12f23522016-04-04 18:33:08 +00004883 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4884 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004885
4886private:
4887 ABIKind getABIKind() const { return Kind; }
4888 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4889
4890 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004891 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004892 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4893 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4894 uint64_t Members) const override;
4895
Tim Northovera2ee4332014-03-29 15:09:45 +00004896 bool isIllegalVectorType(QualType Ty) const;
4897
David Blaikie1cbb9712014-11-14 19:09:44 +00004898 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004899 if (!getCXXABI().classifyReturnType(FI))
4900 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004901
Tim Northoverb047bfa2014-11-27 21:02:49 +00004902 for (auto &it : FI.arguments())
4903 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004904 }
4905
John McCall7f416cc2015-09-08 08:05:57 +00004906 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4907 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004908
John McCall7f416cc2015-09-08 08:05:57 +00004909 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4910 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004911
John McCall7f416cc2015-09-08 08:05:57 +00004912 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4913 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004914 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4915 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4916 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004917 }
John McCall12f23522016-04-04 18:33:08 +00004918
Martin Storsjo502de222017-07-13 17:59:14 +00004919 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4920 QualType Ty) const override;
4921
John McCall56331e22018-01-07 06:28:49 +00004922 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00004923 bool asReturnValue) const override {
4924 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4925 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004926 bool isSwiftErrorInRegister() const override {
4927 return true;
4928 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004929
4930 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4931 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004932};
4933
Tim Northover573cbee2014-05-24 12:52:07 +00004934class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004935public:
Tim Northover573cbee2014-05-24 12:52:07 +00004936 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4937 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004938
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004939 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00004940 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004941 }
4942
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004943 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4944 return 31;
4945 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004946
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004947 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004948};
Martin Storsjo1c8af272017-07-20 05:47:06 +00004949
4950class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4951public:
4952 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4953 : AArch64TargetCodeGenInfo(CGT, K) {}
4954
4955 void getDependentLibraryOption(llvm::StringRef Lib,
4956 llvm::SmallString<24> &Opt) const override {
4957 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4958 }
4959
4960 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4961 llvm::SmallString<32> &Opt) const override {
4962 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4963 }
4964};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004965}
Tim Northovera2ee4332014-03-29 15:09:45 +00004966
Tim Northoverb047bfa2014-11-27 21:02:49 +00004967ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004968 Ty = useFirstFieldIfTransparentUnion(Ty);
4969
Tim Northovera2ee4332014-03-29 15:09:45 +00004970 // Handle illegal vector types here.
4971 if (isIllegalVectorType(Ty)) {
4972 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004973 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004974 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004975 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4976 return ABIArgInfo::getDirect(ResType);
4977 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004978 if (Size <= 32) {
4979 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004980 return ABIArgInfo::getDirect(ResType);
4981 }
4982 if (Size == 64) {
4983 llvm::Type *ResType =
4984 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004985 return ABIArgInfo::getDirect(ResType);
4986 }
4987 if (Size == 128) {
4988 llvm::Type *ResType =
4989 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004990 return ABIArgInfo::getDirect(ResType);
4991 }
John McCall7f416cc2015-09-08 08:05:57 +00004992 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004993 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004994
4995 if (!isAggregateTypeForABI(Ty)) {
4996 // Treat an enum type as its underlying type.
4997 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4998 Ty = EnumTy->getDecl()->getIntegerType();
4999
Tim Northovera2ee4332014-03-29 15:09:45 +00005000 return (Ty->isPromotableIntegerType() && isDarwinPCS()
5001 ? ABIArgInfo::getExtend()
5002 : ABIArgInfo::getDirect());
5003 }
5004
5005 // Structures with either a non-trivial destructor or a non-trivial
5006 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00005007 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005008 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5009 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00005010 }
5011
5012 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5013 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00005014 uint64_t Size = getContext().getTypeSize(Ty);
5015 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5016 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005017 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5018 return ABIArgInfo::getIgnore();
5019
Tim Northover23bcad22017-05-05 22:36:06 +00005020 // GNU C mode. The only argument that gets ignored is an empty one with size
5021 // 0.
5022 if (IsEmpty && Size == 0)
5023 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00005024 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5025 }
5026
5027 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005028 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005029 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005030 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005031 return ABIArgInfo::getDirect(
5032 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005033 }
5034
5035 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005036 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005037 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5038 // same size and alignment.
5039 if (getTarget().isRenderScriptTarget()) {
5040 return coerceToIntArray(Ty, getContext(), getVMContext());
5041 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00005042 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005043 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005044
Tim Northovera2ee4332014-03-29 15:09:45 +00005045 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5046 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005047 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005048 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5049 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5050 }
5051 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5052 }
5053
John McCall7f416cc2015-09-08 08:05:57 +00005054 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005055}
5056
Tim Northover573cbee2014-05-24 12:52:07 +00005057ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005058 if (RetTy->isVoidType())
5059 return ABIArgInfo::getIgnore();
5060
5061 // Large vector types should be returned via memory.
5062 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005063 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005064
5065 if (!isAggregateTypeForABI(RetTy)) {
5066 // Treat an enum type as its underlying type.
5067 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5068 RetTy = EnumTy->getDecl()->getIntegerType();
5069
Tim Northover4dab6982014-04-18 13:46:08 +00005070 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5071 ? ABIArgInfo::getExtend()
5072 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005073 }
5074
Tim Northover23bcad22017-05-05 22:36:06 +00005075 uint64_t Size = getContext().getTypeSize(RetTy);
5076 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005077 return ABIArgInfo::getIgnore();
5078
Craig Topper8a13c412014-05-21 05:09:00 +00005079 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005080 uint64_t Members = 0;
5081 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005082 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5083 return ABIArgInfo::getDirect();
5084
5085 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005086 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005087 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5088 // same size and alignment.
5089 if (getTarget().isRenderScriptTarget()) {
5090 return coerceToIntArray(RetTy, getContext(), getVMContext());
5091 }
Pete Cooper635b5092015-04-17 22:16:24 +00005092 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005093 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005094
5095 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5096 // For aggregates with 16-byte alignment, we use i128.
5097 if (Alignment < 128 && Size == 128) {
5098 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5099 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5100 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005101 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5102 }
5103
John McCall7f416cc2015-09-08 08:05:57 +00005104 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005105}
5106
Tim Northover573cbee2014-05-24 12:52:07 +00005107/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5108bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005109 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5110 // Check whether VT is legal.
5111 unsigned NumElements = VT->getNumElements();
5112 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005113 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005114 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005115 return true;
5116 return Size != 64 && (Size != 128 || NumElements == 1);
5117 }
5118 return false;
5119}
5120
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005121bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5122 llvm::Type *eltTy,
5123 unsigned elts) const {
5124 if (!llvm::isPowerOf2_32(elts))
5125 return false;
5126 if (totalSize.getQuantity() != 8 &&
5127 (totalSize.getQuantity() != 16 || elts == 1))
5128 return false;
5129 return true;
5130}
5131
Reid Klecknere9f6a712014-10-31 17:10:41 +00005132bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5133 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5134 // point type or a short-vector type. This is the same as the 32-bit ABI,
5135 // but with the difference that any floating-point type is allowed,
5136 // including __fp16.
5137 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5138 if (BT->isFloatingPoint())
5139 return true;
5140 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5141 unsigned VecSize = getContext().getTypeSize(VT);
5142 if (VecSize == 64 || VecSize == 128)
5143 return true;
5144 }
5145 return false;
5146}
5147
5148bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5149 uint64_t Members) const {
5150 return Members <= 4;
5151}
5152
John McCall7f416cc2015-09-08 08:05:57 +00005153Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005154 QualType Ty,
5155 CodeGenFunction &CGF) const {
5156 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005157 bool IsIndirect = AI.isIndirect();
5158
Tim Northoverb047bfa2014-11-27 21:02:49 +00005159 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5160 if (IsIndirect)
5161 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5162 else if (AI.getCoerceToType())
5163 BaseTy = AI.getCoerceToType();
5164
5165 unsigned NumRegs = 1;
5166 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5167 BaseTy = ArrTy->getElementType();
5168 NumRegs = ArrTy->getNumElements();
5169 }
5170 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5171
Tim Northovera2ee4332014-03-29 15:09:45 +00005172 // The AArch64 va_list type and handling is specified in the Procedure Call
5173 // Standard, section B.4:
5174 //
5175 // struct {
5176 // void *__stack;
5177 // void *__gr_top;
5178 // void *__vr_top;
5179 // int __gr_offs;
5180 // int __vr_offs;
5181 // };
5182
5183 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5184 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5185 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5186 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005187
John McCall7f416cc2015-09-08 08:05:57 +00005188 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5189 CharUnits TyAlign = TyInfo.second;
5190
5191 Address reg_offs_p = Address::invalid();
5192 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005193 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005194 CharUnits reg_top_offset;
5195 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005196 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005197 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005198 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005199 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5200 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005201 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5202 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005203 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005204 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005205 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005206 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005207 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005208 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5209 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005210 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5211 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005212 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005213 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005214 }
5215
5216 //=======================================
5217 // Find out where argument was passed
5218 //=======================================
5219
5220 // If reg_offs >= 0 we're already using the stack for this type of
5221 // argument. We don't want to keep updating reg_offs (in case it overflows,
5222 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5223 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005224 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005225 UsingStack = CGF.Builder.CreateICmpSGE(
5226 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5227
5228 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5229
5230 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005231 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005232 CGF.EmitBlock(MaybeRegBlock);
5233
5234 // Integer arguments may need to correct register alignment (for example a
5235 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5236 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005237 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5238 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005239
5240 reg_offs = CGF.Builder.CreateAdd(
5241 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5242 "align_regoffs");
5243 reg_offs = CGF.Builder.CreateAnd(
5244 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5245 "aligned_regoffs");
5246 }
5247
5248 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005249 // The fact that this is done unconditionally reflects the fact that
5250 // allocating an argument to the stack also uses up all the remaining
5251 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005252 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005253 NewOffset = CGF.Builder.CreateAdd(
5254 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5255 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5256
5257 // Now we're in a position to decide whether this argument really was in
5258 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005259 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005260 InRegs = CGF.Builder.CreateICmpSLE(
5261 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5262
5263 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5264
5265 //=======================================
5266 // Argument was in registers
5267 //=======================================
5268
5269 // Now we emit the code for if the argument was originally passed in
5270 // registers. First start the appropriate block:
5271 CGF.EmitBlock(InRegBlock);
5272
John McCall7f416cc2015-09-08 08:05:57 +00005273 llvm::Value *reg_top = nullptr;
5274 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5275 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005276 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005277 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5278 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5279 Address RegAddr = Address::invalid();
5280 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005281
5282 if (IsIndirect) {
5283 // If it's been passed indirectly (actually a struct), whatever we find from
5284 // stored registers or on the stack will actually be a struct **.
5285 MemTy = llvm::PointerType::getUnqual(MemTy);
5286 }
5287
Craig Topper8a13c412014-05-21 05:09:00 +00005288 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005289 uint64_t NumMembers = 0;
5290 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005291 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005292 // Homogeneous aggregates passed in registers will have their elements split
5293 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5294 // qN+1, ...). We reload and store into a temporary local variable
5295 // contiguously.
5296 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005297 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005298 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5299 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005300 Address Tmp = CGF.CreateTempAlloca(HFATy,
5301 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005302
John McCall7f416cc2015-09-08 08:05:57 +00005303 // On big-endian platforms, the value will be right-aligned in its slot.
5304 int Offset = 0;
5305 if (CGF.CGM.getDataLayout().isBigEndian() &&
5306 BaseTyInfo.first.getQuantity() < 16)
5307 Offset = 16 - BaseTyInfo.first.getQuantity();
5308
Tim Northovera2ee4332014-03-29 15:09:45 +00005309 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005310 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5311 Address LoadAddr =
5312 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5313 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5314
5315 Address StoreAddr =
5316 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005317
5318 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5319 CGF.Builder.CreateStore(Elem, StoreAddr);
5320 }
5321
John McCall7f416cc2015-09-08 08:05:57 +00005322 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005323 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005324 // Otherwise the object is contiguous in memory.
5325
5326 // It might be right-aligned in its slot.
5327 CharUnits SlotSize = BaseAddr.getAlignment();
5328 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005329 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005330 TyInfo.first < SlotSize) {
5331 CharUnits Offset = SlotSize - TyInfo.first;
5332 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005333 }
5334
John McCall7f416cc2015-09-08 08:05:57 +00005335 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005336 }
5337
5338 CGF.EmitBranch(ContBlock);
5339
5340 //=======================================
5341 // Argument was on the stack
5342 //=======================================
5343 CGF.EmitBlock(OnStackBlock);
5344
John McCall7f416cc2015-09-08 08:05:57 +00005345 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5346 CharUnits::Zero(), "stack_p");
5347 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005348
John McCall7f416cc2015-09-08 08:05:57 +00005349 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005350 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005351 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5352 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005353
John McCall7f416cc2015-09-08 08:05:57 +00005354 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005355
John McCall7f416cc2015-09-08 08:05:57 +00005356 OnStackPtr = CGF.Builder.CreateAdd(
5357 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005358 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005359 OnStackPtr = CGF.Builder.CreateAnd(
5360 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005361 "align_stack");
5362
John McCall7f416cc2015-09-08 08:05:57 +00005363 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005364 }
John McCall7f416cc2015-09-08 08:05:57 +00005365 Address OnStackAddr(OnStackPtr,
5366 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005367
John McCall7f416cc2015-09-08 08:05:57 +00005368 // All stack slots are multiples of 8 bytes.
5369 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5370 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005371 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005372 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005373 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005374 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005375
John McCall7f416cc2015-09-08 08:05:57 +00005376 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005377 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005378 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005379
5380 // Write the new value of __stack for the next call to va_arg
5381 CGF.Builder.CreateStore(NewStack, stack_p);
5382
5383 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005384 TyInfo.first < StackSlotSize) {
5385 CharUnits Offset = StackSlotSize - TyInfo.first;
5386 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005387 }
5388
John McCall7f416cc2015-09-08 08:05:57 +00005389 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005390
5391 CGF.EmitBranch(ContBlock);
5392
5393 //=======================================
5394 // Tidy up
5395 //=======================================
5396 CGF.EmitBlock(ContBlock);
5397
John McCall7f416cc2015-09-08 08:05:57 +00005398 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5399 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005400
5401 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005402 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5403 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005404
5405 return ResAddr;
5406}
5407
John McCall7f416cc2015-09-08 08:05:57 +00005408Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5409 CodeGenFunction &CGF) const {
5410 // The backend's lowering doesn't support va_arg for aggregates or
5411 // illegal vector types. Lower VAArg here for these cases and use
5412 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005413 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005414 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005415
John McCall7f416cc2015-09-08 08:05:57 +00005416 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005417
John McCall7f416cc2015-09-08 08:05:57 +00005418 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005419 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005420 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5421 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5422 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005423 }
5424
John McCall7f416cc2015-09-08 08:05:57 +00005425 // The size of the actual thing passed, which might end up just
5426 // being a pointer for indirect types.
5427 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5428
5429 // Arguments bigger than 16 bytes which aren't homogeneous
5430 // aggregates should be passed indirectly.
5431 bool IsIndirect = false;
5432 if (TyInfo.first.getQuantity() > 16) {
5433 const Type *Base = nullptr;
5434 uint64_t Members = 0;
5435 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005436 }
5437
John McCall7f416cc2015-09-08 08:05:57 +00005438 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5439 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005440}
5441
Martin Storsjo502de222017-07-13 17:59:14 +00005442Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5443 QualType Ty) const {
5444 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5445 CGF.getContext().getTypeInfoInChars(Ty),
5446 CharUnits::fromQuantity(8),
5447 /*allowHigherAlign*/ false);
5448}
5449
Tim Northovera2ee4332014-03-29 15:09:45 +00005450//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005451// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005452//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005453
5454namespace {
5455
John McCall12f23522016-04-04 18:33:08 +00005456class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005457public:
5458 enum ABIKind {
5459 APCS = 0,
5460 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005461 AAPCS_VFP = 2,
5462 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005463 };
5464
5465private:
5466 ABIKind Kind;
5467
5468public:
John McCall12f23522016-04-04 18:33:08 +00005469 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5470 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005471 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005472 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005473
John McCall3480ef22011-08-30 01:42:09 +00005474 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005475 switch (getTarget().getTriple().getEnvironment()) {
5476 case llvm::Triple::Android:
5477 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005478 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005479 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005480 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005481 case llvm::Triple::MuslEABI:
5482 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005483 return true;
5484 default:
5485 return false;
5486 }
John McCall3480ef22011-08-30 01:42:09 +00005487 }
5488
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005489 bool isEABIHF() const {
5490 switch (getTarget().getTriple().getEnvironment()) {
5491 case llvm::Triple::EABIHF:
5492 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005493 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005494 return true;
5495 default:
5496 return false;
5497 }
5498 }
5499
Daniel Dunbar020daa92009-09-12 01:00:39 +00005500 ABIKind getABIKind() const { return Kind; }
5501
Tim Northovera484bc02013-10-01 14:34:25 +00005502private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005503 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005504 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005505 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005506
Reid Klecknere9f6a712014-10-31 17:10:41 +00005507 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5508 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5509 uint64_t Members) const override;
5510
Craig Topper4f12f102014-03-12 06:41:41 +00005511 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005512
John McCall7f416cc2015-09-08 08:05:57 +00005513 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5514 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005515
5516 llvm::CallingConv::ID getLLVMDefaultCC() const;
5517 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005518 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005519
John McCall56331e22018-01-07 06:28:49 +00005520 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005521 bool asReturnValue) const override {
5522 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5523 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005524 bool isSwiftErrorInRegister() const override {
5525 return true;
5526 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005527 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5528 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005529};
5530
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005531class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5532public:
Chris Lattner2b037972010-07-29 02:01:43 +00005533 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5534 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005535
John McCall3480ef22011-08-30 01:42:09 +00005536 const ARMABIInfo &getABIInfo() const {
5537 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5538 }
5539
Craig Topper4f12f102014-03-12 06:41:41 +00005540 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005541 return 13;
5542 }
Roman Divackyc1617352011-05-18 19:36:54 +00005543
Craig Topper4f12f102014-03-12 06:41:41 +00005544 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005545 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005546 }
5547
Roman Divackyc1617352011-05-18 19:36:54 +00005548 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005549 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005550 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005551
5552 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005553 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005554 return false;
5555 }
John McCall3480ef22011-08-30 01:42:09 +00005556
Craig Topper4f12f102014-03-12 06:41:41 +00005557 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005558 if (getABIInfo().isEABI()) return 88;
5559 return TargetCodeGenInfo::getSizeOfUnwindException();
5560 }
Tim Northovera484bc02013-10-01 14:34:25 +00005561
Eric Christopher162c91c2015-06-05 22:03:00 +00005562 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005563 CodeGen::CodeGenModule &CGM,
5564 ForDefinition_t IsForDefinition) const override {
5565 if (!IsForDefinition)
5566 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005567 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005568 if (!FD)
5569 return;
5570
5571 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5572 if (!Attr)
5573 return;
5574
5575 const char *Kind;
5576 switch (Attr->getInterrupt()) {
5577 case ARMInterruptAttr::Generic: Kind = ""; break;
5578 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5579 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5580 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5581 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5582 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5583 }
5584
5585 llvm::Function *Fn = cast<llvm::Function>(GV);
5586
5587 Fn->addFnAttr("interrupt", Kind);
5588
Tim Northover5627d392015-10-30 16:30:45 +00005589 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5590 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005591 return;
5592
5593 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5594 // however this is not necessarily true on taking any interrupt. Instruct
5595 // the backend to perform a realignment as part of the function prologue.
5596 llvm::AttrBuilder B;
5597 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005598 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005599 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005600};
5601
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005602class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005603public:
5604 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5605 : ARMTargetCodeGenInfo(CGT, K) {}
5606
Eric Christopher162c91c2015-06-05 22:03:00 +00005607 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005608 CodeGen::CodeGenModule &CGM,
5609 ForDefinition_t IsForDefinition) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005610
5611 void getDependentLibraryOption(llvm::StringRef Lib,
5612 llvm::SmallString<24> &Opt) const override {
5613 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5614 }
5615
5616 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5617 llvm::SmallString<32> &Opt) const override {
5618 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5619 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005620};
5621
Eric Christopher162c91c2015-06-05 22:03:00 +00005622void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005623 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
5624 ForDefinition_t IsForDefinition) const {
5625 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
5626 if (!IsForDefinition)
5627 return;
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005628 addStackProbeSizeTargetAttribute(D, GV, CGM);
5629}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005630}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005631
Chris Lattner22326a12010-07-29 02:31:05 +00005632void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005633 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005634 FI.getReturnInfo() =
5635 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005636
Tim Northoverbc784d12015-02-24 17:22:40 +00005637 for (auto &I : FI.arguments())
5638 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005639
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005640 // Always honor user-specified calling convention.
5641 if (FI.getCallingConvention() != llvm::CallingConv::C)
5642 return;
5643
John McCall882987f2013-02-28 19:01:20 +00005644 llvm::CallingConv::ID cc = getRuntimeCC();
5645 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005646 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005647}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005648
John McCall882987f2013-02-28 19:01:20 +00005649/// Return the default calling convention that LLVM will use.
5650llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5651 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005652 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005653 return llvm::CallingConv::ARM_AAPCS_VFP;
5654 else if (isEABI())
5655 return llvm::CallingConv::ARM_AAPCS;
5656 else
5657 return llvm::CallingConv::ARM_APCS;
5658}
5659
5660/// Return the calling convention that our ABI would like us to use
5661/// as the C calling convention.
5662llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005663 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005664 case APCS: return llvm::CallingConv::ARM_APCS;
5665 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5666 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005667 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005668 }
John McCall882987f2013-02-28 19:01:20 +00005669 llvm_unreachable("bad ABI kind");
5670}
5671
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005672void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005673 assert(getRuntimeCC() == llvm::CallingConv::C);
5674
5675 // Don't muddy up the IR with a ton of explicit annotations if
5676 // they'd just match what LLVM will infer from the triple.
5677 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5678 if (abiCC != getLLVMDefaultCC())
5679 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005680
Tim Northover5627d392015-10-30 16:30:45 +00005681 // AAPCS apparently requires runtime support functions to be soft-float, but
5682 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5683 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
Peter Smith32e26752017-07-27 10:43:53 +00005684
5685 // The Run-time ABI for the ARM Architecture section 4.1.2 requires
5686 // AEABI-complying FP helper functions to use the base AAPCS.
5687 // These AEABI functions are expanded in the ARM llvm backend, all the builtin
5688 // support functions emitted by clang such as the _Complex helpers follow the
5689 // abiCC.
5690 if (abiCC != getLLVMDefaultCC())
Tim Northover5627d392015-10-30 16:30:45 +00005691 BuiltinCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005692}
5693
Tim Northoverbc784d12015-02-24 17:22:40 +00005694ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5695 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005696 // 6.1.2.1 The following argument types are VFP CPRCs:
5697 // A single-precision floating-point type (including promoted
5698 // half-precision types); A double-precision floating-point type;
5699 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5700 // with a Base Type of a single- or double-precision floating-point type,
5701 // 64-bit containerized vectors or 128-bit containerized vectors with one
5702 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005703 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005704
Reid Klecknerb1be6832014-11-15 01:41:41 +00005705 Ty = useFirstFieldIfTransparentUnion(Ty);
5706
Manman Renfef9e312012-10-16 19:18:39 +00005707 // Handle illegal vector types here.
5708 if (isIllegalVectorType(Ty)) {
5709 uint64_t Size = getContext().getTypeSize(Ty);
5710 if (Size <= 32) {
5711 llvm::Type *ResType =
5712 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005713 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005714 }
5715 if (Size == 64) {
5716 llvm::Type *ResType = llvm::VectorType::get(
5717 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005718 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005719 }
5720 if (Size == 128) {
5721 llvm::Type *ResType = llvm::VectorType::get(
5722 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005723 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005724 }
John McCall7f416cc2015-09-08 08:05:57 +00005725 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005726 }
5727
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005728 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5729 // unspecified. This is not done for OpenCL as it handles the half type
5730 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005731 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005732 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5733 llvm::Type::getFloatTy(getVMContext()) :
5734 llvm::Type::getInt32Ty(getVMContext());
5735 return ABIArgInfo::getDirect(ResType);
5736 }
5737
John McCalla1dee5302010-08-22 10:59:02 +00005738 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005739 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005740 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005741 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005742 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005743
Tim Northover5a1558e2014-11-07 22:30:50 +00005744 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5745 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005746 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005747
Oliver Stannard405bded2014-02-11 09:25:50 +00005748 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005749 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005750 }
Tim Northover1060eae2013-06-21 22:49:34 +00005751
Daniel Dunbar09d33622009-09-14 21:54:03 +00005752 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005753 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005754 return ABIArgInfo::getIgnore();
5755
Tim Northover5a1558e2014-11-07 22:30:50 +00005756 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005757 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5758 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005759 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005760 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005761 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005762 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005763 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005764 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005765 }
Tim Northover5627d392015-10-30 16:30:45 +00005766 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5767 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5768 // this convention even for a variadic function: the backend will use GPRs
5769 // if needed.
5770 const Type *Base = nullptr;
5771 uint64_t Members = 0;
5772 if (isHomogeneousAggregate(Ty, Base, Members)) {
5773 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5774 llvm::Type *Ty =
5775 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5776 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5777 }
5778 }
5779
5780 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5781 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5782 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5783 // bigger than 128-bits, they get placed in space allocated by the caller,
5784 // and a pointer is passed.
5785 return ABIArgInfo::getIndirect(
5786 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005787 }
5788
Manman Ren6c30e132012-08-13 21:23:55 +00005789 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005790 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5791 // most 8-byte. We realign the indirect argument if type alignment is bigger
5792 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005793 uint64_t ABIAlign = 4;
5794 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5795 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005796 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005797 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005798
Manman Ren8cd99812012-11-06 04:58:01 +00005799 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005800 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005801 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5802 /*ByVal=*/true,
5803 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005804 }
5805
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005806 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5807 // same size and alignment.
5808 if (getTarget().isRenderScriptTarget()) {
5809 return coerceToIntArray(Ty, getContext(), getVMContext());
5810 }
5811
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005812 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005813 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005814 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005815 // FIXME: Try to match the types of the arguments more accurately where
5816 // we can.
5817 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005818 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5819 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005820 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005821 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5822 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005823 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005824
Tim Northover5a1558e2014-11-07 22:30:50 +00005825 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005826}
5827
Chris Lattner458b2aa2010-07-29 02:16:43 +00005828static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005829 llvm::LLVMContext &VMContext) {
5830 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5831 // is called integer-like if its size is less than or equal to one word, and
5832 // the offset of each of its addressable sub-fields is zero.
5833
5834 uint64_t Size = Context.getTypeSize(Ty);
5835
5836 // Check that the type fits in a word.
5837 if (Size > 32)
5838 return false;
5839
5840 // FIXME: Handle vector types!
5841 if (Ty->isVectorType())
5842 return false;
5843
Daniel Dunbard53bac72009-09-14 02:20:34 +00005844 // Float types are never treated as "integer like".
5845 if (Ty->isRealFloatingType())
5846 return false;
5847
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005848 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005849 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005850 return true;
5851
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005852 // Small complex integer types are "integer like".
5853 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5854 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005855
5856 // Single element and zero sized arrays should be allowed, by the definition
5857 // above, but they are not.
5858
5859 // Otherwise, it must be a record type.
5860 const RecordType *RT = Ty->getAs<RecordType>();
5861 if (!RT) return false;
5862
5863 // Ignore records with flexible arrays.
5864 const RecordDecl *RD = RT->getDecl();
5865 if (RD->hasFlexibleArrayMember())
5866 return false;
5867
5868 // Check that all sub-fields are at offset 0, and are themselves "integer
5869 // like".
5870 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5871
5872 bool HadField = false;
5873 unsigned idx = 0;
5874 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5875 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005876 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005877
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005878 // Bit-fields are not addressable, we only need to verify they are "integer
5879 // like". We still have to disallow a subsequent non-bitfield, for example:
5880 // struct { int : 0; int x }
5881 // is non-integer like according to gcc.
5882 if (FD->isBitField()) {
5883 if (!RD->isUnion())
5884 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005885
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005886 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5887 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005888
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005889 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005890 }
5891
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005892 // Check if this field is at offset 0.
5893 if (Layout.getFieldOffset(idx) != 0)
5894 return false;
5895
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005896 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5897 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005898
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005899 // Only allow at most one field in a structure. This doesn't match the
5900 // wording above, but follows gcc in situations with a field following an
5901 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005902 if (!RD->isUnion()) {
5903 if (HadField)
5904 return false;
5905
5906 HadField = true;
5907 }
5908 }
5909
5910 return true;
5911}
5912
Oliver Stannard405bded2014-02-11 09:25:50 +00005913ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5914 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005915 bool IsEffectivelyAAPCS_VFP =
5916 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005917
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005918 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005919 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005920
Daniel Dunbar19964db2010-09-23 01:54:32 +00005921 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005922 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005923 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005924 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005925
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005926 // __fp16 gets returned as if it were an int or float, but with the top 16
5927 // bits unspecified. This is not done for OpenCL as it handles the half type
5928 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005929 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005930 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5931 llvm::Type::getFloatTy(getVMContext()) :
5932 llvm::Type::getInt32Ty(getVMContext());
5933 return ABIArgInfo::getDirect(ResType);
5934 }
5935
John McCalla1dee5302010-08-22 10:59:02 +00005936 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005937 // Treat an enum type as its underlying type.
5938 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5939 RetTy = EnumTy->getDecl()->getIntegerType();
5940
Tim Northover5a1558e2014-11-07 22:30:50 +00005941 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5942 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005943 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005944
5945 // Are we following APCS?
5946 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005947 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005948 return ABIArgInfo::getIgnore();
5949
Daniel Dunbareedf1512010-02-01 23:31:19 +00005950 // Complex types are all returned as packed integers.
5951 //
5952 // FIXME: Consider using 2 x vector types if the back end handles them
5953 // correctly.
5954 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005955 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5956 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005957
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005958 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005959 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005960 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005961 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005962 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005963 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005964 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005965 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5966 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005967 }
5968
5969 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005970 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005971 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005972
5973 // Otherwise this is an AAPCS variant.
5974
Chris Lattner458b2aa2010-07-29 02:16:43 +00005975 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005976 return ABIArgInfo::getIgnore();
5977
Bob Wilson1d9269a2011-11-02 04:51:36 +00005978 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005979 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005980 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005981 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005982 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005983 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005984 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005985 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005986 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005987 }
5988
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005989 // Aggregates <= 4 bytes are returned in r0; other aggregates
5990 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005991 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005992 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005993 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5994 // same size and alignment.
5995 if (getTarget().isRenderScriptTarget()) {
5996 return coerceToIntArray(RetTy, getContext(), getVMContext());
5997 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005998 if (getDataLayout().isBigEndian())
5999 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00006000 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00006001
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006002 // Return in the smallest viable integer type.
6003 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00006004 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006005 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00006006 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6007 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00006008 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6009 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6010 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00006011 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00006012 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006013 }
6014
John McCall7f416cc2015-09-08 08:05:57 +00006015 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006016}
6017
Manman Renfef9e312012-10-16 19:18:39 +00006018/// isIllegalVector - check whether Ty is an illegal vector type.
6019bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00006020 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6021 if (isAndroid()) {
6022 // Android shipped using Clang 3.1, which supported a slightly different
6023 // vector ABI. The primary differences were that 3-element vector types
6024 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6025 // accepts that legacy behavior for Android only.
6026 // Check whether VT is legal.
6027 unsigned NumElements = VT->getNumElements();
6028 // NumElements should be power of 2 or equal to 3.
6029 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6030 return true;
6031 } else {
6032 // Check whether VT is legal.
6033 unsigned NumElements = VT->getNumElements();
6034 uint64_t Size = getContext().getTypeSize(VT);
6035 // NumElements should be power of 2.
6036 if (!llvm::isPowerOf2_32(NumElements))
6037 return true;
6038 // Size should be greater than 32 bits.
6039 return Size <= 32;
6040 }
Manman Renfef9e312012-10-16 19:18:39 +00006041 }
6042 return false;
6043}
6044
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006045bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6046 llvm::Type *eltTy,
6047 unsigned numElts) const {
6048 if (!llvm::isPowerOf2_32(numElts))
6049 return false;
6050 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6051 if (size > 64)
6052 return false;
6053 if (vectorSize.getQuantity() != 8 &&
6054 (vectorSize.getQuantity() != 16 || numElts == 1))
6055 return false;
6056 return true;
6057}
6058
Reid Klecknere9f6a712014-10-31 17:10:41 +00006059bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6060 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6061 // double, or 64-bit or 128-bit vectors.
6062 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6063 if (BT->getKind() == BuiltinType::Float ||
6064 BT->getKind() == BuiltinType::Double ||
6065 BT->getKind() == BuiltinType::LongDouble)
6066 return true;
6067 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6068 unsigned VecSize = getContext().getTypeSize(VT);
6069 if (VecSize == 64 || VecSize == 128)
6070 return true;
6071 }
6072 return false;
6073}
6074
6075bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6076 uint64_t Members) const {
6077 return Members <= 4;
6078}
6079
John McCall7f416cc2015-09-08 08:05:57 +00006080Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6081 QualType Ty) const {
6082 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006083
John McCall7f416cc2015-09-08 08:05:57 +00006084 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006085 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006086 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6087 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6088 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006089 }
6090
John McCall7f416cc2015-09-08 08:05:57 +00006091 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6092 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006093
John McCall7f416cc2015-09-08 08:05:57 +00006094 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6095 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006096 const Type *Base = nullptr;
6097 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006098 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6099 IsIndirect = true;
6100
Tim Northover5627d392015-10-30 16:30:45 +00006101 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6102 // allocated by the caller.
6103 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6104 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6105 !isHomogeneousAggregate(Ty, Base, Members)) {
6106 IsIndirect = true;
6107
John McCall7f416cc2015-09-08 08:05:57 +00006108 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006109 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6110 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006111 // Our callers should be prepared to handle an under-aligned address.
6112 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6113 getABIKind() == ARMABIInfo::AAPCS) {
6114 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6115 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006116 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6117 // ARMv7k allows type alignment up to 16 bytes.
6118 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6119 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006120 } else {
6121 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006122 }
John McCall7f416cc2015-09-08 08:05:57 +00006123 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006124
John McCall7f416cc2015-09-08 08:05:57 +00006125 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6126 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006127}
6128
Chris Lattner0cf24192010-06-28 20:05:43 +00006129//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006130// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006131//===----------------------------------------------------------------------===//
6132
6133namespace {
6134
Justin Holewinski83e96682012-05-24 17:43:12 +00006135class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006136public:
Justin Holewinski36837432013-03-30 14:38:24 +00006137 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006138
6139 ABIArgInfo classifyReturnType(QualType RetTy) const;
6140 ABIArgInfo classifyArgumentType(QualType Ty) const;
6141
Craig Topper4f12f102014-03-12 06:41:41 +00006142 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006143 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6144 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006145};
6146
Justin Holewinski83e96682012-05-24 17:43:12 +00006147class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006148public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006149 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6150 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006151
Eric Christopher162c91c2015-06-05 22:03:00 +00006152 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006153 CodeGen::CodeGenModule &M,
6154 ForDefinition_t IsForDefinition) const override;
6155
Justin Holewinski36837432013-03-30 14:38:24 +00006156private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006157 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6158 // resulting MDNode to the nvvm.annotations MDNode.
6159 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006160};
6161
Justin Holewinski83e96682012-05-24 17:43:12 +00006162ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006163 if (RetTy->isVoidType())
6164 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006165
6166 // note: this is different from default ABI
6167 if (!RetTy->isScalarType())
6168 return ABIArgInfo::getDirect();
6169
6170 // Treat an enum type as its underlying type.
6171 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6172 RetTy = EnumTy->getDecl()->getIntegerType();
6173
6174 return (RetTy->isPromotableIntegerType() ?
6175 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006176}
6177
Justin Holewinski83e96682012-05-24 17:43:12 +00006178ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006179 // Treat an enum type as its underlying type.
6180 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6181 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006182
Eli Bendersky95338a02014-10-29 13:43:21 +00006183 // Return aggregates type as indirect by value
6184 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006185 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006186
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006187 return (Ty->isPromotableIntegerType() ?
6188 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006189}
6190
Justin Holewinski83e96682012-05-24 17:43:12 +00006191void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006192 if (!getCXXABI().classifyReturnType(FI))
6193 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006194 for (auto &I : FI.arguments())
6195 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006196
6197 // Always honor user-specified calling convention.
6198 if (FI.getCallingConvention() != llvm::CallingConv::C)
6199 return;
6200
John McCall882987f2013-02-28 19:01:20 +00006201 FI.setEffectiveCallingConvention(getRuntimeCC());
6202}
6203
John McCall7f416cc2015-09-08 08:05:57 +00006204Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6205 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006206 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006207}
6208
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006209void NVPTXTargetCodeGenInfo::setTargetAttributes(
6210 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6211 ForDefinition_t IsForDefinition) const {
6212 if (!IsForDefinition)
6213 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006214 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006215 if (!FD) return;
6216
6217 llvm::Function *F = cast<llvm::Function>(GV);
6218
6219 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006220 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006221 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006222 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006223 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006224 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006225 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6226 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006227 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006228 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006229 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006230 }
Justin Holewinski38031972011-10-05 17:58:44 +00006231
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006232 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006233 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006234 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006235 // __global__ functions cannot be called from the device, we do not
6236 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006237 if (FD->hasAttr<CUDAGlobalAttr>()) {
6238 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6239 addNVVMMetadata(F, "kernel", 1);
6240 }
Artem Belevich7093e402015-04-21 22:55:54 +00006241 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006242 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006243 llvm::APSInt MaxThreads(32);
6244 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6245 if (MaxThreads > 0)
6246 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6247
6248 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6249 // not specified in __launch_bounds__ or if the user specified a 0 value,
6250 // we don't have to add a PTX directive.
6251 if (Attr->getMinBlocks()) {
6252 llvm::APSInt MinBlocks(32);
6253 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6254 if (MinBlocks > 0)
6255 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6256 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006257 }
6258 }
Justin Holewinski38031972011-10-05 17:58:44 +00006259 }
6260}
6261
Eli Benderskye06a2c42014-04-15 16:57:05 +00006262void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6263 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006264 llvm::Module *M = F->getParent();
6265 llvm::LLVMContext &Ctx = M->getContext();
6266
6267 // Get "nvvm.annotations" metadata node
6268 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6269
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006270 llvm::Metadata *MDVals[] = {
6271 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6272 llvm::ConstantAsMetadata::get(
6273 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006274 // Append metadata to nvvm.annotations
6275 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6276}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006277}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006278
6279//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006280// SystemZ ABI Implementation
6281//===----------------------------------------------------------------------===//
6282
6283namespace {
6284
Bryan Chane3f1ed52016-04-28 13:56:43 +00006285class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006286 bool HasVector;
6287
Ulrich Weigand47445072013-05-06 16:26:41 +00006288public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006289 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006290 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006291
6292 bool isPromotableIntegerType(QualType Ty) const;
6293 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006294 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006295 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006296 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006297
6298 ABIArgInfo classifyReturnType(QualType RetTy) const;
6299 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6300
Craig Topper4f12f102014-03-12 06:41:41 +00006301 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006302 if (!getCXXABI().classifyReturnType(FI))
6303 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006304 for (auto &I : FI.arguments())
6305 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006306 }
6307
John McCall7f416cc2015-09-08 08:05:57 +00006308 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6309 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006310
John McCall56331e22018-01-07 06:28:49 +00006311 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
Bryan Chane3f1ed52016-04-28 13:56:43 +00006312 bool asReturnValue) const override {
6313 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6314 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006315 bool isSwiftErrorInRegister() const override {
Arnold Schwaighofer612d6932017-11-07 16:40:51 +00006316 return false;
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006317 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006318};
6319
6320class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6321public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006322 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6323 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006324};
6325
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006326}
Ulrich Weigand47445072013-05-06 16:26:41 +00006327
6328bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6329 // Treat an enum type as its underlying type.
6330 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6331 Ty = EnumTy->getDecl()->getIntegerType();
6332
6333 // Promotable integer types are required to be promoted by the ABI.
6334 if (Ty->isPromotableIntegerType())
6335 return true;
6336
6337 // 32-bit values must also be promoted.
6338 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6339 switch (BT->getKind()) {
6340 case BuiltinType::Int:
6341 case BuiltinType::UInt:
6342 return true;
6343 default:
6344 return false;
6345 }
6346 return false;
6347}
6348
6349bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006350 return (Ty->isAnyComplexType() ||
6351 Ty->isVectorType() ||
6352 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006353}
6354
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006355bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6356 return (HasVector &&
6357 Ty->isVectorType() &&
6358 getContext().getTypeSize(Ty) <= 128);
6359}
6360
Ulrich Weigand47445072013-05-06 16:26:41 +00006361bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6362 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6363 switch (BT->getKind()) {
6364 case BuiltinType::Float:
6365 case BuiltinType::Double:
6366 return true;
6367 default:
6368 return false;
6369 }
6370
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006371 return false;
6372}
6373
6374QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006375 if (const RecordType *RT = Ty->getAsStructureType()) {
6376 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006377 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006378
6379 // If this is a C++ record, check the bases first.
6380 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006381 for (const auto &I : CXXRD->bases()) {
6382 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006383
6384 // Empty bases don't affect things either way.
6385 if (isEmptyRecord(getContext(), Base, true))
6386 continue;
6387
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006388 if (!Found.isNull())
6389 return Ty;
6390 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006391 }
6392
6393 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006394 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006395 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006396 // Unlike isSingleElementStruct(), empty structure and array fields
6397 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006398 if (getContext().getLangOpts().CPlusPlus &&
6399 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6400 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006401
6402 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006403 // Nested structures still do though.
6404 if (!Found.isNull())
6405 return Ty;
6406 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006407 }
6408
6409 // Unlike isSingleElementStruct(), trailing padding is allowed.
6410 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006411 if (!Found.isNull())
6412 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006413 }
6414
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006415 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006416}
6417
John McCall7f416cc2015-09-08 08:05:57 +00006418Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6419 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006420 // Assume that va_list type is correct; should be pointer to LLVM type:
6421 // struct {
6422 // i64 __gpr;
6423 // i64 __fpr;
6424 // i8 *__overflow_arg_area;
6425 // i8 *__reg_save_area;
6426 // };
6427
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006428 // Every non-vector argument occupies 8 bytes and is passed by preference
6429 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6430 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006431 Ty = getContext().getCanonicalType(Ty);
6432 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006433 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006434 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006435 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006436 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006437 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006438 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006439 CharUnits UnpaddedSize;
6440 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006441 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006442 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6443 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006444 } else {
6445 if (AI.getCoerceToType())
6446 ArgTy = AI.getCoerceToType();
6447 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006448 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006449 UnpaddedSize = TyInfo.first;
6450 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006451 }
John McCall7f416cc2015-09-08 08:05:57 +00006452 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6453 if (IsVector && UnpaddedSize > PaddedSize)
6454 PaddedSize = CharUnits::fromQuantity(16);
6455 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006456
John McCall7f416cc2015-09-08 08:05:57 +00006457 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006458
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006459 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006460 llvm::Value *PaddedSizeV =
6461 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006462
6463 if (IsVector) {
6464 // Work out the address of a vector argument on the stack.
6465 // Vector arguments are always passed in the high bits of a
6466 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006467 Address OverflowArgAreaPtr =
6468 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006469 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006470 Address OverflowArgArea =
6471 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6472 TyInfo.second);
6473 Address MemAddr =
6474 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006475
6476 // Update overflow_arg_area_ptr pointer
6477 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006478 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6479 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006480 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6481
6482 return MemAddr;
6483 }
6484
John McCall7f416cc2015-09-08 08:05:57 +00006485 assert(PaddedSize.getQuantity() == 8);
6486
6487 unsigned MaxRegs, RegCountField, RegSaveIndex;
6488 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006489 if (InFPRs) {
6490 MaxRegs = 4; // Maximum of 4 FPR arguments
6491 RegCountField = 1; // __fpr
6492 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006493 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006494 } else {
6495 MaxRegs = 5; // Maximum of 5 GPR arguments
6496 RegCountField = 0; // __gpr
6497 RegSaveIndex = 2; // save offset for r2
6498 RegPadding = Padding; // values are passed in the low bits of a GPR
6499 }
6500
John McCall7f416cc2015-09-08 08:05:57 +00006501 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6502 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6503 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006504 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006505 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6506 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006507 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006508
6509 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6510 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6511 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6512 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6513
6514 // Emit code to load the value if it was passed in registers.
6515 CGF.EmitBlock(InRegBlock);
6516
6517 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006518 llvm::Value *ScaledRegCount =
6519 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6520 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006521 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6522 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006523 llvm::Value *RegOffset =
6524 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006525 Address RegSaveAreaPtr =
6526 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6527 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006528 llvm::Value *RegSaveArea =
6529 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006530 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6531 "raw_reg_addr"),
6532 PaddedSize);
6533 Address RegAddr =
6534 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006535
6536 // Update the register count
6537 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6538 llvm::Value *NewRegCount =
6539 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6540 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6541 CGF.EmitBranch(ContBlock);
6542
6543 // Emit code to load the value if it was passed in memory.
6544 CGF.EmitBlock(InMemBlock);
6545
6546 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006547 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6548 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6549 Address OverflowArgArea =
6550 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6551 PaddedSize);
6552 Address RawMemAddr =
6553 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6554 Address MemAddr =
6555 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006556
6557 // Update overflow_arg_area_ptr pointer
6558 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006559 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6560 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006561 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6562 CGF.EmitBranch(ContBlock);
6563
6564 // Return the appropriate result.
6565 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006566 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6567 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006568
6569 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006570 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6571 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006572
6573 return ResAddr;
6574}
6575
Ulrich Weigand47445072013-05-06 16:26:41 +00006576ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6577 if (RetTy->isVoidType())
6578 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006579 if (isVectorArgumentType(RetTy))
6580 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006581 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006582 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006583 return (isPromotableIntegerType(RetTy) ?
6584 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6585}
6586
6587ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6588 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006589 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006590 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006591
6592 // Integers and enums are extended to full register width.
6593 if (isPromotableIntegerType(Ty))
6594 return ABIArgInfo::getExtend();
6595
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006596 // Handle vector types and vector-like structure types. Note that
6597 // as opposed to float-like structure types, we do not allow any
6598 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006599 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006600 QualType SingleElementTy = GetSingleElementType(Ty);
6601 if (isVectorArgumentType(SingleElementTy) &&
6602 getContext().getTypeSize(SingleElementTy) == Size)
6603 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6604
6605 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006606 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006607 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006608
6609 // Handle small structures.
6610 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6611 // Structures with flexible arrays have variable length, so really
6612 // fail the size test above.
6613 const RecordDecl *RD = RT->getDecl();
6614 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006615 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006616
6617 // The structure is passed as an unextended integer, a float, or a double.
6618 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006619 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006620 assert(Size == 32 || Size == 64);
6621 if (Size == 32)
6622 PassTy = llvm::Type::getFloatTy(getVMContext());
6623 else
6624 PassTy = llvm::Type::getDoubleTy(getVMContext());
6625 } else
6626 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6627 return ABIArgInfo::getDirect(PassTy);
6628 }
6629
6630 // Non-structure compounds are passed indirectly.
6631 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006632 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006633
Craig Topper8a13c412014-05-21 05:09:00 +00006634 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006635}
6636
6637//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006638// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006639//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006640
6641namespace {
6642
6643class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6644public:
Chris Lattner2b037972010-07-29 02:01:43 +00006645 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6646 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006647 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006648 CodeGen::CodeGenModule &M,
6649 ForDefinition_t IsForDefinition) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006650};
6651
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006652}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006653
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006654void MSP430TargetCodeGenInfo::setTargetAttributes(
6655 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6656 ForDefinition_t IsForDefinition) const {
6657 if (!IsForDefinition)
6658 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006659 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006660 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6661 // Handle 'interrupt' attribute:
6662 llvm::Function *F = cast<llvm::Function>(GV);
6663
6664 // Step 1: Set ISR calling convention.
6665 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6666
6667 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006668 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006669
6670 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006671 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006672 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6673 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006674 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006675 }
6676}
6677
Chris Lattner0cf24192010-06-28 20:05:43 +00006678//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006679// MIPS ABI Implementation. This works for both little-endian and
6680// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006681//===----------------------------------------------------------------------===//
6682
John McCall943fae92010-05-27 06:19:26 +00006683namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006684class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006685 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006686 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6687 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006688 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006689 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006690 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006691 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006692public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006693 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006694 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006695 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006696
6697 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006698 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006699 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006700 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6701 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006702 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006703};
6704
John McCall943fae92010-05-27 06:19:26 +00006705class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006706 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006707public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006708 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6709 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006710 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006711
Craig Topper4f12f102014-03-12 06:41:41 +00006712 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006713 return 29;
6714 }
6715
Eric Christopher162c91c2015-06-05 22:03:00 +00006716 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006717 CodeGen::CodeGenModule &CGM,
6718 ForDefinition_t IsForDefinition) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006719 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006720 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006721 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006722
6723 if (FD->hasAttr<MipsLongCallAttr>())
6724 Fn->addFnAttr("long-call");
6725 else if (FD->hasAttr<MipsShortCallAttr>())
6726 Fn->addFnAttr("short-call");
6727
6728 // Other attributes do not have a meaning for declarations.
6729 if (!IsForDefinition)
6730 return;
6731
Reed Kotler3d5966f2013-03-13 20:40:30 +00006732 if (FD->hasAttr<Mips16Attr>()) {
6733 Fn->addFnAttr("mips16");
6734 }
6735 else if (FD->hasAttr<NoMips16Attr>()) {
6736 Fn->addFnAttr("nomips16");
6737 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006738
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006739 if (FD->hasAttr<MicroMipsAttr>())
6740 Fn->addFnAttr("micromips");
6741 else if (FD->hasAttr<NoMicroMipsAttr>())
6742 Fn->addFnAttr("nomicromips");
6743
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006744 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6745 if (!Attr)
6746 return;
6747
6748 const char *Kind;
6749 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006750 case MipsInterruptAttr::eic: Kind = "eic"; break;
6751 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6752 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6753 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6754 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6755 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6756 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6757 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6758 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6759 }
6760
6761 Fn->addFnAttr("interrupt", Kind);
6762
Reed Kotler373feca2013-01-16 17:10:28 +00006763 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006764
John McCall943fae92010-05-27 06:19:26 +00006765 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006766 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006767
Craig Topper4f12f102014-03-12 06:41:41 +00006768 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006769 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006770 }
John McCall943fae92010-05-27 06:19:26 +00006771};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006772}
John McCall943fae92010-05-27 06:19:26 +00006773
Eric Christopher7565e0d2015-05-29 23:09:49 +00006774void MipsABIInfo::CoerceToIntArgs(
6775 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006776 llvm::IntegerType *IntTy =
6777 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006778
6779 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6780 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6781 ArgList.push_back(IntTy);
6782
6783 // If necessary, add one more integer type to ArgList.
6784 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6785
6786 if (R)
6787 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006788}
6789
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006790// In N32/64, an aligned double precision floating point field is passed in
6791// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006792llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006793 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6794
6795 if (IsO32) {
6796 CoerceToIntArgs(TySize, ArgList);
6797 return llvm::StructType::get(getVMContext(), ArgList);
6798 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006799
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006800 if (Ty->isComplexType())
6801 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006802
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006803 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006804
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006805 // Unions/vectors are passed in integer registers.
6806 if (!RT || !RT->isStructureOrClassType()) {
6807 CoerceToIntArgs(TySize, ArgList);
6808 return llvm::StructType::get(getVMContext(), ArgList);
6809 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006810
6811 const RecordDecl *RD = RT->getDecl();
6812 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006813 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006814
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006815 uint64_t LastOffset = 0;
6816 unsigned idx = 0;
6817 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6818
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006819 // Iterate over fields in the struct/class and check if there are any aligned
6820 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006821 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6822 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006823 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006824 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6825
6826 if (!BT || BT->getKind() != BuiltinType::Double)
6827 continue;
6828
6829 uint64_t Offset = Layout.getFieldOffset(idx);
6830 if (Offset % 64) // Ignore doubles that are not aligned.
6831 continue;
6832
6833 // Add ((Offset - LastOffset) / 64) args of type i64.
6834 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6835 ArgList.push_back(I64);
6836
6837 // Add double type.
6838 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6839 LastOffset = Offset + 64;
6840 }
6841
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006842 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6843 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006844
6845 return llvm::StructType::get(getVMContext(), ArgList);
6846}
6847
Akira Hatanakaddd66342013-10-29 18:41:15 +00006848llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6849 uint64_t Offset) const {
6850 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006851 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006852
Akira Hatanakaddd66342013-10-29 18:41:15 +00006853 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006854}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006855
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006856ABIArgInfo
6857MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006858 Ty = useFirstFieldIfTransparentUnion(Ty);
6859
Akira Hatanaka1632af62012-01-09 19:31:25 +00006860 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006861 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006862 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006863
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006864 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6865 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006866 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6867 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006868
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006869 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006870 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006871 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006872 return ABIArgInfo::getIgnore();
6873
Mark Lacey3825e832013-10-06 01:33:34 +00006874 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006875 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006876 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006877 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006878
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006879 // If we have reached here, aggregates are passed directly by coercing to
6880 // another structure type. Padding is inserted if the offset of the
6881 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006882 ABIArgInfo ArgInfo =
6883 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6884 getPaddingType(OrigOffset, CurrOffset));
6885 ArgInfo.setInReg(true);
6886 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006887 }
6888
6889 // Treat an enum type as its underlying type.
6890 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6891 Ty = EnumTy->getDecl()->getIntegerType();
6892
Daniel Sanders5b445b32014-10-24 14:42:42 +00006893 // All integral types are promoted to the GPR width.
6894 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006895 return ABIArgInfo::getExtend();
6896
Akira Hatanakaddd66342013-10-29 18:41:15 +00006897 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006898 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006899}
6900
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006901llvm::Type*
6902MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006903 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006904 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006905
Akira Hatanakab6f74432012-02-09 18:49:26 +00006906 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006907 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006908 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6909 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006910
Akira Hatanakab6f74432012-02-09 18:49:26 +00006911 // N32/64 returns struct/classes in floating point registers if the
6912 // following conditions are met:
6913 // 1. The size of the struct/class is no larger than 128-bit.
6914 // 2. The struct/class has one or two fields all of which are floating
6915 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006916 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006917 //
6918 // Any other composite results are returned in integer registers.
6919 //
6920 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6921 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6922 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006923 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006924
Akira Hatanakab6f74432012-02-09 18:49:26 +00006925 if (!BT || !BT->isFloatingPoint())
6926 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006927
David Blaikie2d7c57e2012-04-30 02:36:29 +00006928 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006929 }
6930
6931 if (b == e)
6932 return llvm::StructType::get(getVMContext(), RTList,
6933 RD->hasAttr<PackedAttr>());
6934
6935 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006936 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006937 }
6938
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006939 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006940 return llvm::StructType::get(getVMContext(), RTList);
6941}
6942
Akira Hatanakab579fe52011-06-02 00:09:17 +00006943ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006944 uint64_t Size = getContext().getTypeSize(RetTy);
6945
Daniel Sandersed39f582014-09-04 13:28:14 +00006946 if (RetTy->isVoidType())
6947 return ABIArgInfo::getIgnore();
6948
6949 // O32 doesn't treat zero-sized structs differently from other structs.
6950 // However, N32/N64 ignores zero sized return values.
6951 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006952 return ABIArgInfo::getIgnore();
6953
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006954 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006955 if (Size <= 128) {
6956 if (RetTy->isAnyComplexType())
6957 return ABIArgInfo::getDirect();
6958
Daniel Sanderse5018b62014-09-04 15:05:39 +00006959 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006960 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006961 if (!IsO32 ||
6962 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6963 ABIArgInfo ArgInfo =
6964 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6965 ArgInfo.setInReg(true);
6966 return ArgInfo;
6967 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006968 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006969
John McCall7f416cc2015-09-08 08:05:57 +00006970 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006971 }
6972
6973 // Treat an enum type as its underlying type.
6974 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6975 RetTy = EnumTy->getDecl()->getIntegerType();
6976
6977 return (RetTy->isPromotableIntegerType() ?
6978 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6979}
6980
6981void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006982 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006983 if (!getCXXABI().classifyReturnType(FI))
6984 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006985
Eric Christopher7565e0d2015-05-29 23:09:49 +00006986 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006987 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006988
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006989 for (auto &I : FI.arguments())
6990 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006991}
6992
John McCall7f416cc2015-09-08 08:05:57 +00006993Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6994 QualType OrigTy) const {
6995 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006996
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006997 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6998 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006999 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007000 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00007001 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007002 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00007003 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007004 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00007005 DidPromote = true;
7006 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7007 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00007008 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00007009
John McCall7f416cc2015-09-08 08:05:57 +00007010 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007011
John McCall7f416cc2015-09-08 08:05:57 +00007012 // The alignment of things in the argument area is never larger than
7013 // StackAlignInBytes.
7014 TyInfo.second =
7015 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7016
7017 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7018 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7019
7020 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7021 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7022
7023
7024 // If there was a promotion, "unpromote" into a temporary.
7025 // TODO: can we just use a pointer into a subset of the original slot?
7026 if (DidPromote) {
7027 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7028 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7029
7030 // Truncate down to the right width.
7031 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7032 : CGF.IntPtrTy);
7033 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7034 if (OrigTy->isPointerType())
7035 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7036
7037 CGF.Builder.CreateStore(V, Temp);
7038 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007039 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007040
John McCall7f416cc2015-09-08 08:05:57 +00007041 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007042}
7043
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007044bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
7045 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007046
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007047 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7048 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7049 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00007050
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007051 return false;
7052}
7053
John McCall943fae92010-05-27 06:19:26 +00007054bool
7055MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7056 llvm::Value *Address) const {
7057 // This information comes from gcc's implementation, which seems to
7058 // as canonical as it gets.
7059
John McCall943fae92010-05-27 06:19:26 +00007060 // Everything on MIPS is 4 bytes. Double-precision FP registers
7061 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007062 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007063
7064 // 0-31 are the general purpose registers, $0 - $31.
7065 // 32-63 are the floating-point registers, $f0 - $f31.
7066 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7067 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007068 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007069
7070 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7071 // They are one bit wide and ignored here.
7072
7073 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7074 // (coprocessor 1 is the FP unit)
7075 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7076 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7077 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007078 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007079 return false;
7080}
7081
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007082//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007083// AVR ABI Implementation.
7084//===----------------------------------------------------------------------===//
7085
7086namespace {
7087class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7088public:
7089 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7090 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7091
7092 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007093 CodeGen::CodeGenModule &CGM,
7094 ForDefinition_t IsForDefinition) const override {
7095 if (!IsForDefinition)
7096 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007097 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7098 if (!FD) return;
7099 auto *Fn = cast<llvm::Function>(GV);
7100
7101 if (FD->getAttr<AVRInterruptAttr>())
7102 Fn->addFnAttr("interrupt");
7103
7104 if (FD->getAttr<AVRSignalAttr>())
7105 Fn->addFnAttr("signal");
7106 }
7107};
7108}
7109
7110//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007111// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007112// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007113// handling.
7114//===----------------------------------------------------------------------===//
7115
7116namespace {
7117
7118class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7119public:
7120 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7121 : DefaultTargetCodeGenInfo(CGT) {}
7122
Eric Christopher162c91c2015-06-05 22:03:00 +00007123 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007124 CodeGen::CodeGenModule &M,
7125 ForDefinition_t IsForDefinition) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007126};
7127
Eric Christopher162c91c2015-06-05 22:03:00 +00007128void TCETargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007129 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7130 ForDefinition_t IsForDefinition) const {
7131 if (!IsForDefinition)
7132 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007133 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007134 if (!FD) return;
7135
7136 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007137
David Blaikiebbafb8a2012-03-11 07:00:24 +00007138 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007139 if (FD->hasAttr<OpenCLKernelAttr>()) {
7140 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007141 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007142 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7143 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007144 // Convert the reqd_work_group_size() attributes to metadata.
7145 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007146 llvm::NamedMDNode *OpenCLMetadata =
7147 M.getModule().getOrInsertNamedMetadata(
7148 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007149
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007150 SmallVector<llvm::Metadata *, 5> Operands;
7151 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007152
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007153 Operands.push_back(
7154 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7155 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7156 Operands.push_back(
7157 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7158 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7159 Operands.push_back(
7160 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7161 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007162
Eric Christopher7565e0d2015-05-29 23:09:49 +00007163 // Add a boolean constant operand for "required" (true) or "hint"
7164 // (false) for implementing the work_group_size_hint attr later.
7165 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007166 Operands.push_back(
7167 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007168 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7169 }
7170 }
7171 }
7172}
7173
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007174}
John McCall943fae92010-05-27 06:19:26 +00007175
Tony Linthicum76329bf2011-12-12 21:14:55 +00007176//===----------------------------------------------------------------------===//
7177// Hexagon ABI Implementation
7178//===----------------------------------------------------------------------===//
7179
7180namespace {
7181
7182class HexagonABIInfo : public ABIInfo {
7183
7184
7185public:
7186 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7187
7188private:
7189
7190 ABIArgInfo classifyReturnType(QualType RetTy) const;
7191 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7192
Craig Topper4f12f102014-03-12 06:41:41 +00007193 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007194
John McCall7f416cc2015-09-08 08:05:57 +00007195 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7196 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007197};
7198
7199class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7200public:
7201 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7202 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7203
Craig Topper4f12f102014-03-12 06:41:41 +00007204 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007205 return 29;
7206 }
7207};
7208
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007209}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007210
7211void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007212 if (!getCXXABI().classifyReturnType(FI))
7213 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007214 for (auto &I : FI.arguments())
7215 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007216}
7217
7218ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7219 if (!isAggregateTypeForABI(Ty)) {
7220 // Treat an enum type as its underlying type.
7221 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7222 Ty = EnumTy->getDecl()->getIntegerType();
7223
7224 return (Ty->isPromotableIntegerType() ?
7225 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7226 }
7227
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007228 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7229 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7230
Tony Linthicum76329bf2011-12-12 21:14:55 +00007231 // Ignore empty records.
7232 if (isEmptyRecord(getContext(), Ty, true))
7233 return ABIArgInfo::getIgnore();
7234
Tony Linthicum76329bf2011-12-12 21:14:55 +00007235 uint64_t Size = getContext().getTypeSize(Ty);
7236 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007237 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007238 // Pass in the smallest viable integer type.
7239 else if (Size > 32)
7240 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7241 else if (Size > 16)
7242 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7243 else if (Size > 8)
7244 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7245 else
7246 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7247}
7248
7249ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7250 if (RetTy->isVoidType())
7251 return ABIArgInfo::getIgnore();
7252
7253 // Large vector types should be returned via memory.
7254 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007255 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007256
7257 if (!isAggregateTypeForABI(RetTy)) {
7258 // Treat an enum type as its underlying type.
7259 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7260 RetTy = EnumTy->getDecl()->getIntegerType();
7261
7262 return (RetTy->isPromotableIntegerType() ?
7263 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7264 }
7265
Tony Linthicum76329bf2011-12-12 21:14:55 +00007266 if (isEmptyRecord(getContext(), RetTy, true))
7267 return ABIArgInfo::getIgnore();
7268
7269 // Aggregates <= 8 bytes are returned in r0; other aggregates
7270 // are returned indirectly.
7271 uint64_t Size = getContext().getTypeSize(RetTy);
7272 if (Size <= 64) {
7273 // Return in the smallest viable integer type.
7274 if (Size <= 8)
7275 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7276 if (Size <= 16)
7277 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7278 if (Size <= 32)
7279 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7280 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7281 }
7282
John McCall7f416cc2015-09-08 08:05:57 +00007283 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007284}
7285
John McCall7f416cc2015-09-08 08:05:57 +00007286Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7287 QualType Ty) const {
7288 // FIXME: Someone needs to audit that this handle alignment correctly.
7289 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7290 getContext().getTypeInfoInChars(Ty),
7291 CharUnits::fromQuantity(4),
7292 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007293}
7294
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007295//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007296// Lanai ABI Implementation
7297//===----------------------------------------------------------------------===//
7298
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007299namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007300class LanaiABIInfo : public DefaultABIInfo {
7301public:
7302 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7303
7304 bool shouldUseInReg(QualType Ty, CCState &State) const;
7305
7306 void computeInfo(CGFunctionInfo &FI) const override {
7307 CCState State(FI.getCallingConvention());
7308 // Lanai uses 4 registers to pass arguments unless the function has the
7309 // regparm attribute set.
7310 if (FI.getHasRegParm()) {
7311 State.FreeRegs = FI.getRegParm();
7312 } else {
7313 State.FreeRegs = 4;
7314 }
7315
7316 if (!getCXXABI().classifyReturnType(FI))
7317 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7318 for (auto &I : FI.arguments())
7319 I.info = classifyArgumentType(I.type, State);
7320 }
7321
Jacques Pienaare74d9132016-04-26 00:09:29 +00007322 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007323 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7324};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007325} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007326
7327bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7328 unsigned Size = getContext().getTypeSize(Ty);
7329 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7330
7331 if (SizeInRegs == 0)
7332 return false;
7333
7334 if (SizeInRegs > State.FreeRegs) {
7335 State.FreeRegs = 0;
7336 return false;
7337 }
7338
7339 State.FreeRegs -= SizeInRegs;
7340
7341 return true;
7342}
7343
Jacques Pienaare74d9132016-04-26 00:09:29 +00007344ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7345 CCState &State) const {
7346 if (!ByVal) {
7347 if (State.FreeRegs) {
7348 --State.FreeRegs; // Non-byval indirects just use one pointer.
7349 return getNaturalAlignIndirectInReg(Ty);
7350 }
7351 return getNaturalAlignIndirect(Ty, false);
7352 }
7353
7354 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007355 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007356 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7357 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7358 /*Realign=*/TypeAlign >
7359 MinABIStackAlignInBytes);
7360}
7361
Jacques Pienaard964cc22016-03-28 21:02:54 +00007362ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7363 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007364 // Check with the C++ ABI first.
7365 const RecordType *RT = Ty->getAs<RecordType>();
7366 if (RT) {
7367 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7368 if (RAA == CGCXXABI::RAA_Indirect) {
7369 return getIndirectResult(Ty, /*ByVal=*/false, State);
7370 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7371 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7372 }
7373 }
7374
7375 if (isAggregateTypeForABI(Ty)) {
7376 // Structures with flexible arrays are always indirect.
7377 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7378 return getIndirectResult(Ty, /*ByVal=*/true, State);
7379
7380 // Ignore empty structs/unions.
7381 if (isEmptyRecord(getContext(), Ty, true))
7382 return ABIArgInfo::getIgnore();
7383
7384 llvm::LLVMContext &LLVMContext = getVMContext();
7385 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7386 if (SizeInRegs <= State.FreeRegs) {
7387 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7388 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7389 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7390 State.FreeRegs -= SizeInRegs;
7391 return ABIArgInfo::getDirectInReg(Result);
7392 } else {
7393 State.FreeRegs = 0;
7394 }
7395 return getIndirectResult(Ty, true, State);
7396 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007397
7398 // Treat an enum type as its underlying type.
7399 if (const auto *EnumTy = Ty->getAs<EnumType>())
7400 Ty = EnumTy->getDecl()->getIntegerType();
7401
Jacques Pienaare74d9132016-04-26 00:09:29 +00007402 bool InReg = shouldUseInReg(Ty, State);
7403 if (Ty->isPromotableIntegerType()) {
7404 if (InReg)
7405 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007406 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007407 }
7408 if (InReg)
7409 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007410 return ABIArgInfo::getDirect();
7411}
7412
7413namespace {
7414class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7415public:
7416 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7417 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7418};
7419}
7420
7421//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007422// AMDGPU ABI Implementation
7423//===----------------------------------------------------------------------===//
7424
7425namespace {
7426
Matt Arsenault88d7da02016-08-22 19:25:59 +00007427class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007428private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007429 static const unsigned MaxNumRegsForArgsRet = 16;
7430
Matt Arsenault3fe73952017-08-09 21:44:58 +00007431 unsigned numRegsForType(QualType Ty) const;
7432
7433 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7434 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7435 uint64_t Members) const override;
7436
7437public:
7438 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7439 DefaultABIInfo(CGT) {}
7440
7441 ABIArgInfo classifyReturnType(QualType RetTy) const;
7442 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7443 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007444
7445 void computeInfo(CGFunctionInfo &FI) const override;
7446};
7447
Matt Arsenault3fe73952017-08-09 21:44:58 +00007448bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7449 return true;
7450}
7451
7452bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7453 const Type *Base, uint64_t Members) const {
7454 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7455
7456 // Homogeneous Aggregates may occupy at most 16 registers.
7457 return Members * NumRegs <= MaxNumRegsForArgsRet;
7458}
7459
Matt Arsenault3fe73952017-08-09 21:44:58 +00007460/// Estimate number of registers the type will use when passed in registers.
7461unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7462 unsigned NumRegs = 0;
7463
7464 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7465 // Compute from the number of elements. The reported size is based on the
7466 // in-memory size, which includes the padding 4th element for 3-vectors.
7467 QualType EltTy = VT->getElementType();
7468 unsigned EltSize = getContext().getTypeSize(EltTy);
7469
7470 // 16-bit element vectors should be passed as packed.
7471 if (EltSize == 16)
7472 return (VT->getNumElements() + 1) / 2;
7473
7474 unsigned EltNumRegs = (EltSize + 31) / 32;
7475 return EltNumRegs * VT->getNumElements();
7476 }
7477
7478 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7479 const RecordDecl *RD = RT->getDecl();
7480 assert(!RD->hasFlexibleArrayMember());
7481
7482 for (const FieldDecl *Field : RD->fields()) {
7483 QualType FieldTy = Field->getType();
7484 NumRegs += numRegsForType(FieldTy);
7485 }
7486
7487 return NumRegs;
7488 }
7489
7490 return (getContext().getTypeSize(Ty) + 31) / 32;
7491}
7492
Matt Arsenault88d7da02016-08-22 19:25:59 +00007493void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007494 llvm::CallingConv::ID CC = FI.getCallingConvention();
7495
Matt Arsenault88d7da02016-08-22 19:25:59 +00007496 if (!getCXXABI().classifyReturnType(FI))
7497 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7498
Matt Arsenault3fe73952017-08-09 21:44:58 +00007499 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7500 for (auto &Arg : FI.arguments()) {
7501 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7502 Arg.info = classifyKernelArgumentType(Arg.type);
7503 } else {
7504 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7505 }
7506 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007507}
7508
Matt Arsenault3fe73952017-08-09 21:44:58 +00007509ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7510 if (isAggregateTypeForABI(RetTy)) {
7511 // Records with non-trivial destructors/copy-constructors should not be
7512 // returned by value.
7513 if (!getRecordArgABI(RetTy, getCXXABI())) {
7514 // Ignore empty structs/unions.
7515 if (isEmptyRecord(getContext(), RetTy, true))
7516 return ABIArgInfo::getIgnore();
7517
7518 // Lower single-element structs to just return a regular value.
7519 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7520 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7521
7522 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7523 const RecordDecl *RD = RT->getDecl();
7524 if (RD->hasFlexibleArrayMember())
7525 return DefaultABIInfo::classifyReturnType(RetTy);
7526 }
7527
7528 // Pack aggregates <= 4 bytes into single VGPR or pair.
7529 uint64_t Size = getContext().getTypeSize(RetTy);
7530 if (Size <= 16)
7531 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7532
7533 if (Size <= 32)
7534 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7535
7536 if (Size <= 64) {
7537 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7538 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7539 }
7540
7541 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7542 return ABIArgInfo::getDirect();
7543 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007544 }
7545
Matt Arsenault3fe73952017-08-09 21:44:58 +00007546 // Otherwise just do the default thing.
7547 return DefaultABIInfo::classifyReturnType(RetTy);
7548}
7549
7550/// For kernels all parameters are really passed in a special buffer. It doesn't
7551/// make sense to pass anything byval, so everything must be direct.
7552ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7553 Ty = useFirstFieldIfTransparentUnion(Ty);
7554
7555 // TODO: Can we omit empty structs?
7556
Matt Arsenault88d7da02016-08-22 19:25:59 +00007557 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007558 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7559 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007560
7561 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7562 // individual elements, which confuses the Clover OpenCL backend; therefore we
7563 // have to set it to false here. Other args of getDirect() are just defaults.
7564 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7565}
7566
Matt Arsenault3fe73952017-08-09 21:44:58 +00007567ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7568 unsigned &NumRegsLeft) const {
7569 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7570
7571 Ty = useFirstFieldIfTransparentUnion(Ty);
7572
7573 if (isAggregateTypeForABI(Ty)) {
7574 // Records with non-trivial destructors/copy-constructors should not be
7575 // passed by value.
7576 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7577 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7578
7579 // Ignore empty structs/unions.
7580 if (isEmptyRecord(getContext(), Ty, true))
7581 return ABIArgInfo::getIgnore();
7582
7583 // Lower single-element structs to just pass a regular value. TODO: We
7584 // could do reasonable-size multiple-element structs too, using getExpand(),
7585 // though watch out for things like bitfields.
7586 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7587 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7588
7589 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7590 const RecordDecl *RD = RT->getDecl();
7591 if (RD->hasFlexibleArrayMember())
7592 return DefaultABIInfo::classifyArgumentType(Ty);
7593 }
7594
7595 // Pack aggregates <= 8 bytes into single VGPR or pair.
7596 uint64_t Size = getContext().getTypeSize(Ty);
7597 if (Size <= 64) {
7598 unsigned NumRegs = (Size + 31) / 32;
7599 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7600
7601 if (Size <= 16)
7602 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7603
7604 if (Size <= 32)
7605 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7606
7607 // XXX: Should this be i64 instead, and should the limit increase?
7608 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7609 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7610 }
7611
7612 if (NumRegsLeft > 0) {
7613 unsigned NumRegs = numRegsForType(Ty);
7614 if (NumRegsLeft >= NumRegs) {
7615 NumRegsLeft -= NumRegs;
7616 return ABIArgInfo::getDirect();
7617 }
7618 }
7619 }
7620
7621 // Otherwise just do the default thing.
7622 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7623 if (!ArgInfo.isIndirect()) {
7624 unsigned NumRegs = numRegsForType(Ty);
7625 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7626 }
7627
7628 return ArgInfo;
7629}
7630
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007631class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7632public:
7633 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007634 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007635 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007636 CodeGen::CodeGenModule &M,
7637 ForDefinition_t IsForDefinition) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007638 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007639
Yaxun Liu402804b2016-12-15 08:09:08 +00007640 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7641 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007642
Alexander Richardson6d989432017-10-15 18:48:14 +00007643 LangAS getASTAllocaAddressSpace() const override {
7644 return getLangASFromTargetAS(
7645 getABIInfo().getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007646 }
Alexander Richardson6d989432017-10-15 18:48:14 +00007647 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7648 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007649 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7650 llvm::LLVMContext &C) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007651 llvm::Function *
7652 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7653 llvm::Function *BlockInvokeFunc,
7654 llvm::Value *BlockLiteral) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007655};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007656}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007657
Eric Christopher162c91c2015-06-05 22:03:00 +00007658void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007659 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7660 ForDefinition_t IsForDefinition) const {
7661 if (!IsForDefinition)
7662 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007663 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007664 if (!FD)
7665 return;
7666
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007667 llvm::Function *F = cast<llvm::Function>(GV);
7668
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007669 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7670 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7671 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7672 if (ReqdWGS || FlatWGS) {
7673 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7674 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7675 if (ReqdWGS && Min == 0 && Max == 0)
7676 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007677
7678 if (Min != 0) {
7679 assert(Min <= Max && "Min must be less than or equal Max");
7680
7681 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7682 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7683 } else
7684 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007685 }
7686
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007687 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7688 unsigned Min = Attr->getMin();
7689 unsigned Max = Attr->getMax();
7690
7691 if (Min != 0) {
7692 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7693
7694 std::string AttrVal = llvm::utostr(Min);
7695 if (Max != 0)
7696 AttrVal = AttrVal + "," + llvm::utostr(Max);
7697 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7698 } else
7699 assert(Max == 0 && "Max must be zero");
7700 }
7701
7702 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007703 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007704
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007705 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007706 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7707 }
7708
7709 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7710 uint32_t NumVGPR = Attr->getNumVGPR();
7711
7712 if (NumVGPR != 0)
7713 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007714 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007715}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007716
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007717unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7718 return llvm::CallingConv::AMDGPU_KERNEL;
7719}
7720
Yaxun Liu402804b2016-12-15 08:09:08 +00007721// Currently LLVM assumes null pointers always have value 0,
7722// which results in incorrectly transformed IR. Therefore, instead of
7723// emitting null pointers in private and local address spaces, a null
7724// pointer in generic address space is emitted which is casted to a
7725// pointer in local or private address space.
7726llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7727 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7728 QualType QT) const {
7729 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7730 return llvm::ConstantPointerNull::get(PT);
7731
7732 auto &Ctx = CGM.getContext();
7733 auto NPT = llvm::PointerType::get(PT->getElementType(),
7734 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7735 return llvm::ConstantExpr::getAddrSpaceCast(
7736 llvm::ConstantPointerNull::get(NPT), PT);
7737}
7738
Alexander Richardson6d989432017-10-15 18:48:14 +00007739LangAS
Yaxun Liucbf647c2017-07-08 13:24:52 +00007740AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7741 const VarDecl *D) const {
7742 assert(!CGM.getLangOpts().OpenCL &&
7743 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7744 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +00007745 LangAS DefaultGlobalAS = getLangASFromTargetAS(
7746 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007747 if (!D)
7748 return DefaultGlobalAS;
7749
Alexander Richardson6d989432017-10-15 18:48:14 +00007750 LangAS AddrSpace = D->getType().getAddressSpace();
7751 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007752 if (AddrSpace != LangAS::Default)
7753 return AddrSpace;
7754
7755 if (CGM.isTypeConstant(D->getType(), false)) {
7756 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7757 return ConstAS.getValue();
7758 }
7759 return DefaultGlobalAS;
7760}
7761
Yaxun Liu39195062017-08-04 18:16:31 +00007762llvm::SyncScope::ID
7763AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7764 llvm::LLVMContext &C) const {
7765 StringRef Name;
7766 switch (S) {
7767 case SyncScope::OpenCLWorkGroup:
7768 Name = "workgroup";
7769 break;
7770 case SyncScope::OpenCLDevice:
7771 Name = "agent";
7772 break;
7773 case SyncScope::OpenCLAllSVMDevices:
7774 Name = "";
7775 break;
7776 case SyncScope::OpenCLSubGroup:
7777 Name = "subgroup";
7778 }
7779 return C.getOrInsertSyncScopeID(Name);
7780}
7781
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007782//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007783// SPARC v8 ABI Implementation.
7784// Based on the SPARC Compliance Definition version 2.4.1.
7785//
7786// Ensures that complex values are passed in registers.
7787//
7788namespace {
7789class SparcV8ABIInfo : public DefaultABIInfo {
7790public:
7791 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7792
7793private:
7794 ABIArgInfo classifyReturnType(QualType RetTy) const;
7795 void computeInfo(CGFunctionInfo &FI) const override;
7796};
7797} // end anonymous namespace
7798
7799
7800ABIArgInfo
7801SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7802 if (Ty->isAnyComplexType()) {
7803 return ABIArgInfo::getDirect();
7804 }
7805 else {
7806 return DefaultABIInfo::classifyReturnType(Ty);
7807 }
7808}
7809
7810void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7811
7812 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7813 for (auto &Arg : FI.arguments())
7814 Arg.info = classifyArgumentType(Arg.type);
7815}
7816
7817namespace {
7818class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7819public:
7820 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7821 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7822};
7823} // end anonymous namespace
7824
7825//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007826// SPARC v9 ABI Implementation.
7827// Based on the SPARC Compliance Definition version 2.4.1.
7828//
7829// Function arguments a mapped to a nominal "parameter array" and promoted to
7830// registers depending on their type. Each argument occupies 8 or 16 bytes in
7831// the array, structs larger than 16 bytes are passed indirectly.
7832//
7833// One case requires special care:
7834//
7835// struct mixed {
7836// int i;
7837// float f;
7838// };
7839//
7840// When a struct mixed is passed by value, it only occupies 8 bytes in the
7841// parameter array, but the int is passed in an integer register, and the float
7842// is passed in a floating point register. This is represented as two arguments
7843// with the LLVM IR inreg attribute:
7844//
7845// declare void f(i32 inreg %i, float inreg %f)
7846//
7847// The code generator will only allocate 4 bytes from the parameter array for
7848// the inreg arguments. All other arguments are allocated a multiple of 8
7849// bytes.
7850//
7851namespace {
7852class SparcV9ABIInfo : public ABIInfo {
7853public:
7854 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7855
7856private:
7857 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007858 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007859 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7860 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007861
7862 // Coercion type builder for structs passed in registers. The coercion type
7863 // serves two purposes:
7864 //
7865 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7866 // in registers.
7867 // 2. Expose aligned floating point elements as first-level elements, so the
7868 // code generator knows to pass them in floating point registers.
7869 //
7870 // We also compute the InReg flag which indicates that the struct contains
7871 // aligned 32-bit floats.
7872 //
7873 struct CoerceBuilder {
7874 llvm::LLVMContext &Context;
7875 const llvm::DataLayout &DL;
7876 SmallVector<llvm::Type*, 8> Elems;
7877 uint64_t Size;
7878 bool InReg;
7879
7880 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7881 : Context(c), DL(dl), Size(0), InReg(false) {}
7882
7883 // Pad Elems with integers until Size is ToSize.
7884 void pad(uint64_t ToSize) {
7885 assert(ToSize >= Size && "Cannot remove elements");
7886 if (ToSize == Size)
7887 return;
7888
7889 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007890 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007891 if (Aligned > Size && Aligned <= ToSize) {
7892 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7893 Size = Aligned;
7894 }
7895
7896 // Add whole 64-bit words.
7897 while (Size + 64 <= ToSize) {
7898 Elems.push_back(llvm::Type::getInt64Ty(Context));
7899 Size += 64;
7900 }
7901
7902 // Final in-word padding.
7903 if (Size < ToSize) {
7904 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7905 Size = ToSize;
7906 }
7907 }
7908
7909 // Add a floating point element at Offset.
7910 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7911 // Unaligned floats are treated as integers.
7912 if (Offset % Bits)
7913 return;
7914 // The InReg flag is only required if there are any floats < 64 bits.
7915 if (Bits < 64)
7916 InReg = true;
7917 pad(Offset);
7918 Elems.push_back(Ty);
7919 Size = Offset + Bits;
7920 }
7921
7922 // Add a struct type to the coercion type, starting at Offset (in bits).
7923 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7924 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7925 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7926 llvm::Type *ElemTy = StrTy->getElementType(i);
7927 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7928 switch (ElemTy->getTypeID()) {
7929 case llvm::Type::StructTyID:
7930 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7931 break;
7932 case llvm::Type::FloatTyID:
7933 addFloat(ElemOffset, ElemTy, 32);
7934 break;
7935 case llvm::Type::DoubleTyID:
7936 addFloat(ElemOffset, ElemTy, 64);
7937 break;
7938 case llvm::Type::FP128TyID:
7939 addFloat(ElemOffset, ElemTy, 128);
7940 break;
7941 case llvm::Type::PointerTyID:
7942 if (ElemOffset % 64 == 0) {
7943 pad(ElemOffset);
7944 Elems.push_back(ElemTy);
7945 Size += 64;
7946 }
7947 break;
7948 default:
7949 break;
7950 }
7951 }
7952 }
7953
7954 // Check if Ty is a usable substitute for the coercion type.
7955 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007956 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007957 }
7958
7959 // Get the coercion type as a literal struct type.
7960 llvm::Type *getType() const {
7961 if (Elems.size() == 1)
7962 return Elems.front();
7963 else
7964 return llvm::StructType::get(Context, Elems);
7965 }
7966 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007967};
7968} // end anonymous namespace
7969
7970ABIArgInfo
7971SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7972 if (Ty->isVoidType())
7973 return ABIArgInfo::getIgnore();
7974
7975 uint64_t Size = getContext().getTypeSize(Ty);
7976
7977 // Anything too big to fit in registers is passed with an explicit indirect
7978 // pointer / sret pointer.
7979 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007980 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007981
7982 // Treat an enum type as its underlying type.
7983 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7984 Ty = EnumTy->getDecl()->getIntegerType();
7985
7986 // Integer types smaller than a register are extended.
7987 if (Size < 64 && Ty->isIntegerType())
7988 return ABIArgInfo::getExtend();
7989
7990 // Other non-aggregates go in registers.
7991 if (!isAggregateTypeForABI(Ty))
7992 return ABIArgInfo::getDirect();
7993
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007994 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7995 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7996 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007997 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007998
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007999 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008000 // Build a coercion type from the LLVM struct type.
8001 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8002 if (!StrTy)
8003 return ABIArgInfo::getDirect();
8004
8005 CoerceBuilder CB(getVMContext(), getDataLayout());
8006 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00008007 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008008
8009 // Try to use the original type for coercion.
8010 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8011
8012 if (CB.InReg)
8013 return ABIArgInfo::getDirectInReg(CoerceTy);
8014 else
8015 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008016}
8017
John McCall7f416cc2015-09-08 08:05:57 +00008018Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8019 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008020 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8021 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8022 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8023 AI.setCoerceToType(ArgTy);
8024
John McCall7f416cc2015-09-08 08:05:57 +00008025 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008026
John McCall7f416cc2015-09-08 08:05:57 +00008027 CGBuilderTy &Builder = CGF.Builder;
8028 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8029 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8030
8031 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8032
8033 Address ArgAddr = Address::invalid();
8034 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008035 switch (AI.getKind()) {
8036 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008037 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008038 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008039 llvm_unreachable("Unsupported ABI kind for va_arg");
8040
John McCall7f416cc2015-09-08 08:05:57 +00008041 case ABIArgInfo::Extend: {
8042 Stride = SlotSize;
8043 CharUnits Offset = SlotSize - TypeInfo.first;
8044 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008045 break;
John McCall7f416cc2015-09-08 08:05:57 +00008046 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008047
John McCall7f416cc2015-09-08 08:05:57 +00008048 case ABIArgInfo::Direct: {
8049 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008050 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008051 ArgAddr = Addr;
8052 break;
John McCall7f416cc2015-09-08 08:05:57 +00008053 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008054
8055 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008056 Stride = SlotSize;
8057 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8058 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8059 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008060 break;
8061
8062 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008063 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008064 }
8065
8066 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008067 llvm::Value *NextPtr =
8068 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8069 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008070
John McCall7f416cc2015-09-08 08:05:57 +00008071 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008072}
8073
8074void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8075 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008076 for (auto &I : FI.arguments())
8077 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008078}
8079
8080namespace {
8081class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8082public:
8083 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8084 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008085
Craig Topper4f12f102014-03-12 06:41:41 +00008086 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008087 return 14;
8088 }
8089
8090 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008091 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008092};
8093} // end anonymous namespace
8094
Roman Divackyf02c9942014-02-24 18:46:27 +00008095bool
8096SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8097 llvm::Value *Address) const {
8098 // This is calculated from the LLVM and GCC tables and verified
8099 // against gcc output. AFAIK all ABIs use the same encoding.
8100
8101 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8102
8103 llvm::IntegerType *i8 = CGF.Int8Ty;
8104 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8105 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8106
8107 // 0-31: the 8-byte general-purpose registers
8108 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8109
8110 // 32-63: f0-31, the 4-byte floating-point registers
8111 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8112
8113 // Y = 64
8114 // PSR = 65
8115 // WIM = 66
8116 // TBR = 67
8117 // PC = 68
8118 // NPC = 69
8119 // FSR = 70
8120 // CSR = 71
8121 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008122
Roman Divackyf02c9942014-02-24 18:46:27 +00008123 // 72-87: d0-15, the 8-byte floating-point registers
8124 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8125
8126 return false;
8127}
8128
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008129
Robert Lytton0e076492013-08-13 09:43:10 +00008130//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008131// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008132//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008133
Robert Lytton0e076492013-08-13 09:43:10 +00008134namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008135
8136/// A SmallStringEnc instance is used to build up the TypeString by passing
8137/// it by reference between functions that append to it.
8138typedef llvm::SmallString<128> SmallStringEnc;
8139
8140/// TypeStringCache caches the meta encodings of Types.
8141///
8142/// The reason for caching TypeStrings is two fold:
8143/// 1. To cache a type's encoding for later uses;
8144/// 2. As a means to break recursive member type inclusion.
8145///
8146/// A cache Entry can have a Status of:
8147/// NonRecursive: The type encoding is not recursive;
8148/// Recursive: The type encoding is recursive;
8149/// Incomplete: An incomplete TypeString;
8150/// IncompleteUsed: An incomplete TypeString that has been used in a
8151/// Recursive type encoding.
8152///
8153/// A NonRecursive entry will have all of its sub-members expanded as fully
8154/// as possible. Whilst it may contain types which are recursive, the type
8155/// itself is not recursive and thus its encoding may be safely used whenever
8156/// the type is encountered.
8157///
8158/// A Recursive entry will have all of its sub-members expanded as fully as
8159/// possible. The type itself is recursive and it may contain other types which
8160/// are recursive. The Recursive encoding must not be used during the expansion
8161/// of a recursive type's recursive branch. For simplicity the code uses
8162/// IncompleteCount to reject all usage of Recursive encodings for member types.
8163///
8164/// An Incomplete entry is always a RecordType and only encodes its
8165/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8166/// are placed into the cache during type expansion as a means to identify and
8167/// handle recursive inclusion of types as sub-members. If there is recursion
8168/// the entry becomes IncompleteUsed.
8169///
8170/// During the expansion of a RecordType's members:
8171///
8172/// If the cache contains a NonRecursive encoding for the member type, the
8173/// cached encoding is used;
8174///
8175/// If the cache contains a Recursive encoding for the member type, the
8176/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8177///
8178/// If the member is a RecordType, an Incomplete encoding is placed into the
8179/// cache to break potential recursive inclusion of itself as a sub-member;
8180///
8181/// Once a member RecordType has been expanded, its temporary incomplete
8182/// entry is removed from the cache. If a Recursive encoding was swapped out
8183/// it is swapped back in;
8184///
8185/// If an incomplete entry is used to expand a sub-member, the incomplete
8186/// entry is marked as IncompleteUsed. The cache keeps count of how many
8187/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8188///
8189/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8190/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8191/// Else the member is part of a recursive type and thus the recursion has
8192/// been exited too soon for the encoding to be correct for the member.
8193///
8194class TypeStringCache {
8195 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8196 struct Entry {
8197 std::string Str; // The encoded TypeString for the type.
8198 enum Status State; // Information about the encoding in 'Str'.
8199 std::string Swapped; // A temporary place holder for a Recursive encoding
8200 // during the expansion of RecordType's members.
8201 };
8202 std::map<const IdentifierInfo *, struct Entry> Map;
8203 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8204 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8205public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008206 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008207 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8208 bool removeIncomplete(const IdentifierInfo *ID);
8209 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8210 bool IsRecursive);
8211 StringRef lookupStr(const IdentifierInfo *ID);
8212};
8213
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008214/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008215/// FieldEncoding is a helper for this ordering process.
8216class FieldEncoding {
8217 bool HasName;
8218 std::string Enc;
8219public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008220 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008221 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008222 bool operator<(const FieldEncoding &rhs) const {
8223 if (HasName != rhs.HasName) return HasName;
8224 return Enc < rhs.Enc;
8225 }
8226};
8227
Robert Lytton7d1db152013-08-19 09:46:39 +00008228class XCoreABIInfo : public DefaultABIInfo {
8229public:
8230 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008231 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8232 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008233};
8234
Robert Lyttond21e2d72014-03-03 13:45:29 +00008235class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008236 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008237public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008238 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008239 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008240 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8241 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008242};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008243
Robert Lytton2d196952013-10-11 10:29:34 +00008244} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008245
James Y Knight29b5f082016-02-24 02:59:33 +00008246// TODO: this implementation is likely now redundant with the default
8247// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008248Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8249 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008250 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008251
Robert Lytton2d196952013-10-11 10:29:34 +00008252 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008253 CharUnits SlotSize = CharUnits::fromQuantity(4);
8254 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008255
Robert Lytton2d196952013-10-11 10:29:34 +00008256 // Handle the argument.
8257 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008258 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008259 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8260 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8261 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008262 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008263
8264 Address Val = Address::invalid();
8265 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008266 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008267 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008268 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008269 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008270 llvm_unreachable("Unsupported ABI kind for va_arg");
8271 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008272 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8273 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008274 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008275 case ABIArgInfo::Extend:
8276 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008277 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8278 ArgSize = CharUnits::fromQuantity(
8279 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008280 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008281 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008282 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008283 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8284 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8285 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008286 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008287 }
Robert Lytton2d196952013-10-11 10:29:34 +00008288
8289 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008290 if (!ArgSize.isZero()) {
8291 llvm::Value *APN =
8292 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8293 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008294 }
John McCall7f416cc2015-09-08 08:05:57 +00008295
Robert Lytton2d196952013-10-11 10:29:34 +00008296 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008297}
Robert Lytton0e076492013-08-13 09:43:10 +00008298
Robert Lytton844aeeb2014-05-02 09:33:20 +00008299/// During the expansion of a RecordType, an incomplete TypeString is placed
8300/// into the cache as a means to identify and break recursion.
8301/// If there is a Recursive encoding in the cache, it is swapped out and will
8302/// be reinserted by removeIncomplete().
8303/// All other types of encoding should have been used rather than arriving here.
8304void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8305 std::string StubEnc) {
8306 if (!ID)
8307 return;
8308 Entry &E = Map[ID];
8309 assert( (E.Str.empty() || E.State == Recursive) &&
8310 "Incorrectly use of addIncomplete");
8311 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8312 E.Swapped.swap(E.Str); // swap out the Recursive
8313 E.Str.swap(StubEnc);
8314 E.State = Incomplete;
8315 ++IncompleteCount;
8316}
8317
8318/// Once the RecordType has been expanded, the temporary incomplete TypeString
8319/// must be removed from the cache.
8320/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8321/// Returns true if the RecordType was defined recursively.
8322bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8323 if (!ID)
8324 return false;
8325 auto I = Map.find(ID);
8326 assert(I != Map.end() && "Entry not present");
8327 Entry &E = I->second;
8328 assert( (E.State == Incomplete ||
8329 E.State == IncompleteUsed) &&
8330 "Entry must be an incomplete type");
8331 bool IsRecursive = false;
8332 if (E.State == IncompleteUsed) {
8333 // We made use of our Incomplete encoding, thus we are recursive.
8334 IsRecursive = true;
8335 --IncompleteUsedCount;
8336 }
8337 if (E.Swapped.empty())
8338 Map.erase(I);
8339 else {
8340 // Swap the Recursive back.
8341 E.Swapped.swap(E.Str);
8342 E.Swapped.clear();
8343 E.State = Recursive;
8344 }
8345 --IncompleteCount;
8346 return IsRecursive;
8347}
8348
8349/// Add the encoded TypeString to the cache only if it is NonRecursive or
8350/// Recursive (viz: all sub-members were expanded as fully as possible).
8351void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8352 bool IsRecursive) {
8353 if (!ID || IncompleteUsedCount)
8354 return; // No key or it is is an incomplete sub-type so don't add.
8355 Entry &E = Map[ID];
8356 if (IsRecursive && !E.Str.empty()) {
8357 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8358 "This is not the same Recursive entry");
8359 // The parent container was not recursive after all, so we could have used
8360 // this Recursive sub-member entry after all, but we assumed the worse when
8361 // we started viz: IncompleteCount!=0.
8362 return;
8363 }
8364 assert(E.Str.empty() && "Entry already present");
8365 E.Str = Str.str();
8366 E.State = IsRecursive? Recursive : NonRecursive;
8367}
8368
8369/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8370/// are recursively expanding a type (IncompleteCount != 0) and the cached
8371/// encoding is Recursive, return an empty StringRef.
8372StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8373 if (!ID)
8374 return StringRef(); // We have no key.
8375 auto I = Map.find(ID);
8376 if (I == Map.end())
8377 return StringRef(); // We have no encoding.
8378 Entry &E = I->second;
8379 if (E.State == Recursive && IncompleteCount)
8380 return StringRef(); // We don't use Recursive encodings for member types.
8381
8382 if (E.State == Incomplete) {
8383 // The incomplete type is being used to break out of recursion.
8384 E.State = IncompleteUsed;
8385 ++IncompleteUsedCount;
8386 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008387 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008388}
8389
8390/// The XCore ABI includes a type information section that communicates symbol
8391/// type information to the linker. The linker uses this information to verify
8392/// safety/correctness of things such as array bound and pointers et al.
8393/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8394/// This type information (TypeString) is emitted into meta data for all global
8395/// symbols: definitions, declarations, functions & variables.
8396///
8397/// The TypeString carries type, qualifier, name, size & value details.
8398/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008399/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008400/// The output is tested by test/CodeGen/xcore-stringtype.c.
8401///
8402static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8403 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8404
8405/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8406void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8407 CodeGen::CodeGenModule &CGM) const {
8408 SmallStringEnc Enc;
8409 if (getTypeString(Enc, D, CGM, TSC)) {
8410 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008411 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8412 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008413 llvm::NamedMDNode *MD =
8414 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8415 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8416 }
8417}
8418
Xiuli Pan972bea82016-03-24 03:57:17 +00008419//===----------------------------------------------------------------------===//
8420// SPIR ABI Implementation
8421//===----------------------------------------------------------------------===//
8422
8423namespace {
8424class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8425public:
8426 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8427 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008428 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008429};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008430
Xiuli Pan972bea82016-03-24 03:57:17 +00008431} // End anonymous namespace.
8432
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008433namespace clang {
8434namespace CodeGen {
8435void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8436 DefaultABIInfo SPIRABI(CGM.getTypes());
8437 SPIRABI.computeInfo(FI);
8438}
8439}
8440}
8441
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008442unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8443 return llvm::CallingConv::SPIR_KERNEL;
8444}
8445
Robert Lytton844aeeb2014-05-02 09:33:20 +00008446static bool appendType(SmallStringEnc &Enc, QualType QType,
8447 const CodeGen::CodeGenModule &CGM,
8448 TypeStringCache &TSC);
8449
8450/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008451/// Builds a SmallVector containing the encoded field types in declaration
8452/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008453static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8454 const RecordDecl *RD,
8455 const CodeGen::CodeGenModule &CGM,
8456 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008457 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008458 SmallStringEnc Enc;
8459 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008460 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008461 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008462 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008463 Enc += "b(";
8464 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008465 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008466 Enc += ':';
8467 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008468 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008469 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008470 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008471 Enc += ')';
8472 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008473 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008474 }
8475 return true;
8476}
8477
8478/// Appends structure and union types to Enc and adds encoding to cache.
8479/// Recursively calls appendType (via extractFieldType) for each field.
8480/// Union types have their fields ordered according to the ABI.
8481static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8482 const CodeGen::CodeGenModule &CGM,
8483 TypeStringCache &TSC, const IdentifierInfo *ID) {
8484 // Append the cached TypeString if we have one.
8485 StringRef TypeString = TSC.lookupStr(ID);
8486 if (!TypeString.empty()) {
8487 Enc += TypeString;
8488 return true;
8489 }
8490
8491 // Start to emit an incomplete TypeString.
8492 size_t Start = Enc.size();
8493 Enc += (RT->isUnionType()? 'u' : 's');
8494 Enc += '(';
8495 if (ID)
8496 Enc += ID->getName();
8497 Enc += "){";
8498
8499 // We collect all encoded fields and order as necessary.
8500 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008501 const RecordDecl *RD = RT->getDecl()->getDefinition();
8502 if (RD && !RD->field_empty()) {
8503 // An incomplete TypeString stub is placed in the cache for this RecordType
8504 // so that recursive calls to this RecordType will use it whilst building a
8505 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008506 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008507 std::string StubEnc(Enc.substr(Start).str());
8508 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8509 TSC.addIncomplete(ID, std::move(StubEnc));
8510 if (!extractFieldType(FE, RD, CGM, TSC)) {
8511 (void) TSC.removeIncomplete(ID);
8512 return false;
8513 }
8514 IsRecursive = TSC.removeIncomplete(ID);
8515 // The ABI requires unions to be sorted but not structures.
8516 // See FieldEncoding::operator< for sort algorithm.
8517 if (RT->isUnionType())
8518 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008519 // We can now complete the TypeString.
8520 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008521 for (unsigned I = 0; I != E; ++I) {
8522 if (I)
8523 Enc += ',';
8524 Enc += FE[I].str();
8525 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008526 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008527 Enc += '}';
8528 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8529 return true;
8530}
8531
8532/// Appends enum types to Enc and adds the encoding to the cache.
8533static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8534 TypeStringCache &TSC,
8535 const IdentifierInfo *ID) {
8536 // Append the cached TypeString if we have one.
8537 StringRef TypeString = TSC.lookupStr(ID);
8538 if (!TypeString.empty()) {
8539 Enc += TypeString;
8540 return true;
8541 }
8542
8543 size_t Start = Enc.size();
8544 Enc += "e(";
8545 if (ID)
8546 Enc += ID->getName();
8547 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008548
8549 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008550 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008551 SmallVector<FieldEncoding, 16> FE;
8552 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8553 ++I) {
8554 SmallStringEnc EnumEnc;
8555 EnumEnc += "m(";
8556 EnumEnc += I->getName();
8557 EnumEnc += "){";
8558 I->getInitVal().toString(EnumEnc);
8559 EnumEnc += '}';
8560 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8561 }
8562 std::sort(FE.begin(), FE.end());
8563 unsigned E = FE.size();
8564 for (unsigned I = 0; I != E; ++I) {
8565 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008566 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008567 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008568 }
8569 }
8570 Enc += '}';
8571 TSC.addIfComplete(ID, Enc.substr(Start), false);
8572 return true;
8573}
8574
8575/// Appends type's qualifier to Enc.
8576/// This is done prior to appending the type's encoding.
8577static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8578 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008579 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008580 int Lookup = 0;
8581 if (QT.isConstQualified())
8582 Lookup += 1<<0;
8583 if (QT.isRestrictQualified())
8584 Lookup += 1<<1;
8585 if (QT.isVolatileQualified())
8586 Lookup += 1<<2;
8587 Enc += Table[Lookup];
8588}
8589
8590/// Appends built-in types to Enc.
8591static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8592 const char *EncType;
8593 switch (BT->getKind()) {
8594 case BuiltinType::Void:
8595 EncType = "0";
8596 break;
8597 case BuiltinType::Bool:
8598 EncType = "b";
8599 break;
8600 case BuiltinType::Char_U:
8601 EncType = "uc";
8602 break;
8603 case BuiltinType::UChar:
8604 EncType = "uc";
8605 break;
8606 case BuiltinType::SChar:
8607 EncType = "sc";
8608 break;
8609 case BuiltinType::UShort:
8610 EncType = "us";
8611 break;
8612 case BuiltinType::Short:
8613 EncType = "ss";
8614 break;
8615 case BuiltinType::UInt:
8616 EncType = "ui";
8617 break;
8618 case BuiltinType::Int:
8619 EncType = "si";
8620 break;
8621 case BuiltinType::ULong:
8622 EncType = "ul";
8623 break;
8624 case BuiltinType::Long:
8625 EncType = "sl";
8626 break;
8627 case BuiltinType::ULongLong:
8628 EncType = "ull";
8629 break;
8630 case BuiltinType::LongLong:
8631 EncType = "sll";
8632 break;
8633 case BuiltinType::Float:
8634 EncType = "ft";
8635 break;
8636 case BuiltinType::Double:
8637 EncType = "d";
8638 break;
8639 case BuiltinType::LongDouble:
8640 EncType = "ld";
8641 break;
8642 default:
8643 return false;
8644 }
8645 Enc += EncType;
8646 return true;
8647}
8648
8649/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8650static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8651 const CodeGen::CodeGenModule &CGM,
8652 TypeStringCache &TSC) {
8653 Enc += "p(";
8654 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8655 return false;
8656 Enc += ')';
8657 return true;
8658}
8659
8660/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008661static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8662 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008663 const CodeGen::CodeGenModule &CGM,
8664 TypeStringCache &TSC, StringRef NoSizeEnc) {
8665 if (AT->getSizeModifier() != ArrayType::Normal)
8666 return false;
8667 Enc += "a(";
8668 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8669 CAT->getSize().toStringUnsigned(Enc);
8670 else
8671 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8672 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008673 // The Qualifiers should be attached to the type rather than the array.
8674 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008675 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8676 return false;
8677 Enc += ')';
8678 return true;
8679}
8680
8681/// Appends a function encoding to Enc, calling appendType for the return type
8682/// and the arguments.
8683static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8684 const CodeGen::CodeGenModule &CGM,
8685 TypeStringCache &TSC) {
8686 Enc += "f{";
8687 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8688 return false;
8689 Enc += "}(";
8690 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8691 // N.B. we are only interested in the adjusted param types.
8692 auto I = FPT->param_type_begin();
8693 auto E = FPT->param_type_end();
8694 if (I != E) {
8695 do {
8696 if (!appendType(Enc, *I, CGM, TSC))
8697 return false;
8698 ++I;
8699 if (I != E)
8700 Enc += ',';
8701 } while (I != E);
8702 if (FPT->isVariadic())
8703 Enc += ",va";
8704 } else {
8705 if (FPT->isVariadic())
8706 Enc += "va";
8707 else
8708 Enc += '0';
8709 }
8710 }
8711 Enc += ')';
8712 return true;
8713}
8714
8715/// Handles the type's qualifier before dispatching a call to handle specific
8716/// type encodings.
8717static bool appendType(SmallStringEnc &Enc, QualType QType,
8718 const CodeGen::CodeGenModule &CGM,
8719 TypeStringCache &TSC) {
8720
8721 QualType QT = QType.getCanonicalType();
8722
Robert Lytton6adb20f2014-06-05 09:06:21 +00008723 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8724 // The Qualifiers should be attached to the type rather than the array.
8725 // Thus we don't call appendQualifier() here.
8726 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8727
Robert Lytton844aeeb2014-05-02 09:33:20 +00008728 appendQualifier(Enc, QT);
8729
8730 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8731 return appendBuiltinType(Enc, BT);
8732
Robert Lytton844aeeb2014-05-02 09:33:20 +00008733 if (const PointerType *PT = QT->getAs<PointerType>())
8734 return appendPointerType(Enc, PT, CGM, TSC);
8735
8736 if (const EnumType *ET = QT->getAs<EnumType>())
8737 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8738
8739 if (const RecordType *RT = QT->getAsStructureType())
8740 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8741
8742 if (const RecordType *RT = QT->getAsUnionType())
8743 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8744
8745 if (const FunctionType *FT = QT->getAs<FunctionType>())
8746 return appendFunctionType(Enc, FT, CGM, TSC);
8747
8748 return false;
8749}
8750
8751static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8752 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8753 if (!D)
8754 return false;
8755
8756 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8757 if (FD->getLanguageLinkage() != CLanguageLinkage)
8758 return false;
8759 return appendType(Enc, FD->getType(), CGM, TSC);
8760 }
8761
8762 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8763 if (VD->getLanguageLinkage() != CLanguageLinkage)
8764 return false;
8765 QualType QT = VD->getType().getCanonicalType();
8766 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8767 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008768 // The Qualifiers should be attached to the type rather than the array.
8769 // Thus we don't call appendQualifier() here.
8770 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008771 }
8772 return appendType(Enc, QT, CGM, TSC);
8773 }
8774 return false;
8775}
8776
8777
Robert Lytton0e076492013-08-13 09:43:10 +00008778//===----------------------------------------------------------------------===//
8779// Driver code
8780//===----------------------------------------------------------------------===//
8781
Rafael Espindola9f834732014-09-19 01:54:22 +00008782bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008783 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008784}
8785
Chris Lattner2b037972010-07-29 02:01:43 +00008786const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008787 if (TheTargetCodeGenInfo)
8788 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008789
Reid Kleckner9305fd12016-04-13 23:37:17 +00008790 // Helper to set the unique_ptr while still keeping the return value.
8791 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8792 this->TheTargetCodeGenInfo.reset(P);
8793 return *P;
8794 };
8795
John McCallc8e01702013-04-16 22:48:15 +00008796 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008797 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008798 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008799 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008800
Derek Schuff09338a22012-09-06 17:37:28 +00008801 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008802 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008803 case llvm::Triple::mips:
8804 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008805 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008806 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8807 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008808
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008809 case llvm::Triple::mips64:
8810 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008811 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008812
Dylan McKaye8232d72017-02-08 05:09:26 +00008813 case llvm::Triple::avr:
8814 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8815
Tim Northover25e8a672014-05-24 12:51:25 +00008816 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008817 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008818 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008819 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008820 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00008821 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00008822 return SetCGInfo(
8823 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00008824
Reid Kleckner9305fd12016-04-13 23:37:17 +00008825 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008826 }
8827
Dan Gohmanc2853072015-09-03 22:51:53 +00008828 case llvm::Triple::wasm32:
8829 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008830 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008831
Daniel Dunbard59655c2009-09-12 00:59:49 +00008832 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008833 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008834 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008835 case llvm::Triple::thumbeb: {
8836 if (Triple.getOS() == llvm::Triple::Win32) {
8837 return SetCGInfo(
8838 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008839 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008840
Reid Kleckner9305fd12016-04-13 23:37:17 +00008841 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8842 StringRef ABIStr = getTarget().getABI();
8843 if (ABIStr == "apcs-gnu")
8844 Kind = ARMABIInfo::APCS;
8845 else if (ABIStr == "aapcs16")
8846 Kind = ARMABIInfo::AAPCS16_VFP;
8847 else if (CodeGenOpts.FloatABI == "hard" ||
8848 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008849 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008850 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008851 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008852 Kind = ARMABIInfo::AAPCS_VFP;
8853
8854 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8855 }
8856
John McCallea8d8bb2010-03-11 00:10:12 +00008857 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008858 return SetCGInfo(
8859 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008860 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008861 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008862 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008863 if (getTarget().getABI() == "elfv2")
8864 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008865 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008866 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008867
Hal Finkel415c2a32016-10-02 02:10:45 +00008868 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8869 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008870 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008871 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008872 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008873 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008874 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008875 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008876 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008877 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008878 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008879
Hal Finkel415c2a32016-10-02 02:10:45 +00008880 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8881 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008882 }
John McCallea8d8bb2010-03-11 00:10:12 +00008883
Peter Collingbournec947aae2012-05-20 23:28:41 +00008884 case llvm::Triple::nvptx:
8885 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008886 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008887
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008888 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008889 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008890
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008891 case llvm::Triple::systemz: {
8892 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008893 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008894 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008895
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008896 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008897 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008898 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008899
Eli Friedman33465822011-07-08 23:31:17 +00008900 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008901 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008902 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008903 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008904 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008905
John McCall1fe2a8c2013-06-18 02:46:29 +00008906 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008907 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8908 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8909 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008910 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008911 return SetCGInfo(new X86_32TargetCodeGenInfo(
8912 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8913 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8914 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008915 }
Eli Friedman33465822011-07-08 23:31:17 +00008916 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008917
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008918 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008919 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008920 X86AVXABILevel AVXLevel =
8921 (ABI == "avx512"
8922 ? X86AVXABILevel::AVX512
8923 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008924
Chris Lattner04dc9572010-08-31 16:44:54 +00008925 switch (Triple.getOS()) {
8926 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008927 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008928 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008929 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008930 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008931 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008932 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008933 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008934 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008935 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008936 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008937 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008938 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008939 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008940 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008941 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008942 case llvm::Triple::sparc:
8943 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008944 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008945 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008946 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008947 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008948 case llvm::Triple::spir:
8949 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008950 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008951 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008952}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00008953
8954/// Create an OpenCL kernel for an enqueued block.
8955///
8956/// The kernel has the same function type as the block invoke function. Its
8957/// name is the name of the block invoke function postfixed with "_kernel".
8958/// It simply calls the block invoke function then returns.
8959llvm::Function *
8960TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
8961 llvm::Function *Invoke,
8962 llvm::Value *BlockLiteral) const {
8963 auto *InvokeFT = Invoke->getFunctionType();
8964 llvm::SmallVector<llvm::Type *, 2> ArgTys;
8965 for (auto &P : InvokeFT->params())
8966 ArgTys.push_back(P);
8967 auto &C = CGF.getLLVMContext();
8968 std::string Name = Invoke->getName().str() + "_kernel";
8969 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
8970 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
8971 &CGF.CGM.getModule());
8972 auto IP = CGF.Builder.saveIP();
8973 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
8974 auto &Builder = CGF.Builder;
8975 Builder.SetInsertPoint(BB);
8976 llvm::SmallVector<llvm::Value *, 2> Args;
8977 for (auto &A : F->args())
8978 Args.push_back(&A);
8979 Builder.CreateCall(Invoke, Args);
8980 Builder.CreateRetVoid();
8981 Builder.restoreIP(IP);
8982 return F;
8983}
8984
8985/// Create an OpenCL kernel for an enqueued block.
8986///
8987/// The type of the first argument (the block literal) is the struct type
8988/// of the block literal instead of a pointer type. The first argument
8989/// (block literal) is passed directly by value to the kernel. The kernel
8990/// allocates the same type of struct on stack and stores the block literal
8991/// to it and passes its pointer to the block invoke function. The kernel
8992/// has "enqueued-block" function attribute and kernel argument metadata.
8993llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
8994 CodeGenFunction &CGF, llvm::Function *Invoke,
8995 llvm::Value *BlockLiteral) const {
8996 auto &Builder = CGF.Builder;
8997 auto &C = CGF.getLLVMContext();
8998
8999 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
9000 auto *InvokeFT = Invoke->getFunctionType();
9001 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9002 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
9003 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
9004 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
9005 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
9006 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
9007 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
9008
9009 ArgTys.push_back(BlockTy);
9010 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9011 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
9012 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9013 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9014 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9015 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
9016 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
9017 ArgTys.push_back(InvokeFT->getParamType(I));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009018 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
9019 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
9020 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9021 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
9022 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9023 ArgNames.push_back(
Yaxun Liu98f0c432017-10-14 12:51:52 +00009024 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009025 }
9026 std::string Name = Invoke->getName().str() + "_kernel";
9027 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9028 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9029 &CGF.CGM.getModule());
9030 F->addFnAttr("enqueued-block");
9031 auto IP = CGF.Builder.saveIP();
9032 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9033 Builder.SetInsertPoint(BB);
9034 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9035 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9036 BlockPtr->setAlignment(BlockAlign);
9037 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9038 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9039 llvm::SmallVector<llvm::Value *, 2> Args;
9040 Args.push_back(Cast);
9041 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9042 Args.push_back(I);
9043 Builder.CreateCall(Invoke, Args);
9044 Builder.CreateRetVoid();
9045 Builder.restoreIP(IP);
9046
9047 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9048 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9049 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9050 F->setMetadata("kernel_arg_base_type",
9051 llvm::MDNode::get(C, ArgBaseTypeNames));
9052 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9053 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9054 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
9055
9056 return F;
9057}