blob: 8641d872724fc3457d8fb00d9304792a5fc8d034 [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
Yaron Kerencdae9412016-01-29 19:38:18 +0000204LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000205 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000206 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000207 switch (TheKind) {
208 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000209 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000210 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000211 Ty->print(OS);
212 else
213 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000214 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000215 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000216 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000217 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000218 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000219 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000220 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000221 case InAlloca:
222 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
223 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000224 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000225 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000226 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000227 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000228 break;
229 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000230 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000231 break;
John McCallf26e73d2016-03-11 04:30:43 +0000232 case CoerceAndExpand:
233 OS << "CoerceAndExpand Type=";
234 getCoerceAndExpandType()->print(OS);
235 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000236 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000237 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000238}
239
Petar Jovanovic402257b2015-12-04 00:26:47 +0000240// Dynamically round a pointer up to a multiple of the given alignment.
241static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
242 llvm::Value *Ptr,
243 CharUnits Align) {
244 llvm::Value *PtrAsInt = Ptr;
245 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
246 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
247 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
248 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
249 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
250 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
251 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
252 Ptr->getType(),
253 Ptr->getName() + ".aligned");
254 return PtrAsInt;
255}
256
John McCall7f416cc2015-09-08 08:05:57 +0000257/// Emit va_arg for a platform using the common void* representation,
258/// where arguments are simply emitted in an array of slots on the stack.
259///
260/// This version implements the core direct-value passing rules.
261///
262/// \param SlotSize - The size and alignment of a stack slot.
263/// Each argument will be allocated to a multiple of this number of
264/// slots, and all the slots will be aligned to this value.
265/// \param AllowHigherAlign - The slot alignment is not a cap;
266/// an argument type with an alignment greater than the slot size
267/// will be emitted on a higher-alignment address, potentially
268/// leaving one or more empty slots behind as padding. If this
269/// is false, the returned address might be less-aligned than
270/// DirectAlign.
271static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
272 Address VAListAddr,
273 llvm::Type *DirectTy,
274 CharUnits DirectSize,
275 CharUnits DirectAlign,
276 CharUnits SlotSize,
277 bool AllowHigherAlign) {
278 // Cast the element type to i8* if necessary. Some platforms define
279 // va_list as a struct containing an i8* instead of just an i8*.
280 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
281 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
282
283 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
284
285 // If the CC aligns values higher than the slot size, do so if needed.
286 Address Addr = Address::invalid();
287 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000288 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
289 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000290 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000291 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000292 }
293
294 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000295 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000296 llvm::Value *NextPtr =
297 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
298 "argp.next");
299 CGF.Builder.CreateStore(NextPtr, VAListAddr);
300
301 // If the argument is smaller than a slot, and this is a big-endian
302 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000303 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
304 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000305 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
306 }
307
308 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
309 return Addr;
310}
311
312/// Emit va_arg for a platform using the common void* representation,
313/// where arguments are simply emitted in an array of slots on the stack.
314///
315/// \param IsIndirect - Values of this type are passed indirectly.
316/// \param ValueInfo - The size and alignment of this type, generally
317/// computed with getContext().getTypeInfoInChars(ValueTy).
318/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
319/// Each argument will be allocated to a multiple of this number of
320/// slots, and all the slots will be aligned to this value.
321/// \param AllowHigherAlign - The slot alignment is not a cap;
322/// an argument type with an alignment greater than the slot size
323/// will be emitted on a higher-alignment address, potentially
324/// leaving one or more empty slots behind as padding.
325static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
326 QualType ValueTy, bool IsIndirect,
327 std::pair<CharUnits, CharUnits> ValueInfo,
328 CharUnits SlotSizeAndAlign,
329 bool AllowHigherAlign) {
330 // The size and alignment of the value that was passed directly.
331 CharUnits DirectSize, DirectAlign;
332 if (IsIndirect) {
333 DirectSize = CGF.getPointerSize();
334 DirectAlign = CGF.getPointerAlign();
335 } else {
336 DirectSize = ValueInfo.first;
337 DirectAlign = ValueInfo.second;
338 }
339
340 // Cast the address we've calculated to the right type.
341 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
342 if (IsIndirect)
343 DirectTy = DirectTy->getPointerTo(0);
344
345 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
346 DirectSize, DirectAlign,
347 SlotSizeAndAlign,
348 AllowHigherAlign);
349
350 if (IsIndirect) {
351 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
352 }
353
354 return Addr;
355
356}
357
358static Address emitMergePHI(CodeGenFunction &CGF,
359 Address Addr1, llvm::BasicBlock *Block1,
360 Address Addr2, llvm::BasicBlock *Block2,
361 const llvm::Twine &Name = "") {
362 assert(Addr1.getType() == Addr2.getType());
363 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
364 PHI->addIncoming(Addr1.getPointer(), Block1);
365 PHI->addIncoming(Addr2.getPointer(), Block2);
366 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
367 return Address(PHI, Align);
368}
369
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000370TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
371
John McCall3480ef22011-08-30 01:42:09 +0000372// If someone can figure out a general rule for this, that would be great.
373// It's probably just doomed to be platform-dependent, though.
374unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
375 // Verified for:
376 // x86-64 FreeBSD, Linux, Darwin
377 // x86-32 FreeBSD, Linux, Darwin
378 // PowerPC Linux, Darwin
379 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000380 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000381 return 32;
382}
383
John McCalla729c622012-02-17 03:33:10 +0000384bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
385 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000386 // The following conventions are known to require this to be false:
387 // x86_stdcall
388 // MIPS
389 // For everything else, we just prefer false unless we opt out.
390 return false;
391}
392
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000393void
394TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
395 llvm::SmallString<24> &Opt) const {
396 // This assumes the user is passing a library name like "rt" instead of a
397 // filename like "librt.a/so", and that they don't care whether it's static or
398 // dynamic.
399 Opt = "-l";
400 Opt += Lib;
401}
402
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000403unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000404 // OpenCL kernels are called via an explicit runtime API with arguments
405 // set with clSetKernelArg(), not as normal sub-functions.
406 // Return SPIR_KERNEL by default as the kernel calling convention to
407 // ensure the fingerprint is fixed such way that each OpenCL argument
408 // gets one matching argument in the produced kernel function argument
409 // list to enable feasible implementation of clSetKernelArg() with
410 // aggregates etc. In case we would use the default C calling conv here,
411 // clSetKernelArg() might break depending on the target-specific
412 // conventions; different targets might split structs passed as values
413 // to multiple function arguments etc.
414 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000415}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000416
Yaxun Liu402804b2016-12-15 08:09:08 +0000417llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
418 llvm::PointerType *T, QualType QT) const {
419 return llvm::ConstantPointerNull::get(T);
420}
421
Alexander Richardson6d989432017-10-15 18:48:14 +0000422LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
423 const VarDecl *D) const {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000424 assert(!CGM.getLangOpts().OpenCL &&
425 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
426 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +0000427 return D ? D->getType().getAddressSpace() : LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000428}
429
Yaxun Liu402804b2016-12-15 08:09:08 +0000430llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Alexander Richardson6d989432017-10-15 18:48:14 +0000431 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
432 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000433 // Since target may map different address spaces in AST to the same address
434 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000435 if (auto *C = dyn_cast<llvm::Constant>(Src))
436 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000437 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000438}
439
Yaxun Liucbf647c2017-07-08 13:24:52 +0000440llvm::Constant *
441TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
Alexander Richardson6d989432017-10-15 18:48:14 +0000442 LangAS SrcAddr, LangAS DestAddr,
Yaxun Liucbf647c2017-07-08 13:24:52 +0000443 llvm::Type *DestTy) const {
444 // Since target may map different address spaces in AST to the same address
445 // space, an address space conversion may end up as a bitcast.
446 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
447}
448
Yaxun Liu39195062017-08-04 18:16:31 +0000449llvm::SyncScope::ID
450TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
451 return C.getOrInsertSyncScopeID(""); /* default sync scope */
452}
453
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000454static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000455
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000456/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000457/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000458static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
459 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000460 if (FD->isUnnamedBitfield())
461 return true;
462
463 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000464
Eli Friedman0b3f2012011-11-18 03:47:20 +0000465 // Constant arrays of empty records count as empty, strip them off.
466 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000467 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000468 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
469 if (AT->getSize() == 0)
470 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000471 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000472 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000473
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000474 const RecordType *RT = FT->getAs<RecordType>();
475 if (!RT)
476 return false;
477
478 // C++ record fields are never empty, at least in the Itanium ABI.
479 //
480 // FIXME: We should use a predicate for whether this behavior is true in the
481 // current ABI.
482 if (isa<CXXRecordDecl>(RT->getDecl()))
483 return false;
484
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000485 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000486}
487
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000488/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000489/// fields. Note that a structure with a flexible array member is not
490/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000491static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000492 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000493 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000494 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000495 const RecordDecl *RD = RT->getDecl();
496 if (RD->hasFlexibleArrayMember())
497 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000498
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000499 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000500 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000501 for (const auto &I : CXXRD->bases())
502 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000503 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000504
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000505 for (const auto *I : RD->fields())
506 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000507 return false;
508 return true;
509}
510
511/// isSingleElementStruct - Determine if a structure is a "single
512/// element struct", i.e. it has exactly one non-empty field or
513/// exactly one field which is itself a single element
514/// struct. Structures with flexible array members are never
515/// considered single element structs.
516///
517/// \return The field declaration for the single non-empty field, if
518/// it exists.
519static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000520 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000521 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000522 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000523
524 const RecordDecl *RD = RT->getDecl();
525 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000526 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000527
Craig Topper8a13c412014-05-21 05:09:00 +0000528 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000529
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000530 // If this is a C++ record, check the bases first.
531 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000532 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000533 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000534 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000535 continue;
536
537 // If we already found an element then this isn't a single-element struct.
538 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000539 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000540
541 // If this is non-empty and not a single element struct, the composite
542 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000543 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000544 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000545 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000546 }
547 }
548
549 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000550 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000551 QualType FT = FD->getType();
552
553 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000554 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000555 continue;
556
557 // If we already found an element then this isn't a single-element
558 // struct.
559 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000560 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000561
562 // Treat single element arrays as the element.
563 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
564 if (AT->getSize().getZExtValue() != 1)
565 break;
566 FT = AT->getElementType();
567 }
568
John McCalla1dee5302010-08-22 10:59:02 +0000569 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000570 Found = FT.getTypePtr();
571 } else {
572 Found = isSingleElementStruct(FT, Context);
573 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000574 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000575 }
576 }
577
Eli Friedmanee945342011-11-18 01:25:50 +0000578 // We don't consider a struct a single-element struct if it has
579 // padding beyond the element type.
580 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000581 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000582
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000583 return Found;
584}
585
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000586namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000587Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
588 const ABIArgInfo &AI) {
589 // This default implementation defers to the llvm backend's va_arg
590 // instruction. It can handle only passing arguments directly
591 // (typically only handled in the backend for primitive types), or
592 // aggregates passed indirectly by pointer (NOTE: if the "byval"
593 // flag has ABI impact in the callee, this implementation cannot
594 // work.)
595
596 // Only a few cases are covered here at the moment -- those needed
597 // by the default abi.
598 llvm::Value *Val;
599
600 if (AI.isIndirect()) {
601 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000602 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000603 assert(
604 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000605 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000606
607 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
608 CharUnits TyAlignForABI = TyInfo.second;
609
610 llvm::Type *BaseTy =
611 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
612 llvm::Value *Addr =
613 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
614 return Address(Addr, TyAlignForABI);
615 } else {
616 assert((AI.isDirect() || AI.isExtend()) &&
617 "Unexpected ArgInfo Kind in generic VAArg emitter!");
618
619 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000620 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000621 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000622 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000623 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000624 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000625 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000626 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000627
628 Address Temp = CGF.CreateMemTemp(Ty, "varet");
629 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
630 CGF.Builder.CreateStore(Val, Temp);
631 return Temp;
632 }
633}
634
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000635/// DefaultABIInfo - The default implementation for ABI specific
636/// details. This implementation provides information which results in
637/// self-consistent and sensible LLVM IR generation, but does not
638/// conform to any particular ABI.
639class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000640public:
641 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000642
Chris Lattner458b2aa2010-07-29 02:16:43 +0000643 ABIArgInfo classifyReturnType(QualType RetTy) const;
644 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000645
Craig Topper4f12f102014-03-12 06:41:41 +0000646 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000647 if (!getCXXABI().classifyReturnType(FI))
648 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000649 for (auto &I : FI.arguments())
650 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000651 }
652
John McCall7f416cc2015-09-08 08:05:57 +0000653 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000654 QualType Ty) const override {
655 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
656 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000657};
658
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000659class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
660public:
Chris Lattner2b037972010-07-29 02:01:43 +0000661 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
662 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000663};
664
Chris Lattner458b2aa2010-07-29 02:16:43 +0000665ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000666 Ty = useFirstFieldIfTransparentUnion(Ty);
667
668 if (isAggregateTypeForABI(Ty)) {
669 // Records with non-trivial destructors/copy-constructors should not be
670 // passed by value.
671 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000672 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000673
John McCall7f416cc2015-09-08 08:05:57 +0000674 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000675 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000676
Chris Lattner9723d6c2010-03-11 18:19:55 +0000677 // Treat an enum type as its underlying type.
678 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
679 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000680
Alex Bradburye41a5e22018-01-12 20:08:16 +0000681 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
682 : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000683}
684
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000685ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
686 if (RetTy->isVoidType())
687 return ABIArgInfo::getIgnore();
688
689 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000690 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000691
692 // Treat an enum type as its underlying type.
693 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
694 RetTy = EnumTy->getDecl()->getIntegerType();
695
Alex Bradburye41a5e22018-01-12 20:08:16 +0000696 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
697 : ABIArgInfo::getDirect());
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000698}
699
Derek Schuff09338a22012-09-06 17:37:28 +0000700//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000701// WebAssembly ABI Implementation
702//
703// This is a very simple ABI that relies a lot on DefaultABIInfo.
704//===----------------------------------------------------------------------===//
705
706class WebAssemblyABIInfo final : public DefaultABIInfo {
707public:
708 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
709 : DefaultABIInfo(CGT) {}
710
711private:
712 ABIArgInfo classifyReturnType(QualType RetTy) const;
713 ABIArgInfo classifyArgumentType(QualType Ty) const;
714
715 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000716 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000717 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000718 void computeInfo(CGFunctionInfo &FI) const override {
719 if (!getCXXABI().classifyReturnType(FI))
720 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
721 for (auto &Arg : FI.arguments())
722 Arg.info = classifyArgumentType(Arg.type);
723 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000724
725 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
726 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000727};
728
729class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
730public:
731 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
732 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
733};
734
735/// \brief Classify argument of given type \p Ty.
736ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
737 Ty = useFirstFieldIfTransparentUnion(Ty);
738
739 if (isAggregateTypeForABI(Ty)) {
740 // Records with non-trivial destructors/copy-constructors should not be
741 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000742 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000743 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000744 // Ignore empty structs/unions.
745 if (isEmptyRecord(getContext(), Ty, true))
746 return ABIArgInfo::getIgnore();
747 // Lower single-element structs to just pass a regular value. TODO: We
748 // could do reasonable-size multiple-element structs too, using getExpand(),
749 // though watch out for things like bitfields.
750 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
751 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000752 }
753
754 // Otherwise just do the default thing.
755 return DefaultABIInfo::classifyArgumentType(Ty);
756}
757
758ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
759 if (isAggregateTypeForABI(RetTy)) {
760 // Records with non-trivial destructors/copy-constructors should not be
761 // returned by value.
762 if (!getRecordArgABI(RetTy, getCXXABI())) {
763 // Ignore empty structs/unions.
764 if (isEmptyRecord(getContext(), RetTy, true))
765 return ABIArgInfo::getIgnore();
766 // Lower single-element structs to just return a regular value. TODO: We
767 // could do reasonable-size multiple-element structs too, using
768 // ABIArgInfo::getDirect().
769 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
770 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
771 }
772 }
773
774 // Otherwise just do the default thing.
775 return DefaultABIInfo::classifyReturnType(RetTy);
776}
777
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000778Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
779 QualType Ty) const {
780 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
781 getContext().getTypeInfoInChars(Ty),
782 CharUnits::fromQuantity(4),
783 /*AllowHigherAlign=*/ true);
784}
785
Dan Gohmanc2853072015-09-03 22:51:53 +0000786//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000787// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000788//
789// This is a simplified version of the x86_32 ABI. Arguments and return values
790// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000791//===----------------------------------------------------------------------===//
792
793class PNaClABIInfo : public ABIInfo {
794 public:
795 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
796
797 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000798 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000799
Craig Topper4f12f102014-03-12 06:41:41 +0000800 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000801 Address EmitVAArg(CodeGenFunction &CGF,
802 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000803};
804
805class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
806 public:
807 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
808 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
809};
810
811void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000812 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000813 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
814
Reid Kleckner40ca9132014-05-13 22:05:45 +0000815 for (auto &I : FI.arguments())
816 I.info = classifyArgumentType(I.type);
817}
Derek Schuff09338a22012-09-06 17:37:28 +0000818
John McCall7f416cc2015-09-08 08:05:57 +0000819Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
820 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000821 // The PNaCL ABI is a bit odd, in that varargs don't use normal
822 // function classification. Structs get passed directly for varargs
823 // functions, through a rewriting transform in
824 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
825 // this target to actually support a va_arg instructions with an
826 // aggregate type, unlike other targets.
827 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000828}
829
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000830/// \brief Classify argument of given type \p Ty.
831ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000832 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000833 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000834 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
835 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000836 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
837 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000838 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000839 } else if (Ty->isFloatingType()) {
840 // Floating-point types don't go inreg.
841 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000842 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000843
Alex Bradburye41a5e22018-01-12 20:08:16 +0000844 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
845 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000846}
847
848ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
849 if (RetTy->isVoidType())
850 return ABIArgInfo::getIgnore();
851
Eli Benderskye20dad62013-04-04 22:49:35 +0000852 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000853 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000854 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000855
856 // Treat an enum type as its underlying type.
857 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
858 RetTy = EnumTy->getDecl()->getIntegerType();
859
Alex Bradburye41a5e22018-01-12 20:08:16 +0000860 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
861 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000862}
863
Chad Rosier651c1832013-03-25 21:00:27 +0000864/// IsX86_MMXType - Return true if this is an MMX type.
865bool IsX86_MMXType(llvm::Type *IRType) {
866 // 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 +0000867 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
868 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
869 IRType->getScalarSizeInBits() != 64;
870}
871
Jay Foad7c57be32011-07-11 09:56:20 +0000872static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000873 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000874 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000875 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
876 .Cases("y", "&y", "^Ym", true)
877 .Default(false);
878 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000879 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
880 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000881 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000882 }
883
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000884 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000885 }
886
887 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000888 return Ty;
889}
890
Reid Kleckner80944df2014-10-31 22:00:51 +0000891/// Returns true if this type can be passed in SSE registers with the
892/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
893static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
894 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000895 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
896 if (BT->getKind() == BuiltinType::LongDouble) {
897 if (&Context.getTargetInfo().getLongDoubleFormat() ==
898 &llvm::APFloat::x87DoubleExtended())
899 return false;
900 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000901 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000902 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000903 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
904 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
905 // registers specially.
906 unsigned VecSize = Context.getTypeSize(VT);
907 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
908 return true;
909 }
910 return false;
911}
912
913/// Returns true if this aggregate is small enough to be passed in SSE registers
914/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
915static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
916 return NumMembers <= 4;
917}
918
Erich Keane521ed962017-01-05 00:20:51 +0000919/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
920static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
921 auto AI = ABIArgInfo::getDirect(T);
922 AI.setInReg(true);
923 AI.setCanBeFlattened(false);
924 return AI;
925}
926
Chris Lattner0cf24192010-06-28 20:05:43 +0000927//===----------------------------------------------------------------------===//
928// X86-32 ABI Implementation
929//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000930
Reid Kleckner661f35b2014-01-18 01:12:41 +0000931/// \brief Similar to llvm::CCState, but for Clang.
932struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000933 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000934
935 unsigned CC;
936 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000937 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000938};
939
Erich Keane521ed962017-01-05 00:20:51 +0000940enum {
941 // Vectorcall only allows the first 6 parameters to be passed in registers.
942 VectorcallMaxParamNumAsReg = 6
943};
944
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000945/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000946class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000947 enum Class {
948 Integer,
949 Float
950 };
951
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000952 static const unsigned MinABIStackAlignInBytes = 4;
953
David Chisnallde3a0692009-08-17 23:08:21 +0000954 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000955 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000956 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000957 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000958 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000959 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000960
961 static bool isRegisterSize(unsigned Size) {
962 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
963 }
964
Reid Kleckner80944df2014-10-31 22:00:51 +0000965 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
966 // FIXME: Assumes vectorcall is in use.
967 return isX86VectorTypeForVectorCall(getContext(), Ty);
968 }
969
970 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
971 uint64_t NumMembers) const override {
972 // FIXME: Assumes vectorcall is in use.
973 return isX86VectorCallAggregateSmallEnough(NumMembers);
974 }
975
Reid Kleckner40ca9132014-05-13 22:05:45 +0000976 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000977
Daniel Dunbar557893d2010-04-21 19:10:51 +0000978 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
979 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000980 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
981
John McCall7f416cc2015-09-08 08:05:57 +0000982 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000983
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000984 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000985 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000986
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000987 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000988 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000989 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +0000990
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000991 /// \brief Updates the number of available free registers, returns
992 /// true if any registers were allocated.
993 bool updateFreeRegs(QualType Ty, CCState &State) const;
994
995 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
996 bool &NeedsPadding) const;
997 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000998
Reid Kleckner04046052016-05-02 17:41:07 +0000999 bool canExpandIndirectArgument(QualType Ty) const;
1000
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001001 /// \brief Rewrite the function info so that all memory arguments use
1002 /// inalloca.
1003 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1004
1005 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001006 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001007 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001008 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1009 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001010
Rafael Espindola75419dc2012-07-23 23:30:29 +00001011public:
1012
Craig Topper4f12f102014-03-12 06:41:41 +00001013 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001014 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1015 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001016
Michael Kupersteindc745202015-10-19 07:52:25 +00001017 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1018 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001019 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001020 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001021 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1022 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001023 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001024 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001025 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001026
John McCall56331e22018-01-07 06:28:49 +00001027 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00001028 bool asReturnValue) const override {
1029 // LLVM's x86-32 lowering currently only assigns up to three
1030 // integer registers and three fp registers. Oddly, it'll use up to
1031 // four vector registers for vectors, but those can overlap with the
1032 // scalar registers.
1033 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1034 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001035
1036 bool isSwiftErrorInRegister() const override {
1037 // x86-32 lowering does not support passing swifterror in a register.
1038 return false;
1039 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001040};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001041
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001042class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1043public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001044 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1045 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001046 unsigned NumRegisterParameters, bool SoftFloatABI)
1047 : TargetCodeGenInfo(new X86_32ABIInfo(
1048 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1049 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001050
John McCall1fe2a8c2013-06-18 02:46:29 +00001051 static bool isStructReturnInRegABI(
1052 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1053
Eric Christopher162c91c2015-06-05 22:03:00 +00001054 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001055 CodeGen::CodeGenModule &CGM,
1056 ForDefinition_t IsForDefinition) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001057
Craig Topper4f12f102014-03-12 06:41:41 +00001058 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001059 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001060 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001061 return 4;
1062 }
1063
1064 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001065 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001066
Jay Foad7c57be32011-07-11 09:56:20 +00001067 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001068 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001069 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001070 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1071 }
1072
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001073 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1074 std::string &Constraints,
1075 std::vector<llvm::Type *> &ResultRegTypes,
1076 std::vector<llvm::Type *> &ResultTruncRegTypes,
1077 std::vector<LValue> &ResultRegDests,
1078 std::string &AsmString,
1079 unsigned NumOutputs) const override;
1080
Craig Topper4f12f102014-03-12 06:41:41 +00001081 llvm::Constant *
1082 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001083 unsigned Sig = (0xeb << 0) | // jmp rel8
1084 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001085 ('v' << 16) |
1086 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001087 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1088 }
John McCall01391782016-02-05 21:37:38 +00001089
1090 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1091 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001092 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001093 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001094};
1095
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001096}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001097
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001098/// Rewrite input constraint references after adding some output constraints.
1099/// In the case where there is one output and one input and we add one output,
1100/// we need to replace all operand references greater than or equal to 1:
1101/// mov $0, $1
1102/// mov eax, $1
1103/// The result will be:
1104/// mov $0, $2
1105/// mov eax, $2
1106static void rewriteInputConstraintReferences(unsigned FirstIn,
1107 unsigned NumNewOuts,
1108 std::string &AsmString) {
1109 std::string Buf;
1110 llvm::raw_string_ostream OS(Buf);
1111 size_t Pos = 0;
1112 while (Pos < AsmString.size()) {
1113 size_t DollarStart = AsmString.find('$', Pos);
1114 if (DollarStart == std::string::npos)
1115 DollarStart = AsmString.size();
1116 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1117 if (DollarEnd == std::string::npos)
1118 DollarEnd = AsmString.size();
1119 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1120 Pos = DollarEnd;
1121 size_t NumDollars = DollarEnd - DollarStart;
1122 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1123 // We have an operand reference.
1124 size_t DigitStart = Pos;
1125 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1126 if (DigitEnd == std::string::npos)
1127 DigitEnd = AsmString.size();
1128 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1129 unsigned OperandIndex;
1130 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1131 if (OperandIndex >= FirstIn)
1132 OperandIndex += NumNewOuts;
1133 OS << OperandIndex;
1134 } else {
1135 OS << OperandStr;
1136 }
1137 Pos = DigitEnd;
1138 }
1139 }
1140 AsmString = std::move(OS.str());
1141}
1142
1143/// Add output constraints for EAX:EDX because they are return registers.
1144void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1145 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1146 std::vector<llvm::Type *> &ResultRegTypes,
1147 std::vector<llvm::Type *> &ResultTruncRegTypes,
1148 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1149 unsigned NumOutputs) const {
1150 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1151
1152 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1153 // larger.
1154 if (!Constraints.empty())
1155 Constraints += ',';
1156 if (RetWidth <= 32) {
1157 Constraints += "={eax}";
1158 ResultRegTypes.push_back(CGF.Int32Ty);
1159 } else {
1160 // Use the 'A' constraint for EAX:EDX.
1161 Constraints += "=A";
1162 ResultRegTypes.push_back(CGF.Int64Ty);
1163 }
1164
1165 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1166 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1167 ResultTruncRegTypes.push_back(CoerceTy);
1168
1169 // Coerce the integer by bitcasting the return slot pointer.
1170 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1171 CoerceTy->getPointerTo()));
1172 ResultRegDests.push_back(ReturnSlot);
1173
1174 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1175}
1176
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001177/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001178/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001179bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1180 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001181 uint64_t Size = Context.getTypeSize(Ty);
1182
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001183 // For i386, type must be register sized.
1184 // For the MCU ABI, it only needs to be <= 8-byte
1185 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1186 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001187
1188 if (Ty->isVectorType()) {
1189 // 64- and 128- bit vectors inside structures are not returned in
1190 // registers.
1191 if (Size == 64 || Size == 128)
1192 return false;
1193
1194 return true;
1195 }
1196
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001197 // If this is a builtin, pointer, enum, complex type, member pointer, or
1198 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001199 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001200 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001201 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001202 return true;
1203
1204 // Arrays are treated like records.
1205 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001206 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001207
1208 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001209 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001210 if (!RT) return false;
1211
Anders Carlsson40446e82010-01-27 03:25:19 +00001212 // FIXME: Traverse bases here too.
1213
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001214 // Structure types are passed in register if all fields would be
1215 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001216 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001217 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001218 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001219 continue;
1220
1221 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001222 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001223 return false;
1224 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001225 return true;
1226}
1227
Reid Kleckner04046052016-05-02 17:41:07 +00001228static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1229 // Treat complex types as the element type.
1230 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1231 Ty = CTy->getElementType();
1232
1233 // Check for a type which we know has a simple scalar argument-passing
1234 // convention without any padding. (We're specifically looking for 32
1235 // and 64-bit integer and integer-equivalents, float, and double.)
1236 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1237 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1238 return false;
1239
1240 uint64_t Size = Context.getTypeSize(Ty);
1241 return Size == 32 || Size == 64;
1242}
1243
Reid Kleckner791bbf62017-01-13 17:18:19 +00001244static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1245 uint64_t &Size) {
1246 for (const auto *FD : RD->fields()) {
1247 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1248 // argument is smaller than 32-bits, expanding the struct will create
1249 // alignment padding.
1250 if (!is32Or64BitBasicType(FD->getType(), Context))
1251 return false;
1252
1253 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1254 // how to expand them yet, and the predicate for telling if a bitfield still
1255 // counts as "basic" is more complicated than what we were doing previously.
1256 if (FD->isBitField())
1257 return false;
1258
1259 Size += Context.getTypeSize(FD->getType());
1260 }
1261 return true;
1262}
1263
1264static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1265 uint64_t &Size) {
1266 // Don't do this if there are any non-empty bases.
1267 for (const CXXBaseSpecifier &Base : RD->bases()) {
1268 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1269 Size))
1270 return false;
1271 }
1272 if (!addFieldSizes(Context, RD, Size))
1273 return false;
1274 return true;
1275}
1276
Reid Kleckner04046052016-05-02 17:41:07 +00001277/// Test whether an argument type which is to be passed indirectly (on the
1278/// stack) would have the equivalent layout if it was expanded into separate
1279/// arguments. If so, we prefer to do the latter to avoid inhibiting
1280/// optimizations.
1281bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1282 // We can only expand structure types.
1283 const RecordType *RT = Ty->getAs<RecordType>();
1284 if (!RT)
1285 return false;
1286 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001287 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001288 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001289 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001290 // On non-Windows, we have to conservatively match our old bitcode
1291 // prototypes in order to be ABI-compatible at the bitcode level.
1292 if (!CXXRD->isCLike())
1293 return false;
1294 } else {
1295 // Don't do this for dynamic classes.
1296 if (CXXRD->isDynamicClass())
1297 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001298 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001299 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001300 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001301 } else {
1302 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001303 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001304 }
1305
1306 // We can do this if there was no alignment padding.
1307 return Size == getContext().getTypeSize(Ty);
1308}
1309
John McCall7f416cc2015-09-08 08:05:57 +00001310ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001311 // If the return value is indirect, then the hidden argument is consuming one
1312 // integer register.
1313 if (State.FreeRegs) {
1314 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001315 if (!IsMCUABI)
1316 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001317 }
John McCall7f416cc2015-09-08 08:05:57 +00001318 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001319}
1320
Eric Christopher7565e0d2015-05-29 23:09:49 +00001321ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1322 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001323 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001324 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001325
Reid Kleckner80944df2014-10-31 22:00:51 +00001326 const Type *Base = nullptr;
1327 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001328 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1329 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001330 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1331 // The LLVM struct type for such an aggregate should lower properly.
1332 return ABIArgInfo::getDirect();
1333 }
1334
Chris Lattner458b2aa2010-07-29 02:16:43 +00001335 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001336 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001337 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001338 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001339
1340 // 128-bit vectors are a special case; they are returned in
1341 // registers and we need to make sure to pick a type the LLVM
1342 // backend will like.
1343 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001344 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001345 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001346
1347 // Always return in register if it fits in a general purpose
1348 // register, or if it is 64 bits and has a single element.
1349 if ((Size == 8 || Size == 16 || Size == 32) ||
1350 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001351 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001352 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001353
John McCall7f416cc2015-09-08 08:05:57 +00001354 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001355 }
1356
1357 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001358 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001359
John McCalla1dee5302010-08-22 10:59:02 +00001360 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001361 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001362 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001363 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001364 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001365 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001366
David Chisnallde3a0692009-08-17 23:08:21 +00001367 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001368 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001369 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001370
Denis Zobnin380b2242016-02-11 11:26:03 +00001371 // Ignore empty structs/unions.
1372 if (isEmptyRecord(getContext(), RetTy, true))
1373 return ABIArgInfo::getIgnore();
1374
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001375 // Small structures which are register sized are generally returned
1376 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001377 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001378 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001379
1380 // As a special-case, if the struct is a "single-element" struct, and
1381 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001382 // floating-point register. (MSVC does not apply this special case.)
1383 // We apply a similar transformation for pointer types to improve the
1384 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001385 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001386 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001387 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001388 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1389
1390 // FIXME: We should be able to narrow this integer in cases with dead
1391 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001392 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001393 }
1394
John McCall7f416cc2015-09-08 08:05:57 +00001395 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001396 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001397
Chris Lattner458b2aa2010-07-29 02:16:43 +00001398 // Treat an enum type as its underlying type.
1399 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1400 RetTy = EnumTy->getDecl()->getIntegerType();
1401
Alex Bradburye41a5e22018-01-12 20:08:16 +00001402 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1403 : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001404}
1405
Eli Friedman7919bea2012-06-05 19:40:46 +00001406static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1407 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1408}
1409
Daniel Dunbared23de32010-09-16 20:42:00 +00001410static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1411 const RecordType *RT = Ty->getAs<RecordType>();
1412 if (!RT)
1413 return 0;
1414 const RecordDecl *RD = RT->getDecl();
1415
1416 // If this is a C++ record, check the bases first.
1417 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001418 for (const auto &I : CXXRD->bases())
1419 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001420 return false;
1421
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001422 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001423 QualType FT = i->getType();
1424
Eli Friedman7919bea2012-06-05 19:40:46 +00001425 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001426 return true;
1427
1428 if (isRecordWithSSEVectorType(Context, FT))
1429 return true;
1430 }
1431
1432 return false;
1433}
1434
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001435unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1436 unsigned Align) const {
1437 // Otherwise, if the alignment is less than or equal to the minimum ABI
1438 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001439 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001440 return 0; // Use default alignment.
1441
1442 // On non-Darwin, the stack type alignment is always 4.
1443 if (!IsDarwinVectorABI) {
1444 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001445 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001446 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001447
Daniel Dunbared23de32010-09-16 20:42:00 +00001448 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001449 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1450 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001451 return 16;
1452
1453 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001454}
1455
Rafael Espindola703c47f2012-10-19 05:04:37 +00001456ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001457 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001458 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001459 if (State.FreeRegs) {
1460 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001461 if (!IsMCUABI)
1462 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001463 }
John McCall7f416cc2015-09-08 08:05:57 +00001464 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001465 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001466
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001467 // Compute the byval alignment.
1468 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1469 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1470 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001471 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001472
1473 // If the stack alignment is less than the type alignment, realign the
1474 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001475 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001476 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1477 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001478}
1479
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001480X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1481 const Type *T = isSingleElementStruct(Ty, getContext());
1482 if (!T)
1483 T = Ty.getTypePtr();
1484
1485 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1486 BuiltinType::Kind K = BT->getKind();
1487 if (K == BuiltinType::Float || K == BuiltinType::Double)
1488 return Float;
1489 }
1490 return Integer;
1491}
1492
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001493bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001494 if (!IsSoftFloatABI) {
1495 Class C = classify(Ty);
1496 if (C == Float)
1497 return false;
1498 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001499
Rafael Espindola077dd592012-10-24 01:58:58 +00001500 unsigned Size = getContext().getTypeSize(Ty);
1501 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001502
1503 if (SizeInRegs == 0)
1504 return false;
1505
Michael Kuperstein68901882015-10-25 08:18:20 +00001506 if (!IsMCUABI) {
1507 if (SizeInRegs > State.FreeRegs) {
1508 State.FreeRegs = 0;
1509 return false;
1510 }
1511 } else {
1512 // The MCU psABI allows passing parameters in-reg even if there are
1513 // earlier parameters that are passed on the stack. Also,
1514 // it does not allow passing >8-byte structs in-register,
1515 // even if there are 3 free registers available.
1516 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1517 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001518 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001519
Reid Kleckner661f35b2014-01-18 01:12:41 +00001520 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001521 return true;
1522}
1523
1524bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1525 bool &InReg,
1526 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001527 // On Windows, aggregates other than HFAs are never passed in registers, and
1528 // they do not consume register slots. Homogenous floating-point aggregates
1529 // (HFAs) have already been dealt with at this point.
1530 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1531 return false;
1532
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001533 NeedsPadding = false;
1534 InReg = !IsMCUABI;
1535
1536 if (!updateFreeRegs(Ty, State))
1537 return false;
1538
1539 if (IsMCUABI)
1540 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001541
Reid Kleckner80944df2014-10-31 22:00:51 +00001542 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001543 State.CC == llvm::CallingConv::X86_VectorCall ||
1544 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001545 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001546 NeedsPadding = true;
1547
Rafael Espindola077dd592012-10-24 01:58:58 +00001548 return false;
1549 }
1550
Rafael Espindola703c47f2012-10-19 05:04:37 +00001551 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001552}
1553
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001554bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1555 if (!updateFreeRegs(Ty, State))
1556 return false;
1557
1558 if (IsMCUABI)
1559 return false;
1560
1561 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001562 State.CC == llvm::CallingConv::X86_VectorCall ||
1563 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001564 if (getContext().getTypeSize(Ty) > 32)
1565 return false;
1566
1567 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1568 Ty->isReferenceType());
1569 }
1570
1571 return true;
1572}
1573
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001574ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1575 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001576 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001577
Reid Klecknerb1be6832014-11-15 01:41:41 +00001578 Ty = useFirstFieldIfTransparentUnion(Ty);
1579
Reid Kleckner80944df2014-10-31 22:00:51 +00001580 // Check with the C++ ABI first.
1581 const RecordType *RT = Ty->getAs<RecordType>();
1582 if (RT) {
1583 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1584 if (RAA == CGCXXABI::RAA_Indirect) {
1585 return getIndirectResult(Ty, false, State);
1586 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1587 // The field index doesn't matter, we'll fix it up later.
1588 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1589 }
1590 }
1591
Erich Keane4bd39302017-06-21 16:37:22 +00001592 // Regcall uses the concept of a homogenous vector aggregate, similar
1593 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001594 const Type *Base = nullptr;
1595 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001596 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001597 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001598
Erich Keane4bd39302017-06-21 16:37:22 +00001599 if (State.FreeSSERegs >= NumElts) {
1600 State.FreeSSERegs -= NumElts;
1601 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001602 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001603 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001604 }
Erich Keane4bd39302017-06-21 16:37:22 +00001605 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001606 }
1607
1608 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001609 // Structures with flexible arrays are always indirect.
1610 // FIXME: This should not be byval!
1611 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1612 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001613
Reid Kleckner04046052016-05-02 17:41:07 +00001614 // Ignore empty structs/unions on non-Windows.
1615 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001616 return ABIArgInfo::getIgnore();
1617
Rafael Espindolafad28de2012-10-24 01:59:00 +00001618 llvm::LLVMContext &LLVMContext = getVMContext();
1619 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001620 bool NeedsPadding = false;
1621 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001622 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001623 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001624 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001625 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001626 if (InReg)
1627 return ABIArgInfo::getDirectInReg(Result);
1628 else
1629 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001630 }
Craig Topper8a13c412014-05-21 05:09:00 +00001631 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001632
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001633 // Expand small (<= 128-bit) record types when we know that the stack layout
1634 // of those arguments will match the struct. This is important because the
1635 // LLVM backend isn't smart enough to remove byval, which inhibits many
1636 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001637 // Don't do this for the MCU if there are still free integer registers
1638 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001639 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1640 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001641 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001642 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001643 State.CC == llvm::CallingConv::X86_VectorCall ||
1644 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001645 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001646
Reid Kleckner661f35b2014-01-18 01:12:41 +00001647 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001648 }
1649
Chris Lattnerd774ae92010-08-26 20:05:13 +00001650 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001651 // On Darwin, some vectors are passed in memory, we handle this by passing
1652 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001653 if (IsDarwinVectorABI) {
1654 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001655 if ((Size == 8 || Size == 16 || Size == 32) ||
1656 (Size == 64 && VT->getNumElements() == 1))
1657 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1658 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001659 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001660
Chad Rosier651c1832013-03-25 21:00:27 +00001661 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1662 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001663
Chris Lattnerd774ae92010-08-26 20:05:13 +00001664 return ABIArgInfo::getDirect();
1665 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001666
1667
Chris Lattner458b2aa2010-07-29 02:16:43 +00001668 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1669 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001670
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001671 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001672
1673 if (Ty->isPromotableIntegerType()) {
1674 if (InReg)
Alex Bradburye41a5e22018-01-12 20:08:16 +00001675 return ABIArgInfo::getExtendInReg(Ty);
1676 return ABIArgInfo::getExtend(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001677 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001678
Rafael Espindola703c47f2012-10-19 05:04:37 +00001679 if (InReg)
1680 return ABIArgInfo::getDirectInReg();
1681 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001682}
1683
Erich Keane521ed962017-01-05 00:20:51 +00001684void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1685 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001686 // Vectorcall x86 works subtly different than in x64, so the format is
1687 // a bit different than the x64 version. First, all vector types (not HVAs)
1688 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1689 // This differs from the x64 implementation, where the first 6 by INDEX get
1690 // registers.
1691 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1692 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1693 // first take up the remaining YMM/XMM registers. If insufficient registers
1694 // remain but an integer register (ECX/EDX) is available, it will be passed
1695 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001696 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001697 // First pass do all the vector types.
1698 const Type *Base = nullptr;
1699 uint64_t NumElts = 0;
1700 const QualType& Ty = I.type;
1701 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1702 isHomogeneousAggregate(Ty, Base, NumElts)) {
1703 if (State.FreeSSERegs >= NumElts) {
1704 State.FreeSSERegs -= NumElts;
1705 I.info = ABIArgInfo::getDirect();
1706 } else {
1707 I.info = classifyArgumentType(Ty, State);
1708 }
1709 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1710 }
Erich Keane521ed962017-01-05 00:20:51 +00001711 }
Erich Keane4bd39302017-06-21 16:37:22 +00001712
Erich Keane521ed962017-01-05 00:20:51 +00001713 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001714 // Second pass, do the rest!
1715 const Type *Base = nullptr;
1716 uint64_t NumElts = 0;
1717 const QualType& Ty = I.type;
1718 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1719
1720 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1721 // Assign true HVAs (non vector/native FP types).
1722 if (State.FreeSSERegs >= NumElts) {
1723 State.FreeSSERegs -= NumElts;
1724 I.info = getDirectX86Hva();
1725 } else {
1726 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1727 }
1728 } else if (!IsHva) {
1729 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1730 I.info = classifyArgumentType(Ty, State);
1731 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1732 }
Erich Keane521ed962017-01-05 00:20:51 +00001733 }
1734}
1735
Rafael Espindolaa6472962012-07-24 00:01:07 +00001736void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001737 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001738 if (IsMCUABI)
1739 State.FreeRegs = 3;
1740 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001741 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001742 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1743 State.FreeRegs = 2;
1744 State.FreeSSERegs = 6;
1745 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001746 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001747 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1748 State.FreeRegs = 5;
1749 State.FreeSSERegs = 8;
1750 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001751 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001752
Reid Kleckner677539d2014-07-10 01:58:55 +00001753 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001754 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001755 } else if (FI.getReturnInfo().isIndirect()) {
1756 // The C++ ABI is not aware of register usage, so we have to check if the
1757 // return value was sret and put it in a register ourselves if appropriate.
1758 if (State.FreeRegs) {
1759 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001760 if (!IsMCUABI)
1761 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001762 }
1763 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001764
Peter Collingbournef7706832014-12-12 23:41:25 +00001765 // The chain argument effectively gives us another free register.
1766 if (FI.isChainCall())
1767 ++State.FreeRegs;
1768
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001769 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001770 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1771 computeVectorCallArgs(FI, State, UsedInAlloca);
1772 } else {
1773 // If not vectorcall, revert to normal behavior.
1774 for (auto &I : FI.arguments()) {
1775 I.info = classifyArgumentType(I.type, State);
1776 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1777 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001778 }
1779
1780 // If we needed to use inalloca for any argument, do a second pass and rewrite
1781 // all the memory arguments to use inalloca.
1782 if (UsedInAlloca)
1783 rewriteWithInAlloca(FI);
1784}
1785
1786void
1787X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001788 CharUnits &StackOffset, ABIArgInfo &Info,
1789 QualType Type) const {
1790 // Arguments are always 4-byte-aligned.
1791 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1792
1793 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001794 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1795 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001796 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001797
John McCall7f416cc2015-09-08 08:05:57 +00001798 // Insert padding bytes to respect alignment.
1799 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001800 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001801 if (StackOffset != FieldEnd) {
1802 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001803 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001804 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001805 FrameFields.push_back(Ty);
1806 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001807}
1808
Reid Kleckner852361d2014-07-26 00:12:26 +00001809static bool isArgInAlloca(const ABIArgInfo &Info) {
1810 // Leave ignored and inreg arguments alone.
1811 switch (Info.getKind()) {
1812 case ABIArgInfo::InAlloca:
1813 return true;
1814 case ABIArgInfo::Indirect:
1815 assert(Info.getIndirectByVal());
1816 return true;
1817 case ABIArgInfo::Ignore:
1818 return false;
1819 case ABIArgInfo::Direct:
1820 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001821 if (Info.getInReg())
1822 return false;
1823 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001824 case ABIArgInfo::Expand:
1825 case ABIArgInfo::CoerceAndExpand:
1826 // These are aggregate types which are never passed in registers when
1827 // inalloca is involved.
1828 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001829 }
1830 llvm_unreachable("invalid enum");
1831}
1832
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001833void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1834 assert(IsWin32StructABI && "inalloca only supported on win32");
1835
1836 // Build a packed struct type for all of the arguments in memory.
1837 SmallVector<llvm::Type *, 6> FrameFields;
1838
John McCall7f416cc2015-09-08 08:05:57 +00001839 // The stack alignment is always 4.
1840 CharUnits StackAlign = CharUnits::fromQuantity(4);
1841
1842 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001843 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1844
1845 // Put 'this' into the struct before 'sret', if necessary.
1846 bool IsThisCall =
1847 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1848 ABIArgInfo &Ret = FI.getReturnInfo();
1849 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1850 isArgInAlloca(I->info)) {
1851 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1852 ++I;
1853 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001854
1855 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001856 if (Ret.isIndirect() && !Ret.getInReg()) {
1857 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1858 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001859 // On Windows, the hidden sret parameter is always returned in eax.
1860 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001861 }
1862
1863 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001864 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001865 ++I;
1866
1867 // Put arguments passed in memory into the struct.
1868 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001869 if (isArgInAlloca(I->info))
1870 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001871 }
1872
1873 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001874 /*isPacked=*/true),
1875 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001876}
1877
John McCall7f416cc2015-09-08 08:05:57 +00001878Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1879 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001880
John McCall7f416cc2015-09-08 08:05:57 +00001881 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001882
John McCall7f416cc2015-09-08 08:05:57 +00001883 // x86-32 changes the alignment of certain arguments on the stack.
1884 //
1885 // Just messing with TypeInfo like this works because we never pass
1886 // anything indirectly.
1887 TypeInfo.second = CharUnits::fromQuantity(
1888 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001889
John McCall7f416cc2015-09-08 08:05:57 +00001890 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1891 TypeInfo, CharUnits::fromQuantity(4),
1892 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001893}
1894
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001895bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1896 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1897 assert(Triple.getArch() == llvm::Triple::x86);
1898
1899 switch (Opts.getStructReturnConvention()) {
1900 case CodeGenOptions::SRCK_Default:
1901 break;
1902 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1903 return false;
1904 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1905 return true;
1906 }
1907
Michael Kupersteind749f232015-10-27 07:46:22 +00001908 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001909 return true;
1910
1911 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001912 case llvm::Triple::DragonFly:
1913 case llvm::Triple::FreeBSD:
1914 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001915 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001916 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001917 default:
1918 return false;
1919 }
1920}
1921
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001922void X86_32TargetCodeGenInfo::setTargetAttributes(
1923 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
1924 ForDefinition_t IsForDefinition) const {
1925 if (!IsForDefinition)
1926 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001927 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001928 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1929 // Get the LLVM function.
1930 llvm::Function *Fn = cast<llvm::Function>(GV);
1931
1932 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001933 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001934 B.addStackAlignmentAttr(16);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001935 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Charles Davis4ea31ab2010-02-13 15:54:06 +00001936 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001937 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1938 llvm::Function *Fn = cast<llvm::Function>(GV);
1939 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1940 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001941 }
1942}
1943
John McCallbeec5a02010-03-06 00:35:14 +00001944bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1945 CodeGen::CodeGenFunction &CGF,
1946 llvm::Value *Address) const {
1947 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001948
Chris Lattnerece04092012-02-07 00:39:47 +00001949 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001950
John McCallbeec5a02010-03-06 00:35:14 +00001951 // 0-7 are the eight integer registers; the order is different
1952 // on Darwin (for EH), but the range is the same.
1953 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001954 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001955
John McCallc8e01702013-04-16 22:48:15 +00001956 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001957 // 12-16 are st(0..4). Not sure why we stop at 4.
1958 // These have size 16, which is sizeof(long double) on
1959 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001960 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001961 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001962
John McCallbeec5a02010-03-06 00:35:14 +00001963 } else {
1964 // 9 is %eflags, which doesn't get a size on Darwin for some
1965 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001966 Builder.CreateAlignedStore(
1967 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1968 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001969
1970 // 11-16 are st(0..5). Not sure why we stop at 5.
1971 // These have size 12, which is sizeof(long double) on
1972 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001973 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001974 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1975 }
John McCallbeec5a02010-03-06 00:35:14 +00001976
1977 return false;
1978}
1979
Chris Lattner0cf24192010-06-28 20:05:43 +00001980//===----------------------------------------------------------------------===//
1981// X86-64 ABI Implementation
1982//===----------------------------------------------------------------------===//
1983
1984
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001985namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001986/// The AVX ABI level for X86 targets.
1987enum class X86AVXABILevel {
1988 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001989 AVX,
1990 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001991};
1992
1993/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1994static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1995 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001996 case X86AVXABILevel::AVX512:
1997 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001998 case X86AVXABILevel::AVX:
1999 return 256;
2000 case X86AVXABILevel::None:
2001 return 128;
2002 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002003 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002004}
2005
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002006/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002007class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002008 enum Class {
2009 Integer = 0,
2010 SSE,
2011 SSEUp,
2012 X87,
2013 X87Up,
2014 ComplexX87,
2015 NoClass,
2016 Memory
2017 };
2018
2019 /// merge - Implement the X86_64 ABI merging algorithm.
2020 ///
2021 /// Merge an accumulating classification \arg Accum with a field
2022 /// classification \arg Field.
2023 ///
2024 /// \param Accum - The accumulating classification. This should
2025 /// always be either NoClass or the result of a previous merge
2026 /// call. In addition, this should never be Memory (the caller
2027 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002028 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002029
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002030 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2031 ///
2032 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2033 /// final MEMORY or SSE classes when necessary.
2034 ///
2035 /// \param AggregateSize - The size of the current aggregate in
2036 /// the classification process.
2037 ///
2038 /// \param Lo - The classification for the parts of the type
2039 /// residing in the low word of the containing object.
2040 ///
2041 /// \param Hi - The classification for the parts of the type
2042 /// residing in the higher words of the containing object.
2043 ///
2044 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2045
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002046 /// classify - Determine the x86_64 register classes in which the
2047 /// given type T should be passed.
2048 ///
2049 /// \param Lo - The classification for the parts of the type
2050 /// residing in the low word of the containing object.
2051 ///
2052 /// \param Hi - The classification for the parts of the type
2053 /// residing in the high word of the containing object.
2054 ///
2055 /// \param OffsetBase - The bit offset of this type in the
2056 /// containing object. Some parameters are classified different
2057 /// depending on whether they straddle an eightbyte boundary.
2058 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002059 /// \param isNamedArg - Whether the argument in question is a "named"
2060 /// argument, as used in AMD64-ABI 3.5.7.
2061 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002062 /// If a word is unused its result will be NoClass; if a type should
2063 /// be passed in Memory then at least the classification of \arg Lo
2064 /// will be Memory.
2065 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002066 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002067 ///
2068 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2069 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002070 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2071 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002072
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002073 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002074 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2075 unsigned IROffset, QualType SourceTy,
2076 unsigned SourceOffset) const;
2077 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2078 unsigned IROffset, QualType SourceTy,
2079 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002080
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002081 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002082 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002083 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002084
2085 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002086 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002087 ///
2088 /// \param freeIntRegs - The number of free integer registers remaining
2089 /// available.
2090 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002091
Chris Lattner458b2aa2010-07-29 02:16:43 +00002092 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002093
Erich Keane757d3172016-11-02 18:29:35 +00002094 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2095 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002096 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002097
Erich Keane757d3172016-11-02 18:29:35 +00002098 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2099 unsigned &NeededSSE) const;
2100
2101 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2102 unsigned &NeededSSE) const;
2103
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002104 bool IsIllegalVectorType(QualType Ty) const;
2105
John McCalle0fda732011-04-21 01:20:55 +00002106 /// The 0.98 ABI revision clarified a lot of ambiguities,
2107 /// unfortunately in ways that were not always consistent with
2108 /// certain previous compilers. In particular, platforms which
2109 /// required strict binary compatibility with older versions of GCC
2110 /// may need to exempt themselves.
2111 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002112 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002113 }
2114
Richard Smithf667ad52017-08-26 01:04:35 +00002115 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2116 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002117 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002118 // Clang <= 3.8 did not do this.
2119 if (getCodeGenOpts().getClangABICompat() <=
2120 CodeGenOptions::ClangABI::Ver3_8)
2121 return false;
2122
David Majnemere2ae2282016-03-04 05:26:16 +00002123 const llvm::Triple &Triple = getTarget().getTriple();
2124 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2125 return false;
2126 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2127 return false;
2128 return true;
2129 }
2130
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002131 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002132 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2133 // 64-bit hardware.
2134 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002135
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002136public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002137 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002138 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002139 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002140 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002141
John McCalla729c622012-02-17 03:33:10 +00002142 bool isPassedUsingAVXType(QualType type) const {
2143 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002144 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002145 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2146 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002147 if (info.isDirect()) {
2148 llvm::Type *ty = info.getCoerceToType();
2149 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2150 return (vectorTy->getBitWidth() > 128);
2151 }
2152 return false;
2153 }
2154
Craig Topper4f12f102014-03-12 06:41:41 +00002155 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002156
John McCall7f416cc2015-09-08 08:05:57 +00002157 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2158 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002159 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2160 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002161
2162 bool has64BitPointers() const {
2163 return Has64BitPointers;
2164 }
John McCall12f23522016-04-04 18:33:08 +00002165
John McCall56331e22018-01-07 06:28:49 +00002166 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00002167 bool asReturnValue) const override {
2168 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2169 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002170 bool isSwiftErrorInRegister() const override {
2171 return true;
2172 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002173};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002174
Chris Lattner04dc9572010-08-31 16:44:54 +00002175/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002176class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002177public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002178 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002179 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002180 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002181
Craig Topper4f12f102014-03-12 06:41:41 +00002182 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002183
John McCall7f416cc2015-09-08 08:05:57 +00002184 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2185 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002186
2187 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2188 // FIXME: Assumes vectorcall is in use.
2189 return isX86VectorTypeForVectorCall(getContext(), Ty);
2190 }
2191
2192 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2193 uint64_t NumMembers) const override {
2194 // FIXME: Assumes vectorcall is in use.
2195 return isX86VectorCallAggregateSmallEnough(NumMembers);
2196 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002197
John McCall56331e22018-01-07 06:28:49 +00002198 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002199 bool asReturnValue) const override {
2200 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2201 }
2202
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002203 bool isSwiftErrorInRegister() const override {
2204 return true;
2205 }
2206
Reid Kleckner11a17192015-10-28 22:29:52 +00002207private:
Erich Keane521ed962017-01-05 00:20:51 +00002208 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2209 bool IsVectorCall, bool IsRegCall) const;
2210 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2211 const ABIArgInfo &current) const;
2212 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2213 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002214
Erich Keane521ed962017-01-05 00:20:51 +00002215 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002216};
2217
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002218class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2219public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002220 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002221 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002222
John McCalla729c622012-02-17 03:33:10 +00002223 const X86_64ABIInfo &getABIInfo() const {
2224 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2225 }
2226
Craig Topper4f12f102014-03-12 06:41:41 +00002227 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002228 return 7;
2229 }
2230
2231 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002232 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002233 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002234
John McCall943fae92010-05-27 06:19:26 +00002235 // 0-15 are the 16 integer registers.
2236 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002237 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002238 return false;
2239 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002240
Jay Foad7c57be32011-07-11 09:56:20 +00002241 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002242 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002243 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002244 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2245 }
2246
John McCalla729c622012-02-17 03:33:10 +00002247 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002248 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002249 // The default CC on x86-64 sets %al to the number of SSA
2250 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002251 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002252 // that when AVX types are involved: the ABI explicitly states it is
2253 // undefined, and it doesn't work in practice because of how the ABI
2254 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002255 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002256 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002257 for (CallArgList::const_iterator
2258 it = args.begin(), ie = args.end(); it != ie; ++it) {
2259 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2260 HasAVXType = true;
2261 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002262 }
2263 }
John McCalla729c622012-02-17 03:33:10 +00002264
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002265 if (!HasAVXType)
2266 return true;
2267 }
John McCallcbc038a2011-09-21 08:08:30 +00002268
John McCalla729c622012-02-17 03:33:10 +00002269 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002270 }
2271
Craig Topper4f12f102014-03-12 06:41:41 +00002272 llvm::Constant *
2273 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002274 unsigned Sig = (0xeb << 0) | // jmp rel8
2275 (0x06 << 8) | // .+0x08
2276 ('v' << 16) |
2277 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002278 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2279 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002280
2281 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002282 CodeGen::CodeGenModule &CGM,
2283 ForDefinition_t IsForDefinition) const override {
2284 if (!IsForDefinition)
2285 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002286 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002287 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2288 // Get the LLVM function.
2289 auto *Fn = cast<llvm::Function>(GV);
2290
2291 // Now add the 'alignstack' attribute with a value of 16.
2292 llvm::AttrBuilder B;
2293 B.addStackAlignmentAttr(16);
2294 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2295 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002296 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2297 llvm::Function *Fn = cast<llvm::Function>(GV);
2298 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2299 }
2300 }
2301 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002302};
2303
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002304class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2305public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002306 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2307 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002308
2309 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002310 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002311 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002312 // If the argument contains a space, enclose it in quotes.
2313 if (Lib.find(" ") != StringRef::npos)
2314 Opt += "\"" + Lib.str() + "\"";
2315 else
2316 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002317 }
2318};
2319
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002320static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002321 // If the argument does not end in .lib, automatically add the suffix.
2322 // If the argument contains a space, enclose it in quotes.
2323 // This matches the behavior of MSVC.
2324 bool Quote = (Lib.find(" ") != StringRef::npos);
2325 std::string ArgStr = Quote ? "\"" : "";
2326 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002327 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002328 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002329 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002330 return ArgStr;
2331}
2332
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002333class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2334public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002335 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002336 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2337 unsigned NumRegisterParameters)
2338 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002339 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002340
Eric Christopher162c91c2015-06-05 22:03:00 +00002341 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002342 CodeGen::CodeGenModule &CGM,
2343 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002344
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002345 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002346 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002347 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002348 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002349 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002350
2351 void getDetectMismatchOption(llvm::StringRef Name,
2352 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002353 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002354 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002355 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002356};
2357
Hans Wennborg77dc2362015-01-20 19:45:50 +00002358static void addStackProbeSizeTargetAttribute(const Decl *D,
2359 llvm::GlobalValue *GV,
2360 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002361 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002362 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2363 llvm::Function *Fn = cast<llvm::Function>(GV);
2364
Eric Christopher7565e0d2015-05-29 23:09:49 +00002365 Fn->addFnAttr("stack-probe-size",
2366 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002367 }
2368 }
2369}
2370
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002371void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2372 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2373 ForDefinition_t IsForDefinition) const {
2374 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2375 if (!IsForDefinition)
2376 return;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002377 addStackProbeSizeTargetAttribute(D, GV, CGM);
2378}
2379
Chris Lattner04dc9572010-08-31 16:44:54 +00002380class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2381public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002382 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2383 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002384 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002385
Eric Christopher162c91c2015-06-05 22:03:00 +00002386 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002387 CodeGen::CodeGenModule &CGM,
2388 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002389
Craig Topper4f12f102014-03-12 06:41:41 +00002390 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002391 return 7;
2392 }
2393
2394 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002395 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002396 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002397
Chris Lattner04dc9572010-08-31 16:44:54 +00002398 // 0-15 are the 16 integer registers.
2399 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002400 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002401 return false;
2402 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002403
2404 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002405 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002406 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002407 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002408 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002409
2410 void getDetectMismatchOption(llvm::StringRef Name,
2411 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002412 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002413 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002414 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002415};
2416
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002417void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2418 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2419 ForDefinition_t IsForDefinition) const {
2420 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2421 if (!IsForDefinition)
2422 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002423 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002424 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2425 // Get the LLVM function.
2426 auto *Fn = cast<llvm::Function>(GV);
2427
2428 // Now add the 'alignstack' attribute with a value of 16.
2429 llvm::AttrBuilder B;
2430 B.addStackAlignmentAttr(16);
2431 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2432 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002433 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2434 llvm::Function *Fn = cast<llvm::Function>(GV);
2435 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2436 }
2437 }
2438
Hans Wennborg77dc2362015-01-20 19:45:50 +00002439 addStackProbeSizeTargetAttribute(D, GV, CGM);
2440}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002441}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002442
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002443void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2444 Class &Hi) const {
2445 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2446 //
2447 // (a) If one of the classes is Memory, the whole argument is passed in
2448 // memory.
2449 //
2450 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2451 // memory.
2452 //
2453 // (c) If the size of the aggregate exceeds two eightbytes and the first
2454 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2455 // argument is passed in memory. NOTE: This is necessary to keep the
2456 // ABI working for processors that don't support the __m256 type.
2457 //
2458 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2459 //
2460 // Some of these are enforced by the merging logic. Others can arise
2461 // only with unions; for example:
2462 // union { _Complex double; unsigned; }
2463 //
2464 // Note that clauses (b) and (c) were added in 0.98.
2465 //
2466 if (Hi == Memory)
2467 Lo = Memory;
2468 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2469 Lo = Memory;
2470 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2471 Lo = Memory;
2472 if (Hi == SSEUp && Lo != SSE)
2473 Hi = SSE;
2474}
2475
Chris Lattnerd776fb12010-06-28 21:43:59 +00002476X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002477 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2478 // classified recursively so that always two fields are
2479 // considered. The resulting class is calculated according to
2480 // the classes of the fields in the eightbyte:
2481 //
2482 // (a) If both classes are equal, this is the resulting class.
2483 //
2484 // (b) If one of the classes is NO_CLASS, the resulting class is
2485 // the other class.
2486 //
2487 // (c) If one of the classes is MEMORY, the result is the MEMORY
2488 // class.
2489 //
2490 // (d) If one of the classes is INTEGER, the result is the
2491 // INTEGER.
2492 //
2493 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2494 // MEMORY is used as class.
2495 //
2496 // (f) Otherwise class SSE is used.
2497
2498 // Accum should never be memory (we should have returned) or
2499 // ComplexX87 (because this cannot be passed in a structure).
2500 assert((Accum != Memory && Accum != ComplexX87) &&
2501 "Invalid accumulated classification during merge.");
2502 if (Accum == Field || Field == NoClass)
2503 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002504 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002505 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002506 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002507 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002508 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002509 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002510 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2511 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002512 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002513 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002514}
2515
Chris Lattner5c740f12010-06-30 19:14:05 +00002516void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002517 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002518 // FIXME: This code can be simplified by introducing a simple value class for
2519 // Class pairs with appropriate constructor methods for the various
2520 // situations.
2521
2522 // FIXME: Some of the split computations are wrong; unaligned vectors
2523 // shouldn't be passed in registers for example, so there is no chance they
2524 // can straddle an eightbyte. Verify & simplify.
2525
2526 Lo = Hi = NoClass;
2527
2528 Class &Current = OffsetBase < 64 ? Lo : Hi;
2529 Current = Memory;
2530
John McCall9dd450b2009-09-21 23:43:11 +00002531 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002532 BuiltinType::Kind k = BT->getKind();
2533
2534 if (k == BuiltinType::Void) {
2535 Current = NoClass;
2536 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2537 Lo = Integer;
2538 Hi = Integer;
2539 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2540 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002541 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002542 Current = SSE;
2543 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002544 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002545 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002546 Lo = SSE;
2547 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002548 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002549 Lo = X87;
2550 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002551 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002552 Current = SSE;
2553 } else
2554 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555 }
2556 // FIXME: _Decimal32 and _Decimal64 are SSE.
2557 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002558 return;
2559 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002560
Chris Lattnerd776fb12010-06-28 21:43:59 +00002561 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002562 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002563 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002564 return;
2565 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002566
Chris Lattnerd776fb12010-06-28 21:43:59 +00002567 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002568 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002569 return;
2570 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002571
Chris Lattnerd776fb12010-06-28 21:43:59 +00002572 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002573 if (Ty->isMemberFunctionPointerType()) {
2574 if (Has64BitPointers) {
2575 // If Has64BitPointers, this is an {i64, i64}, so classify both
2576 // Lo and Hi now.
2577 Lo = Hi = Integer;
2578 } else {
2579 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2580 // straddles an eightbyte boundary, Hi should be classified as well.
2581 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2582 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2583 if (EB_FuncPtr != EB_ThisAdj) {
2584 Lo = Hi = Integer;
2585 } else {
2586 Current = Integer;
2587 }
2588 }
2589 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002590 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002591 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002592 return;
2593 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002594
Chris Lattnerd776fb12010-06-28 21:43:59 +00002595 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002596 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002597 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2598 // gcc passes the following as integer:
2599 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2600 // 2 bytes - <2 x char>, <1 x short>
2601 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002602 Current = Integer;
2603
2604 // If this type crosses an eightbyte boundary, it should be
2605 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002606 uint64_t EB_Lo = (OffsetBase) / 64;
2607 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2608 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002609 Hi = Lo;
2610 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002611 QualType ElementType = VT->getElementType();
2612
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002613 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002614 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002615 return;
2616
David Majnemere2ae2282016-03-04 05:26:16 +00002617 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2618 // pass them as integer. For platforms where clang is the de facto
2619 // platform compiler, we must continue to use integer.
2620 if (!classifyIntegerMMXAsSSE() &&
2621 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2622 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2623 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2624 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002625 Current = Integer;
2626 else
2627 Current = SSE;
2628
2629 // If this type crosses an eightbyte boundary, it should be
2630 // split.
2631 if (OffsetBase && OffsetBase != 64)
2632 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002633 } else if (Size == 128 ||
2634 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002635 // Arguments of 256-bits are split into four eightbyte chunks. The
2636 // least significant one belongs to class SSE and all the others to class
2637 // SSEUP. The original Lo and Hi design considers that types can't be
2638 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2639 // This design isn't correct for 256-bits, but since there're no cases
2640 // where the upper parts would need to be inspected, avoid adding
2641 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002642 //
2643 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2644 // registers if they are "named", i.e. not part of the "..." of a
2645 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002646 //
2647 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2648 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002649 Lo = SSE;
2650 Hi = SSEUp;
2651 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002652 return;
2653 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002654
Chris Lattnerd776fb12010-06-28 21:43:59 +00002655 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002656 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002657
Chris Lattner2b037972010-07-29 02:01:43 +00002658 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002659 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002660 if (Size <= 64)
2661 Current = Integer;
2662 else if (Size <= 128)
2663 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002664 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002665 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002666 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002667 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002668 } else if (ET == getContext().LongDoubleTy) {
2669 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002670 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002671 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002672 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002673 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002674 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002675 Lo = Hi = SSE;
2676 else
2677 llvm_unreachable("unexpected long double representation!");
2678 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002679
2680 // If this complex type crosses an eightbyte boundary then it
2681 // should be split.
2682 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002683 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002684 if (Hi == NoClass && EB_Real != EB_Imag)
2685 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002686
Chris Lattnerd776fb12010-06-28 21:43:59 +00002687 return;
2688 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002689
Chris Lattner2b037972010-07-29 02:01:43 +00002690 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002691 // Arrays are treated like structures.
2692
Chris Lattner2b037972010-07-29 02:01:43 +00002693 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002694
2695 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002696 // than eight eightbytes, ..., it has class MEMORY.
2697 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002698 return;
2699
2700 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2701 // fields, it has class MEMORY.
2702 //
2703 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002704 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002705 return;
2706
2707 // Otherwise implement simplified merge. We could be smarter about
2708 // this, but it isn't worth it and would be harder to verify.
2709 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002710 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002711 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002712
2713 // The only case a 256-bit wide vector could be used is when the array
2714 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2715 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002716 //
2717 if (Size > 128 &&
2718 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002719 return;
2720
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002721 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2722 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002723 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002724 Lo = merge(Lo, FieldLo);
2725 Hi = merge(Hi, FieldHi);
2726 if (Lo == Memory || Hi == Memory)
2727 break;
2728 }
2729
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002730 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002731 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002732 return;
2733 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002734
Chris Lattnerd776fb12010-06-28 21:43:59 +00002735 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002736 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002737
2738 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002739 // than eight eightbytes, ..., it has class MEMORY.
2740 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002741 return;
2742
Anders Carlsson20759ad2009-09-16 15:53:40 +00002743 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2744 // copy constructor or a non-trivial destructor, it is passed by invisible
2745 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002746 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002747 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002748
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002749 const RecordDecl *RD = RT->getDecl();
2750
2751 // Assume variable sized types are passed in memory.
2752 if (RD->hasFlexibleArrayMember())
2753 return;
2754
Chris Lattner2b037972010-07-29 02:01:43 +00002755 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002756
2757 // Reset Lo class, this will be recomputed.
2758 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002759
2760 // If this is a C++ record, classify the bases first.
2761 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002762 for (const auto &I : CXXRD->bases()) {
2763 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002764 "Unexpected base class!");
2765 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002766 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002767
2768 // Classify this field.
2769 //
2770 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2771 // single eightbyte, each is classified separately. Each eightbyte gets
2772 // initialized to class NO_CLASS.
2773 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002774 uint64_t Offset =
2775 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002776 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002777 Lo = merge(Lo, FieldLo);
2778 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002779 if (Lo == Memory || Hi == Memory) {
2780 postMerge(Size, Lo, Hi);
2781 return;
2782 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002783 }
2784 }
2785
2786 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002787 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002788 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002789 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002790 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2791 bool BitField = i->isBitField();
2792
David Majnemerb439dfe2016-08-15 07:20:40 +00002793 // Ignore padding bit-fields.
2794 if (BitField && i->isUnnamedBitfield())
2795 continue;
2796
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002797 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2798 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002799 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002800 // The only case a 256-bit wide vector could be used is when the struct
2801 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2802 // to work for sizes wider than 128, early check and fallback to memory.
2803 //
David Majnemerb229cb02016-08-15 06:39:18 +00002804 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2805 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002806 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002807 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002808 return;
2809 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002810 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002811 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002812 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002813 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002814 return;
2815 }
2816
2817 // Classify this field.
2818 //
2819 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2820 // exceeds a single eightbyte, each is classified
2821 // separately. Each eightbyte gets initialized to class
2822 // NO_CLASS.
2823 Class FieldLo, FieldHi;
2824
2825 // Bit-fields require special handling, they do not force the
2826 // structure to be passed in memory even if unaligned, and
2827 // therefore they can straddle an eightbyte.
2828 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002829 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002830 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002831 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002832
2833 uint64_t EB_Lo = Offset / 64;
2834 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002835
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002836 if (EB_Lo) {
2837 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2838 FieldLo = NoClass;
2839 FieldHi = Integer;
2840 } else {
2841 FieldLo = Integer;
2842 FieldHi = EB_Hi ? Integer : NoClass;
2843 }
2844 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002845 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002846 Lo = merge(Lo, FieldLo);
2847 Hi = merge(Hi, FieldHi);
2848 if (Lo == Memory || Hi == Memory)
2849 break;
2850 }
2851
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002852 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002853 }
2854}
2855
Chris Lattner22a931e2010-06-29 06:01:59 +00002856ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002857 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2858 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002859 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002860 // Treat an enum type as its underlying type.
2861 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2862 Ty = EnumTy->getDecl()->getIntegerType();
2863
Alex Bradburye41a5e22018-01-12 20:08:16 +00002864 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2865 : ABIArgInfo::getDirect());
Daniel Dunbar53fac692010-04-21 19:49:55 +00002866 }
2867
John McCall7f416cc2015-09-08 08:05:57 +00002868 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002869}
2870
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002871bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2872 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2873 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002874 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002875 if (Size <= 64 || Size > LargestVector)
2876 return true;
2877 }
2878
2879 return false;
2880}
2881
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002882ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2883 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002884 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2885 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002886 //
2887 // This assumption is optimistic, as there could be free registers available
2888 // when we need to pass this argument in memory, and LLVM could try to pass
2889 // the argument in the free register. This does not seem to happen currently,
2890 // but this code would be much safer if we could mark the argument with
2891 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002892 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002893 // Treat an enum type as its underlying type.
2894 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2895 Ty = EnumTy->getDecl()->getIntegerType();
2896
Alex Bradburye41a5e22018-01-12 20:08:16 +00002897 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2898 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002899 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002900
Mark Lacey3825e832013-10-06 01:33:34 +00002901 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002902 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002903
Chris Lattner44c2b902011-05-22 23:21:23 +00002904 // Compute the byval alignment. We specify the alignment of the byval in all
2905 // cases so that the mid-level optimizer knows the alignment of the byval.
2906 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002907
2908 // Attempt to avoid passing indirect results using byval when possible. This
2909 // is important for good codegen.
2910 //
2911 // We do this by coercing the value into a scalar type which the backend can
2912 // handle naturally (i.e., without using byval).
2913 //
2914 // For simplicity, we currently only do this when we have exhausted all of the
2915 // free integer registers. Doing this when there are free integer registers
2916 // would require more care, as we would have to ensure that the coerced value
2917 // did not claim the unused register. That would require either reording the
2918 // arguments to the function (so that any subsequent inreg values came first),
2919 // or only doing this optimization when there were no following arguments that
2920 // might be inreg.
2921 //
2922 // We currently expect it to be rare (particularly in well written code) for
2923 // arguments to be passed on the stack when there are still free integer
2924 // registers available (this would typically imply large structs being passed
2925 // by value), so this seems like a fair tradeoff for now.
2926 //
2927 // We can revisit this if the backend grows support for 'onstack' parameter
2928 // attributes. See PR12193.
2929 if (freeIntRegs == 0) {
2930 uint64_t Size = getContext().getTypeSize(Ty);
2931
2932 // If this type fits in an eightbyte, coerce it into the matching integral
2933 // type, which will end up on the stack (with alignment 8).
2934 if (Align == 8 && Size <= 64)
2935 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2936 Size));
2937 }
2938
John McCall7f416cc2015-09-08 08:05:57 +00002939 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002940}
2941
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002942/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2943/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002944llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002945 // Wrapper structs/arrays that only contain vectors are passed just like
2946 // vectors; strip them off if present.
2947 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2948 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002949
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002950 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002951 if (isa<llvm::VectorType>(IRType) ||
2952 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002953 return IRType;
2954
2955 // We couldn't find the preferred IR vector type for 'Ty'.
2956 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002957 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002958
2959 // Return a LLVM IR vector type based on the size of 'Ty'.
2960 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2961 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002962}
2963
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002964/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2965/// is known to either be off the end of the specified type or being in
2966/// alignment padding. The user type specified is known to be at most 128 bits
2967/// in size, and have passed through X86_64ABIInfo::classify with a successful
2968/// classification that put one of the two halves in the INTEGER class.
2969///
2970/// It is conservatively correct to return false.
2971static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2972 unsigned EndBit, ASTContext &Context) {
2973 // If the bytes being queried are off the end of the type, there is no user
2974 // data hiding here. This handles analysis of builtins, vectors and other
2975 // types that don't contain interesting padding.
2976 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2977 if (TySize <= StartBit)
2978 return true;
2979
Chris Lattner98076a22010-07-29 07:43:55 +00002980 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2981 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2982 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2983
2984 // Check each element to see if the element overlaps with the queried range.
2985 for (unsigned i = 0; i != NumElts; ++i) {
2986 // If the element is after the span we care about, then we're done..
2987 unsigned EltOffset = i*EltSize;
2988 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002989
Chris Lattner98076a22010-07-29 07:43:55 +00002990 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2991 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2992 EndBit-EltOffset, Context))
2993 return false;
2994 }
2995 // If it overlaps no elements, then it is safe to process as padding.
2996 return true;
2997 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002998
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002999 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3000 const RecordDecl *RD = RT->getDecl();
3001 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003002
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003003 // If this is a C++ record, check the bases first.
3004 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003005 for (const auto &I : CXXRD->bases()) {
3006 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003007 "Unexpected base class!");
3008 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003009 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003010
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003011 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003012 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003013 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003014
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003015 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003016 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003017 EndBit-BaseOffset, Context))
3018 return false;
3019 }
3020 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003021
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003022 // Verify that no field has data that overlaps the region of interest. Yes
3023 // this could be sped up a lot by being smarter about queried fields,
3024 // however we're only looking at structs up to 16 bytes, so we don't care
3025 // much.
3026 unsigned idx = 0;
3027 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3028 i != e; ++i, ++idx) {
3029 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003030
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003031 // If we found a field after the region we care about, then we're done.
3032 if (FieldOffset >= EndBit) break;
3033
3034 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3035 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3036 Context))
3037 return false;
3038 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003039
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003040 // If nothing in this record overlapped the area of interest, then we're
3041 // clean.
3042 return true;
3043 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003044
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003045 return false;
3046}
3047
Chris Lattnere556a712010-07-29 18:39:32 +00003048/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3049/// float member at the specified offset. For example, {int,{float}} has a
3050/// float at offset 4. It is conservatively correct for this routine to return
3051/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003052static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003053 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003054 // Base case if we find a float.
3055 if (IROffset == 0 && IRType->isFloatTy())
3056 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003057
Chris Lattnere556a712010-07-29 18:39:32 +00003058 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003059 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003060 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3061 unsigned Elt = SL->getElementContainingOffset(IROffset);
3062 IROffset -= SL->getElementOffset(Elt);
3063 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3064 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003065
Chris Lattnere556a712010-07-29 18:39:32 +00003066 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003067 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3068 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003069 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3070 IROffset -= IROffset/EltSize*EltSize;
3071 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3072 }
3073
3074 return false;
3075}
3076
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003077
3078/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3079/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003080llvm::Type *X86_64ABIInfo::
3081GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003082 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003083 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003084 // pass as float if the last 4 bytes is just padding. This happens for
3085 // structs that contain 3 floats.
3086 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3087 SourceOffset*8+64, getContext()))
3088 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003089
Chris Lattnere556a712010-07-29 18:39:32 +00003090 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3091 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3092 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003093 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3094 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003095 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003096
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003097 return llvm::Type::getDoubleTy(getVMContext());
3098}
3099
3100
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003101/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3102/// an 8-byte GPR. This means that we either have a scalar or we are talking
3103/// about the high or low part of an up-to-16-byte struct. This routine picks
3104/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003105/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3106/// etc).
3107///
3108/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3109/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3110/// the 8-byte value references. PrefType may be null.
3111///
Alp Toker9907f082014-07-09 14:06:35 +00003112/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003113/// an offset into this that we're processing (which is always either 0 or 8).
3114///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003115llvm::Type *X86_64ABIInfo::
3116GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003117 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003118 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3119 // returning an 8-byte unit starting with it. See if we can safely use it.
3120 if (IROffset == 0) {
3121 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003122 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3123 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003124 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003125
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003126 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3127 // goodness in the source type is just tail padding. This is allowed to
3128 // kick in for struct {double,int} on the int, but not on
3129 // struct{double,int,int} because we wouldn't return the second int. We
3130 // have to do this analysis on the source type because we can't depend on
3131 // unions being lowered a specific way etc.
3132 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003133 IRType->isIntegerTy(32) ||
3134 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3135 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3136 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003137
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003138 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3139 SourceOffset*8+64, getContext()))
3140 return IRType;
3141 }
3142 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003143
Chris Lattner2192fe52011-07-18 04:24:23 +00003144 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003145 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003146 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003147 if (IROffset < SL->getSizeInBytes()) {
3148 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3149 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003150
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003151 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3152 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003153 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003154 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003155
Chris Lattner2192fe52011-07-18 04:24:23 +00003156 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003157 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003158 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003159 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003160 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3161 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003162 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003163
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003164 // Okay, we don't have any better idea of what to pass, so we pass this in an
3165 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003166 unsigned TySizeInBytes =
3167 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003168
Chris Lattner3f763422010-07-29 17:34:39 +00003169 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003170
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003171 // It is always safe to classify this as an integer type up to i64 that
3172 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003173 return llvm::IntegerType::get(getVMContext(),
3174 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003175}
3176
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003177
3178/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3179/// be used as elements of a two register pair to pass or return, return a
3180/// first class aggregate to represent them. For example, if the low part of
3181/// a by-value argument should be passed as i32* and the high part as float,
3182/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003183static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003184GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003185 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003186 // In order to correctly satisfy the ABI, we need to the high part to start
3187 // at offset 8. If the high and low parts we inferred are both 4-byte types
3188 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3189 // the second element at offset 8. Check for this:
3190 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3191 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003192 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003193 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003194
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003195 // To handle this, we have to increase the size of the low part so that the
3196 // second element will start at an 8 byte offset. We can't increase the size
3197 // of the second element because it might make us access off the end of the
3198 // struct.
3199 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003200 // There are usually two sorts of types the ABI generation code can produce
3201 // for the low part of a pair that aren't 8 bytes in size: float or
3202 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3203 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003204 // Promote these to a larger type.
3205 if (Lo->isFloatTy())
3206 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3207 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003208 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3209 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003210 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3211 }
3212 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003213
Serge Guelton1d993272017-05-09 19:31:30 +00003214 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003215
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003216 // Verify that the second element is at an 8-byte offset.
3217 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3218 "Invalid x86-64 argument pair!");
3219 return Result;
3220}
3221
Chris Lattner31faff52010-07-28 23:06:14 +00003222ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003223classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003224 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3225 // classification algorithm.
3226 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003227 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003228
3229 // Check some invariants.
3230 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003231 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3232
Craig Topper8a13c412014-05-21 05:09:00 +00003233 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003234 switch (Lo) {
3235 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003236 if (Hi == NoClass)
3237 return ABIArgInfo::getIgnore();
3238 // If the low part is just padding, it takes no register, leave ResType
3239 // null.
3240 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3241 "Unknown missing lo part");
3242 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003243
3244 case SSEUp:
3245 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003246 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003247
3248 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3249 // hidden argument.
3250 case Memory:
3251 return getIndirectReturnResult(RetTy);
3252
3253 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3254 // available register of the sequence %rax, %rdx is used.
3255 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003256 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003257
Chris Lattner1f3a0632010-07-29 21:42:50 +00003258 // If we have a sign or zero extended integer, make sure to return Extend
3259 // so that the parameter gets the right LLVM IR attributes.
3260 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3261 // Treat an enum type as its underlying type.
3262 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3263 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003264
Chris Lattner1f3a0632010-07-29 21:42:50 +00003265 if (RetTy->isIntegralOrEnumerationType() &&
3266 RetTy->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003267 return ABIArgInfo::getExtend(RetTy);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003268 }
Chris Lattner31faff52010-07-28 23:06:14 +00003269 break;
3270
3271 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3272 // available SSE register of the sequence %xmm0, %xmm1 is used.
3273 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003274 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003275 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003276
3277 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3278 // returned on the X87 stack in %st0 as 80-bit x87 number.
3279 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003280 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003281 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003282
3283 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3284 // part of the value is returned in %st0 and the imaginary part in
3285 // %st1.
3286 case ComplexX87:
3287 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003288 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003289 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003290 break;
3291 }
3292
Craig Topper8a13c412014-05-21 05:09:00 +00003293 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003294 switch (Hi) {
3295 // Memory was handled previously and X87 should
3296 // never occur as a hi class.
3297 case Memory:
3298 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003299 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003300
3301 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003302 case NoClass:
3303 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003304
Chris Lattner52b3c132010-09-01 00:20:33 +00003305 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003306 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003307 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3308 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003309 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003310 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003311 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003312 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3313 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003314 break;
3315
3316 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003317 // is passed in the next available eightbyte chunk if the last used
3318 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003319 //
Chris Lattner57540c52011-04-15 05:22:18 +00003320 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003321 case SSEUp:
3322 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003323 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003324 break;
3325
3326 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3327 // returned together with the previous X87 value in %st0.
3328 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003329 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003330 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003331 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003332 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003333 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003334 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003335 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3336 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003337 }
Chris Lattner31faff52010-07-28 23:06:14 +00003338 break;
3339 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003340
Chris Lattner52b3c132010-09-01 00:20:33 +00003341 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003342 // known to pass in the high eightbyte of the result. We do this by forming a
3343 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003344 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003345 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003346
Chris Lattner1f3a0632010-07-29 21:42:50 +00003347 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003348}
3349
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003350ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003351 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3352 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003353 const
3354{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003355 Ty = useFirstFieldIfTransparentUnion(Ty);
3356
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003357 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003358 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003359
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003360 // Check some invariants.
3361 // FIXME: Enforce these by construction.
3362 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003363 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3364
3365 neededInt = 0;
3366 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003367 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003368 switch (Lo) {
3369 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003370 if (Hi == NoClass)
3371 return ABIArgInfo::getIgnore();
3372 // If the low part is just padding, it takes no register, leave ResType
3373 // null.
3374 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3375 "Unknown missing lo part");
3376 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003377
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003378 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3379 // on the stack.
3380 case Memory:
3381
3382 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3383 // COMPLEX_X87, it is passed in memory.
3384 case X87:
3385 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003386 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003387 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003388 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003389
3390 case SSEUp:
3391 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003392 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003393
3394 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3395 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3396 // and %r9 is used.
3397 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003398 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003399
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003400 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003401 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003402
3403 // If we have a sign or zero extended integer, make sure to return Extend
3404 // so that the parameter gets the right LLVM IR attributes.
3405 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3406 // Treat an enum type as its underlying type.
3407 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3408 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003409
Chris Lattner1f3a0632010-07-29 21:42:50 +00003410 if (Ty->isIntegralOrEnumerationType() &&
3411 Ty->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003412 return ABIArgInfo::getExtend(Ty);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003413 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003414
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003415 break;
3416
3417 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3418 // available SSE register is used, the registers are taken in the
3419 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003420 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003421 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003422 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003423 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003424 break;
3425 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003426 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003427
Craig Topper8a13c412014-05-21 05:09:00 +00003428 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003429 switch (Hi) {
3430 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003431 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003432 // which is passed in memory.
3433 case Memory:
3434 case X87:
3435 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003436 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003437
3438 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003439
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003440 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003441 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003442 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003443 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003444
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003445 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3446 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003447 break;
3448
3449 // X87Up generally doesn't occur here (long double is passed in
3450 // memory), except in situations involving unions.
3451 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003452 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003453 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003454
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003455 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3456 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003457
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003458 ++neededSSE;
3459 break;
3460
3461 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3462 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003463 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003464 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003465 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003466 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003467 break;
3468 }
3469
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003470 // If a high part was specified, merge it together with the low part. It is
3471 // known to pass in the high eightbyte of the result. We do this by forming a
3472 // first class struct aggregate with the high and low part: {low, high}
3473 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003474 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003475
Chris Lattner1f3a0632010-07-29 21:42:50 +00003476 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003477}
3478
Erich Keane757d3172016-11-02 18:29:35 +00003479ABIArgInfo
3480X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3481 unsigned &NeededSSE) const {
3482 auto RT = Ty->getAs<RecordType>();
3483 assert(RT && "classifyRegCallStructType only valid with struct types");
3484
3485 if (RT->getDecl()->hasFlexibleArrayMember())
3486 return getIndirectReturnResult(Ty);
3487
3488 // Sum up bases
3489 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3490 if (CXXRD->isDynamicClass()) {
3491 NeededInt = NeededSSE = 0;
3492 return getIndirectReturnResult(Ty);
3493 }
3494
3495 for (const auto &I : CXXRD->bases())
3496 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3497 .isIndirect()) {
3498 NeededInt = NeededSSE = 0;
3499 return getIndirectReturnResult(Ty);
3500 }
3501 }
3502
3503 // Sum up members
3504 for (const auto *FD : RT->getDecl()->fields()) {
3505 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3506 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3507 .isIndirect()) {
3508 NeededInt = NeededSSE = 0;
3509 return getIndirectReturnResult(Ty);
3510 }
3511 } else {
3512 unsigned LocalNeededInt, LocalNeededSSE;
3513 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3514 LocalNeededSSE, true)
3515 .isIndirect()) {
3516 NeededInt = NeededSSE = 0;
3517 return getIndirectReturnResult(Ty);
3518 }
3519 NeededInt += LocalNeededInt;
3520 NeededSSE += LocalNeededSSE;
3521 }
3522 }
3523
3524 return ABIArgInfo::getDirect();
3525}
3526
3527ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3528 unsigned &NeededInt,
3529 unsigned &NeededSSE) const {
3530
3531 NeededInt = 0;
3532 NeededSSE = 0;
3533
3534 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3535}
3536
Chris Lattner22326a12010-07-29 02:31:05 +00003537void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003538
Erich Keane757d3172016-11-02 18:29:35 +00003539 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003540
3541 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003542 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3543 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3544 unsigned NeededInt, NeededSSE;
3545
Erich Keanede1b2a92017-07-21 18:50:36 +00003546 if (!getCXXABI().classifyReturnType(FI)) {
3547 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3548 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3549 FI.getReturnInfo() =
3550 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3551 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3552 FreeIntRegs -= NeededInt;
3553 FreeSSERegs -= NeededSSE;
3554 } else {
3555 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3556 }
3557 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3558 // Complex Long Double Type is passed in Memory when Regcall
3559 // calling convention is used.
3560 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3561 if (getContext().getCanonicalType(CT->getElementType()) ==
3562 getContext().LongDoubleTy)
3563 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3564 } else
3565 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3566 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003567
3568 // If the return value is indirect, then the hidden argument is consuming one
3569 // integer register.
3570 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003571 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003572
Peter Collingbournef7706832014-12-12 23:41:25 +00003573 // The chain argument effectively gives us another free register.
3574 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003575 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003576
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003577 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003578 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3579 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003580 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003581 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003582 it != ie; ++it, ++ArgNo) {
3583 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003584
Erich Keane757d3172016-11-02 18:29:35 +00003585 if (IsRegCall && it->type->isStructureOrClassType())
3586 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3587 else
3588 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3589 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003590
3591 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3592 // eightbyte of an argument, the whole argument is passed on the
3593 // stack. If registers have already been assigned for some
3594 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003595 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3596 FreeIntRegs -= NeededInt;
3597 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003598 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003599 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003600 }
3601 }
3602}
3603
John McCall7f416cc2015-09-08 08:05:57 +00003604static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3605 Address VAListAddr, QualType Ty) {
3606 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3607 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003608 llvm::Value *overflow_arg_area =
3609 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3610
3611 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3612 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003613 // It isn't stated explicitly in the standard, but in practice we use
3614 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003615 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3616 if (Align > CharUnits::fromQuantity(8)) {
3617 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3618 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003619 }
3620
3621 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003622 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003623 llvm::Value *Res =
3624 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003625 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003626
3627 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3628 // l->overflow_arg_area + sizeof(type).
3629 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3630 // an 8 byte boundary.
3631
3632 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003633 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003634 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003635 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3636 "overflow_arg_area.next");
3637 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3638
3639 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003640 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003641}
3642
John McCall7f416cc2015-09-08 08:05:57 +00003643Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3644 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003645 // Assume that va_list type is correct; should be pointer to LLVM type:
3646 // struct {
3647 // i32 gp_offset;
3648 // i32 fp_offset;
3649 // i8* overflow_arg_area;
3650 // i8* reg_save_area;
3651 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003652 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003653
John McCall7f416cc2015-09-08 08:05:57 +00003654 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003655 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003656 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003657
3658 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3659 // in the registers. If not go to step 7.
3660 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003661 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003662
3663 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3664 // general purpose registers needed to pass type and num_fp to hold
3665 // the number of floating point registers needed.
3666
3667 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3668 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3669 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3670 //
3671 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3672 // register save space).
3673
Craig Topper8a13c412014-05-21 05:09:00 +00003674 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003675 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3676 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003677 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003678 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003679 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3680 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003681 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003682 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3683 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003684 }
3685
3686 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003687 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003688 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3689 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003690 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3691 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003692 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3693 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003694 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3695 }
3696
3697 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3698 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3699 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3700 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3701
3702 // Emit code to load the value if it was passed in registers.
3703
3704 CGF.EmitBlock(InRegBlock);
3705
3706 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3707 // an offset of l->gp_offset and/or l->fp_offset. This may require
3708 // copying to a temporary location in case the parameter is passed
3709 // in different register classes or requires an alignment greater
3710 // than 8 for general purpose registers and 16 for XMM registers.
3711 //
3712 // FIXME: This really results in shameful code when we end up needing to
3713 // collect arguments from different places; often what should result in a
3714 // simple assembling of a structure from scattered addresses has many more
3715 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003716 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003717 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3718 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3719 "reg_save_area");
3720
3721 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003722 if (neededInt && neededSSE) {
3723 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003724 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003725 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003726 Address Tmp = CGF.CreateMemTemp(Ty);
3727 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003728 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003729 llvm::Type *TyLo = ST->getElementType(0);
3730 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003731 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003732 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003733 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3734 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003735 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3736 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003737 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3738 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003739
John McCall7f416cc2015-09-08 08:05:57 +00003740 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003741 // FIXME: Our choice of alignment here and below is probably pessimistic.
3742 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3743 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3744 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003745 CGF.Builder.CreateStore(V,
3746 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3747
3748 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003749 V = CGF.Builder.CreateAlignedLoad(
3750 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3751 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003752 CharUnits Offset = CharUnits::fromQuantity(
3753 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3754 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3755
3756 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003757 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003758 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3759 CharUnits::fromQuantity(8));
3760 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003761
3762 // Copy to a temporary if necessary to ensure the appropriate alignment.
3763 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003764 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003765 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003766 CharUnits TyAlign = SizeAlign.second;
3767
3768 // Copy into a temporary if the type is more aligned than the
3769 // register save area.
3770 if (TyAlign.getQuantity() > 8) {
3771 Address Tmp = CGF.CreateMemTemp(Ty);
3772 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003773 RegAddr = Tmp;
3774 }
John McCall7f416cc2015-09-08 08:05:57 +00003775
Chris Lattner0cf24192010-06-28 20:05:43 +00003776 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003777 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3778 CharUnits::fromQuantity(16));
3779 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003780 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003781 assert(neededSSE == 2 && "Invalid number of needed registers!");
3782 // SSE registers are spaced 16 bytes apart in the register save
3783 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003784 // The ABI isn't explicit about this, but it seems reasonable
3785 // to assume that the slots are 16-byte aligned, since the stack is
3786 // naturally 16-byte aligned and the prologue is expected to store
3787 // all the SSE registers to the RSA.
3788 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3789 CharUnits::fromQuantity(16));
3790 Address RegAddrHi =
3791 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3792 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003793 llvm::Type *DoubleTy = CGF.DoubleTy;
Serge Guelton1d993272017-05-09 19:31:30 +00003794 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003795 llvm::Value *V;
3796 Address Tmp = CGF.CreateMemTemp(Ty);
3797 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3798 V = CGF.Builder.CreateLoad(
3799 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3800 CGF.Builder.CreateStore(V,
3801 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3802 V = CGF.Builder.CreateLoad(
3803 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3804 CGF.Builder.CreateStore(V,
3805 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3806
3807 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003808 }
3809
3810 // AMD64-ABI 3.5.7p5: Step 5. Set:
3811 // l->gp_offset = l->gp_offset + num_gp * 8
3812 // l->fp_offset = l->fp_offset + num_fp * 16.
3813 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003814 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003815 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3816 gp_offset_p);
3817 }
3818 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003819 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003820 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3821 fp_offset_p);
3822 }
3823 CGF.EmitBranch(ContBlock);
3824
3825 // Emit code to load the value if it was passed in memory.
3826
3827 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003828 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003829
3830 // Return the appropriate result.
3831
3832 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003833 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3834 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003835 return ResAddr;
3836}
3837
Charles Davisc7d5c942015-09-17 20:55:33 +00003838Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3839 QualType Ty) const {
3840 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3841 CGF.getContext().getTypeInfoInChars(Ty),
3842 CharUnits::fromQuantity(8),
3843 /*allowHigherAlign*/ false);
3844}
3845
Erich Keane521ed962017-01-05 00:20:51 +00003846ABIArgInfo
3847WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3848 const ABIArgInfo &current) const {
3849 // Assumes vectorCall calling convention.
3850 const Type *Base = nullptr;
3851 uint64_t NumElts = 0;
3852
3853 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3854 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3855 FreeSSERegs -= NumElts;
3856 return getDirectX86Hva();
3857 }
3858 return current;
3859}
3860
Reid Kleckner80944df2014-10-31 22:00:51 +00003861ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003862 bool IsReturnType, bool IsVectorCall,
3863 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003864
3865 if (Ty->isVoidType())
3866 return ABIArgInfo::getIgnore();
3867
3868 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3869 Ty = EnumTy->getDecl()->getIntegerType();
3870
Reid Kleckner80944df2014-10-31 22:00:51 +00003871 TypeInfo Info = getContext().getTypeInfo(Ty);
3872 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003873 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003874
Reid Kleckner9005f412014-05-02 00:51:20 +00003875 const RecordType *RT = Ty->getAs<RecordType>();
3876 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003877 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003878 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003879 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003880 }
3881
3882 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003883 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003884
Reid Kleckner9005f412014-05-02 00:51:20 +00003885 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003886
Reid Kleckner80944df2014-10-31 22:00:51 +00003887 const Type *Base = nullptr;
3888 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003889 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3890 // other targets.
3891 if ((IsVectorCall || IsRegCall) &&
3892 isHomogeneousAggregate(Ty, Base, NumElts)) {
3893 if (IsRegCall) {
3894 if (FreeSSERegs >= NumElts) {
3895 FreeSSERegs -= NumElts;
3896 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3897 return ABIArgInfo::getDirect();
3898 return ABIArgInfo::getExpand();
3899 }
3900 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3901 } else if (IsVectorCall) {
3902 if (FreeSSERegs >= NumElts &&
3903 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3904 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003905 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003906 } else if (IsReturnType) {
3907 return ABIArgInfo::getExpand();
3908 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3909 // HVAs are delayed and reclassified in the 2nd step.
3910 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3911 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003912 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003913 }
3914
Reid Klecknerec87fec2014-05-02 01:17:12 +00003915 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003916 // If the member pointer is represented by an LLVM int or ptr, pass it
3917 // directly.
3918 llvm::Type *LLTy = CGT.ConvertType(Ty);
3919 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3920 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003921 }
3922
Michael Kuperstein4f818702015-02-24 09:35:58 +00003923 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003924 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3925 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003926 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003927 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003928
Reid Kleckner9005f412014-05-02 00:51:20 +00003929 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003930 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003931 }
3932
Julien Lerouge10dcff82014-08-27 00:36:55 +00003933 // Bool type is always extended to the ABI, other builtin types are not
3934 // extended.
3935 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3936 if (BT && BT->getKind() == BuiltinType::Bool)
Alex Bradburye41a5e22018-01-12 20:08:16 +00003937 return ABIArgInfo::getExtend(Ty);
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003938
Reid Kleckner11a17192015-10-28 22:29:52 +00003939 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3940 // passes them indirectly through memory.
3941 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3942 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003943 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003944 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3945 }
3946
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003947 return ABIArgInfo::getDirect();
3948}
3949
Erich Keane521ed962017-01-05 00:20:51 +00003950void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3951 unsigned FreeSSERegs,
3952 bool IsVectorCall,
3953 bool IsRegCall) const {
3954 unsigned Count = 0;
3955 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003956 // Vectorcall in x64 only permits the first 6 arguments to be passed
3957 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003958 if (Count < VectorcallMaxParamNumAsReg)
3959 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3960 else {
3961 // Since these cannot be passed in registers, pretend no registers
3962 // are left.
3963 unsigned ZeroSSERegsAvail = 0;
3964 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3965 IsVectorCall, IsRegCall);
3966 }
3967 ++Count;
3968 }
3969
Erich Keane521ed962017-01-05 00:20:51 +00003970 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003971 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00003972 }
3973}
3974
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003975void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003976 bool IsVectorCall =
3977 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003978 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003979
Erich Keane757d3172016-11-02 18:29:35 +00003980 unsigned FreeSSERegs = 0;
3981 if (IsVectorCall) {
3982 // We can use up to 4 SSE return registers with vectorcall.
3983 FreeSSERegs = 4;
3984 } else if (IsRegCall) {
3985 // RegCall gives us 16 SSE registers.
3986 FreeSSERegs = 16;
3987 }
3988
Reid Kleckner80944df2014-10-31 22:00:51 +00003989 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00003990 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3991 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00003992
Erich Keane757d3172016-11-02 18:29:35 +00003993 if (IsVectorCall) {
3994 // We can use up to 6 SSE register parameters with vectorcall.
3995 FreeSSERegs = 6;
3996 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00003997 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00003998 FreeSSERegs = 16;
3999 }
4000
Erich Keane521ed962017-01-05 00:20:51 +00004001 if (IsVectorCall) {
4002 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4003 } else {
4004 for (auto &I : FI.arguments())
4005 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4006 }
4007
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004008}
4009
John McCall7f416cc2015-09-08 08:05:57 +00004010Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4011 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004012
4013 bool IsIndirect = false;
4014
4015 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4016 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4017 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4018 uint64_t Width = getContext().getTypeSize(Ty);
4019 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4020 }
4021
4022 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004023 CGF.getContext().getTypeInfoInChars(Ty),
4024 CharUnits::fromQuantity(8),
4025 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004026}
Chris Lattner0cf24192010-06-28 20:05:43 +00004027
John McCallea8d8bb2010-03-11 00:10:12 +00004028// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004029namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004030/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4031class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004032 bool IsSoftFloatABI;
4033
4034 CharUnits getParamTypeAlignment(QualType Ty) const;
4035
John McCallea8d8bb2010-03-11 00:10:12 +00004036public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004037 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4038 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004039
John McCall7f416cc2015-09-08 08:05:57 +00004040 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4041 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004042};
4043
4044class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4045public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004046 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4047 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004048
Craig Topper4f12f102014-03-12 06:41:41 +00004049 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004050 // This is recovered from gcc output.
4051 return 1; // r1 is the dedicated stack pointer
4052 }
4053
4054 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004055 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004056};
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004057}
John McCallea8d8bb2010-03-11 00:10:12 +00004058
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004059CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4060 // Complex types are passed just like their elements
4061 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4062 Ty = CTy->getElementType();
4063
4064 if (Ty->isVectorType())
4065 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4066 : 4);
4067
4068 // For single-element float/vector structs, we consider the whole type
4069 // to have the same alignment requirements as its single element.
4070 const Type *AlignTy = nullptr;
4071 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4072 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4073 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4074 (BT && BT->isFloatingPoint()))
4075 AlignTy = EltType;
4076 }
4077
4078 if (AlignTy)
4079 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4080 return CharUnits::fromQuantity(4);
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004081}
John McCallea8d8bb2010-03-11 00:10:12 +00004082
James Y Knight29b5f082016-02-24 02:59:33 +00004083// TODO: this implementation is now likely redundant with
4084// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004085Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4086 QualType Ty) const {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004087 if (getTarget().getTriple().isOSDarwin()) {
4088 auto TI = getContext().getTypeInfoInChars(Ty);
4089 TI.second = getParamTypeAlignment(Ty);
4090
4091 CharUnits SlotSize = CharUnits::fromQuantity(4);
4092 return emitVoidPtrVAArg(CGF, VAList, Ty,
4093 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4094 /*AllowHigherAlign=*/true);
4095 }
4096
Roman Divacky039b9702016-02-20 08:31:24 +00004097 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004098 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4099 // TODO: Implement this. For now ignore.
4100 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004101 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004102 }
4103
John McCall7f416cc2015-09-08 08:05:57 +00004104 // struct __va_list_tag {
4105 // unsigned char gpr;
4106 // unsigned char fpr;
4107 // unsigned short reserved;
4108 // void *overflow_arg_area;
4109 // void *reg_save_area;
4110 // };
4111
Roman Divacky8a12d842014-11-03 18:32:54 +00004112 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004113 bool isInt =
4114 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004115 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004116
4117 // All aggregates are passed indirectly? That doesn't seem consistent
4118 // with the argument-lowering code.
4119 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004120
4121 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004122
4123 // The calling convention either uses 1-2 GPRs or 1 FPR.
4124 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004125 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004126 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4127 } else {
4128 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004129 }
John McCall7f416cc2015-09-08 08:05:57 +00004130
4131 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4132
4133 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004134 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004135 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4136 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4137 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004138
Eric Christopher7565e0d2015-05-29 23:09:49 +00004139 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004140 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004141
4142 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4143 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4144 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4145
4146 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4147
John McCall7f416cc2015-09-08 08:05:57 +00004148 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4149 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004150
John McCall7f416cc2015-09-08 08:05:57 +00004151 // Case 1: consume registers.
4152 Address RegAddr = Address::invalid();
4153 {
4154 CGF.EmitBlock(UsingRegs);
4155
4156 Address RegSaveAreaPtr =
4157 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4158 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4159 CharUnits::fromQuantity(8));
4160 assert(RegAddr.getElementType() == CGF.Int8Ty);
4161
4162 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004163 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004164 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4165 CharUnits::fromQuantity(32));
4166 }
4167
4168 // Get the address of the saved value by scaling the number of
4169 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004170 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004171 llvm::Value *RegOffset =
4172 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4173 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4174 RegAddr.getPointer(), RegOffset),
4175 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4176 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4177
4178 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004179 NumRegs =
4180 Builder.CreateAdd(NumRegs,
4181 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004182 Builder.CreateStore(NumRegs, NumRegsAddr);
4183
4184 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004185 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004186
John McCall7f416cc2015-09-08 08:05:57 +00004187 // Case 2: consume space in the overflow area.
4188 Address MemAddr = Address::invalid();
4189 {
4190 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004191
Roman Divacky039b9702016-02-20 08:31:24 +00004192 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4193
John McCall7f416cc2015-09-08 08:05:57 +00004194 // Everything in the overflow area is rounded up to a size of at least 4.
4195 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4196
4197 CharUnits Size;
4198 if (!isIndirect) {
4199 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004200 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004201 } else {
4202 Size = CGF.getPointerSize();
4203 }
4204
4205 Address OverflowAreaAddr =
4206 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004207 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004208 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004209 // Round up address of argument to alignment
4210 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4211 if (Align > OverflowAreaAlign) {
4212 llvm::Value *Ptr = OverflowArea.getPointer();
4213 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4214 Align);
4215 }
4216
John McCall7f416cc2015-09-08 08:05:57 +00004217 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4218
4219 // Increase the overflow area.
4220 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4221 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4222 CGF.EmitBranch(Cont);
4223 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004224
4225 CGF.EmitBlock(Cont);
4226
John McCall7f416cc2015-09-08 08:05:57 +00004227 // Merge the cases with a phi.
4228 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4229 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004230
John McCall7f416cc2015-09-08 08:05:57 +00004231 // Load the pointer if the argument was passed indirectly.
4232 if (isIndirect) {
4233 Result = Address(Builder.CreateLoad(Result, "aggr"),
4234 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004235 }
4236
4237 return Result;
4238}
4239
John McCallea8d8bb2010-03-11 00:10:12 +00004240bool
4241PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4242 llvm::Value *Address) const {
4243 // This is calculated from the LLVM and GCC tables and verified
4244 // against gcc output. AFAIK all ABIs use the same encoding.
4245
4246 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004247
Chris Lattnerece04092012-02-07 00:39:47 +00004248 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004249 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4250 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4251 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4252
4253 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004254 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004255
4256 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004257 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004258
4259 // 64-76 are various 4-byte special-purpose registers:
4260 // 64: mq
4261 // 65: lr
4262 // 66: ctr
4263 // 67: ap
4264 // 68-75 cr0-7
4265 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004266 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004267
4268 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004269 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004270
4271 // 109: vrsave
4272 // 110: vscr
4273 // 111: spe_acc
4274 // 112: spefscr
4275 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004276 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004277
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004278 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004279}
4280
Roman Divackyd966e722012-05-09 18:22:46 +00004281// PowerPC-64
4282
4283namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004284/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004285class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004286public:
4287 enum ABIKind {
4288 ELFv1 = 0,
4289 ELFv2
4290 };
4291
4292private:
4293 static const unsigned GPRBits = 64;
4294 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004295 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004296 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004297
4298 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4299 // will be passed in a QPX register.
4300 bool IsQPXVectorTy(const Type *Ty) const {
4301 if (!HasQPX)
4302 return false;
4303
4304 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4305 unsigned NumElements = VT->getNumElements();
4306 if (NumElements == 1)
4307 return false;
4308
4309 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4310 if (getContext().getTypeSize(Ty) <= 256)
4311 return true;
4312 } else if (VT->getElementType()->
4313 isSpecificBuiltinType(BuiltinType::Float)) {
4314 if (getContext().getTypeSize(Ty) <= 128)
4315 return true;
4316 }
4317 }
4318
4319 return false;
4320 }
4321
4322 bool IsQPXVectorTy(QualType Ty) const {
4323 return IsQPXVectorTy(Ty.getTypePtr());
4324 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004325
4326public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004327 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4328 bool SoftFloatABI)
4329 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4330 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004331
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004332 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004333 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004334
4335 ABIArgInfo classifyReturnType(QualType RetTy) const;
4336 ABIArgInfo classifyArgumentType(QualType Ty) const;
4337
Reid Klecknere9f6a712014-10-31 17:10:41 +00004338 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4339 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4340 uint64_t Members) const override;
4341
Bill Schmidt84d37792012-10-12 19:26:17 +00004342 // TODO: We can add more logic to computeInfo to improve performance.
4343 // Example: For aggregate arguments that fit in a register, we could
4344 // use getDirectInReg (as is done below for structs containing a single
4345 // floating-point value) to avoid pushing them to memory on function
4346 // entry. This would require changing the logic in PPCISelLowering
4347 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004348 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004349 if (!getCXXABI().classifyReturnType(FI))
4350 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004351 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004352 // We rely on the default argument classification for the most part.
4353 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004354 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004355 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004356 if (T) {
4357 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004358 if (IsQPXVectorTy(T) ||
4359 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004360 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004361 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004362 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004363 continue;
4364 }
4365 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004366 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004367 }
4368 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004369
John McCall7f416cc2015-09-08 08:05:57 +00004370 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4371 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004372};
4373
4374class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004375
Bill Schmidt25cb3492012-10-03 19:18:57 +00004376public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004377 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004378 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4379 bool SoftFloatABI)
4380 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4381 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004382
Craig Topper4f12f102014-03-12 06:41:41 +00004383 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004384 // This is recovered from gcc output.
4385 return 1; // r1 is the dedicated stack pointer
4386 }
4387
4388 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004389 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004390};
4391
Roman Divackyd966e722012-05-09 18:22:46 +00004392class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4393public:
4394 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4395
Craig Topper4f12f102014-03-12 06:41:41 +00004396 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004397 // This is recovered from gcc output.
4398 return 1; // r1 is the dedicated stack pointer
4399 }
4400
4401 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004402 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004403};
4404
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004405}
Roman Divackyd966e722012-05-09 18:22:46 +00004406
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004407// Return true if the ABI requires Ty to be passed sign- or zero-
4408// extended to 64 bits.
4409bool
4410PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4411 // Treat an enum type as its underlying type.
4412 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4413 Ty = EnumTy->getDecl()->getIntegerType();
4414
4415 // Promotable integer types are required to be promoted by the ABI.
4416 if (Ty->isPromotableIntegerType())
4417 return true;
4418
4419 // In addition to the usual promotable integer types, we also need to
4420 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4421 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4422 switch (BT->getKind()) {
4423 case BuiltinType::Int:
4424 case BuiltinType::UInt:
4425 return true;
4426 default:
4427 break;
4428 }
4429
4430 return false;
4431}
4432
John McCall7f416cc2015-09-08 08:05:57 +00004433/// isAlignedParamType - Determine whether a type requires 16-byte or
4434/// higher alignment in the parameter area. Always returns at least 8.
4435CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004436 // Complex types are passed just like their elements.
4437 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4438 Ty = CTy->getElementType();
4439
4440 // Only vector types of size 16 bytes need alignment (larger types are
4441 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004442 if (IsQPXVectorTy(Ty)) {
4443 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004444 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004445
John McCall7f416cc2015-09-08 08:05:57 +00004446 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004447 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004448 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004449 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004450
4451 // For single-element float/vector structs, we consider the whole type
4452 // to have the same alignment requirements as its single element.
4453 const Type *AlignAsType = nullptr;
4454 const Type *EltType = isSingleElementStruct(Ty, getContext());
4455 if (EltType) {
4456 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004457 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004458 getContext().getTypeSize(EltType) == 128) ||
4459 (BT && BT->isFloatingPoint()))
4460 AlignAsType = EltType;
4461 }
4462
Ulrich Weigandb7122372014-07-21 00:48:09 +00004463 // Likewise for ELFv2 homogeneous aggregates.
4464 const Type *Base = nullptr;
4465 uint64_t Members = 0;
4466 if (!AlignAsType && Kind == ELFv2 &&
4467 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4468 AlignAsType = Base;
4469
Ulrich Weigand581badc2014-07-10 17:20:07 +00004470 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004471 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4472 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004473 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004474
John McCall7f416cc2015-09-08 08:05:57 +00004475 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004476 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004477 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004478 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004479
4480 // Otherwise, we only need alignment for any aggregate type that
4481 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004482 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4483 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004484 return CharUnits::fromQuantity(32);
4485 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004486 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004487
John McCall7f416cc2015-09-08 08:05:57 +00004488 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004489}
4490
Ulrich Weigandb7122372014-07-21 00:48:09 +00004491/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4492/// aggregate. Base is set to the base element type, and Members is set
4493/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004494bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4495 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004496 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4497 uint64_t NElements = AT->getSize().getZExtValue();
4498 if (NElements == 0)
4499 return false;
4500 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4501 return false;
4502 Members *= NElements;
4503 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4504 const RecordDecl *RD = RT->getDecl();
4505 if (RD->hasFlexibleArrayMember())
4506 return false;
4507
4508 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004509
4510 // If this is a C++ record, check the bases first.
4511 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4512 for (const auto &I : CXXRD->bases()) {
4513 // Ignore empty records.
4514 if (isEmptyRecord(getContext(), I.getType(), true))
4515 continue;
4516
4517 uint64_t FldMembers;
4518 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4519 return false;
4520
4521 Members += FldMembers;
4522 }
4523 }
4524
Ulrich Weigandb7122372014-07-21 00:48:09 +00004525 for (const auto *FD : RD->fields()) {
4526 // Ignore (non-zero arrays of) empty records.
4527 QualType FT = FD->getType();
4528 while (const ConstantArrayType *AT =
4529 getContext().getAsConstantArrayType(FT)) {
4530 if (AT->getSize().getZExtValue() == 0)
4531 return false;
4532 FT = AT->getElementType();
4533 }
4534 if (isEmptyRecord(getContext(), FT, true))
4535 continue;
4536
4537 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4538 if (getContext().getLangOpts().CPlusPlus &&
4539 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4540 continue;
4541
4542 uint64_t FldMembers;
4543 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4544 return false;
4545
4546 Members = (RD->isUnion() ?
4547 std::max(Members, FldMembers) : Members + FldMembers);
4548 }
4549
4550 if (!Base)
4551 return false;
4552
4553 // Ensure there is no padding.
4554 if (getContext().getTypeSize(Base) * Members !=
4555 getContext().getTypeSize(Ty))
4556 return false;
4557 } else {
4558 Members = 1;
4559 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4560 Members = 2;
4561 Ty = CT->getElementType();
4562 }
4563
Reid Klecknere9f6a712014-10-31 17:10:41 +00004564 // Most ABIs only support float, double, and some vector type widths.
4565 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004566 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004567
4568 // The base type must be the same for all members. Types that
4569 // agree in both total size and mode (float vs. vector) are
4570 // treated as being equivalent here.
4571 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004572 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004573 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004574 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4575 // so make sure to widen it explicitly.
4576 if (const VectorType *VT = Base->getAs<VectorType>()) {
4577 QualType EltTy = VT->getElementType();
4578 unsigned NumElements =
4579 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4580 Base = getContext()
4581 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4582 .getTypePtr();
4583 }
4584 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004585
4586 if (Base->isVectorType() != TyPtr->isVectorType() ||
4587 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4588 return false;
4589 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004590 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4591}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004592
Reid Klecknere9f6a712014-10-31 17:10:41 +00004593bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4594 // Homogeneous aggregates for ELFv2 must have base types of float,
4595 // double, long double, or 128-bit vectors.
4596 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4597 if (BT->getKind() == BuiltinType::Float ||
4598 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004599 BT->getKind() == BuiltinType::LongDouble) {
4600 if (IsSoftFloatABI)
4601 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004602 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004603 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004604 }
4605 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004606 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004607 return true;
4608 }
4609 return false;
4610}
4611
4612bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4613 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004614 // Vector types require one register, floating point types require one
4615 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004616 uint32_t NumRegs =
4617 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004618
4619 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004620 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004621}
4622
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004623ABIArgInfo
4624PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004625 Ty = useFirstFieldIfTransparentUnion(Ty);
4626
Bill Schmidt90b22c92012-11-27 02:46:43 +00004627 if (Ty->isAnyComplexType())
4628 return ABIArgInfo::getDirect();
4629
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004630 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4631 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004632 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004633 uint64_t Size = getContext().getTypeSize(Ty);
4634 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004635 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004636 else if (Size < 128) {
4637 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4638 return ABIArgInfo::getDirect(CoerceTy);
4639 }
4640 }
4641
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004642 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004643 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004644 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004645
John McCall7f416cc2015-09-08 08:05:57 +00004646 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4647 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004648
4649 // ELFv2 homogeneous aggregates are passed as array types.
4650 const Type *Base = nullptr;
4651 uint64_t Members = 0;
4652 if (Kind == ELFv2 &&
4653 isHomogeneousAggregate(Ty, Base, Members)) {
4654 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4655 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4656 return ABIArgInfo::getDirect(CoerceTy);
4657 }
4658
Ulrich Weigand601957f2014-07-21 00:56:36 +00004659 // If an aggregate may end up fully in registers, we do not
4660 // use the ByVal method, but pass the aggregate as array.
4661 // This is usually beneficial since we avoid forcing the
4662 // back-end to store the argument to memory.
4663 uint64_t Bits = getContext().getTypeSize(Ty);
4664 if (Bits > 0 && Bits <= 8 * GPRBits) {
4665 llvm::Type *CoerceTy;
4666
4667 // Types up to 8 bytes are passed as integer type (which will be
4668 // properly aligned in the argument save area doubleword).
4669 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004670 CoerceTy =
4671 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004672 // Larger types are passed as arrays, with the base type selected
4673 // according to the required alignment in the save area.
4674 else {
4675 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004676 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004677 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4678 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4679 }
4680
4681 return ABIArgInfo::getDirect(CoerceTy);
4682 }
4683
Ulrich Weigandb7122372014-07-21 00:48:09 +00004684 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004685 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4686 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004687 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004688 }
4689
Alex Bradburye41a5e22018-01-12 20:08:16 +00004690 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4691 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004692}
4693
4694ABIArgInfo
4695PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4696 if (RetTy->isVoidType())
4697 return ABIArgInfo::getIgnore();
4698
Bill Schmidta3d121c2012-12-17 04:20:17 +00004699 if (RetTy->isAnyComplexType())
4700 return ABIArgInfo::getDirect();
4701
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004702 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4703 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004704 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004705 uint64_t Size = getContext().getTypeSize(RetTy);
4706 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004707 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004708 else if (Size < 128) {
4709 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4710 return ABIArgInfo::getDirect(CoerceTy);
4711 }
4712 }
4713
Ulrich Weigandb7122372014-07-21 00:48:09 +00004714 if (isAggregateTypeForABI(RetTy)) {
4715 // ELFv2 homogeneous aggregates are returned as array types.
4716 const Type *Base = nullptr;
4717 uint64_t Members = 0;
4718 if (Kind == ELFv2 &&
4719 isHomogeneousAggregate(RetTy, Base, Members)) {
4720 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4721 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4722 return ABIArgInfo::getDirect(CoerceTy);
4723 }
4724
4725 // ELFv2 small aggregates are returned in up to two registers.
4726 uint64_t Bits = getContext().getTypeSize(RetTy);
4727 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4728 if (Bits == 0)
4729 return ABIArgInfo::getIgnore();
4730
4731 llvm::Type *CoerceTy;
4732 if (Bits > GPRBits) {
4733 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004734 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004735 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004736 CoerceTy =
4737 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004738 return ABIArgInfo::getDirect(CoerceTy);
4739 }
4740
4741 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004742 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004743 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004744
Alex Bradburye41a5e22018-01-12 20:08:16 +00004745 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4746 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004747}
4748
Bill Schmidt25cb3492012-10-03 19:18:57 +00004749// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004750Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4751 QualType Ty) const {
4752 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4753 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004754
John McCall7f416cc2015-09-08 08:05:57 +00004755 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004756
Bill Schmidt924c4782013-01-14 17:45:36 +00004757 // If we have a complex type and the base type is smaller than 8 bytes,
4758 // the ABI calls for the real and imaginary parts to be right-adjusted
4759 // in separate doublewords. However, Clang expects us to produce a
4760 // pointer to a structure with the two parts packed tightly. So generate
4761 // loads of the real and imaginary parts relative to the va_list pointer,
4762 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004763 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4764 CharUnits EltSize = TypeInfo.first / 2;
4765 if (EltSize < SlotSize) {
4766 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4767 SlotSize * 2, SlotSize,
4768 SlotSize, /*AllowHigher*/ true);
4769
4770 Address RealAddr = Addr;
4771 Address ImagAddr = RealAddr;
4772 if (CGF.CGM.getDataLayout().isBigEndian()) {
4773 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4774 SlotSize - EltSize);
4775 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4776 2 * SlotSize - EltSize);
4777 } else {
4778 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4779 }
4780
4781 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4782 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4783 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4784 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4785 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4786
4787 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4788 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4789 /*init*/ true);
4790 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004791 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004792 }
4793
John McCall7f416cc2015-09-08 08:05:57 +00004794 // Otherwise, just use the general rule.
4795 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4796 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004797}
4798
4799static bool
4800PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4801 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004802 // This is calculated from the LLVM and GCC tables and verified
4803 // against gcc output. AFAIK all ABIs use the same encoding.
4804
4805 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4806
4807 llvm::IntegerType *i8 = CGF.Int8Ty;
4808 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4809 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4810 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4811
4812 // 0-31: r0-31, the 8-byte general-purpose registers
4813 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4814
4815 // 32-63: fp0-31, the 8-byte floating-point registers
4816 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4817
Hal Finkel84832a72016-08-30 02:38:34 +00004818 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004819 // 64: mq
4820 // 65: lr
4821 // 66: ctr
4822 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004823 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4824
4825 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004826 // 68-75 cr0-7
4827 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004828 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004829
4830 // 77-108: v0-31, the 16-byte vector registers
4831 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4832
4833 // 109: vrsave
4834 // 110: vscr
4835 // 111: spe_acc
4836 // 112: spefscr
4837 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004838 // 114: tfhar
4839 // 115: tfiar
4840 // 116: texasr
4841 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004842
4843 return false;
4844}
John McCallea8d8bb2010-03-11 00:10:12 +00004845
Bill Schmidt25cb3492012-10-03 19:18:57 +00004846bool
4847PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4848 CodeGen::CodeGenFunction &CGF,
4849 llvm::Value *Address) const {
4850
4851 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4852}
4853
4854bool
4855PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4856 llvm::Value *Address) const {
4857
4858 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4859}
4860
Chris Lattner0cf24192010-06-28 20:05:43 +00004861//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004862// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004863//===----------------------------------------------------------------------===//
4864
4865namespace {
4866
John McCall12f23522016-04-04 18:33:08 +00004867class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004868public:
4869 enum ABIKind {
4870 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004871 DarwinPCS,
4872 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004873 };
4874
4875private:
4876 ABIKind Kind;
4877
4878public:
John McCall12f23522016-04-04 18:33:08 +00004879 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4880 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004881
4882private:
4883 ABIKind getABIKind() const { return Kind; }
4884 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4885
4886 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004887 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004888 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4889 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4890 uint64_t Members) const override;
4891
Tim Northovera2ee4332014-03-29 15:09:45 +00004892 bool isIllegalVectorType(QualType Ty) const;
4893
David Blaikie1cbb9712014-11-14 19:09:44 +00004894 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004895 if (!getCXXABI().classifyReturnType(FI))
4896 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004897
Tim Northoverb047bfa2014-11-27 21:02:49 +00004898 for (auto &it : FI.arguments())
4899 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004900 }
4901
John McCall7f416cc2015-09-08 08:05:57 +00004902 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4903 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004904
John McCall7f416cc2015-09-08 08:05:57 +00004905 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4906 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004907
John McCall7f416cc2015-09-08 08:05:57 +00004908 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4909 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004910 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4911 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4912 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004913 }
John McCall12f23522016-04-04 18:33:08 +00004914
Martin Storsjo502de222017-07-13 17:59:14 +00004915 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4916 QualType Ty) const override;
4917
John McCall56331e22018-01-07 06:28:49 +00004918 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00004919 bool asReturnValue) const override {
4920 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4921 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004922 bool isSwiftErrorInRegister() const override {
4923 return true;
4924 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004925
4926 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4927 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004928};
4929
Tim Northover573cbee2014-05-24 12:52:07 +00004930class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004931public:
Tim Northover573cbee2014-05-24 12:52:07 +00004932 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4933 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004934
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004935 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00004936 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004937 }
4938
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004939 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4940 return 31;
4941 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004942
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004943 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004944};
Martin Storsjo1c8af272017-07-20 05:47:06 +00004945
4946class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4947public:
4948 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4949 : AArch64TargetCodeGenInfo(CGT, K) {}
4950
4951 void getDependentLibraryOption(llvm::StringRef Lib,
4952 llvm::SmallString<24> &Opt) const override {
4953 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4954 }
4955
4956 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4957 llvm::SmallString<32> &Opt) const override {
4958 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4959 }
4960};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004961}
Tim Northovera2ee4332014-03-29 15:09:45 +00004962
Tim Northoverb047bfa2014-11-27 21:02:49 +00004963ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004964 Ty = useFirstFieldIfTransparentUnion(Ty);
4965
Tim Northovera2ee4332014-03-29 15:09:45 +00004966 // Handle illegal vector types here.
4967 if (isIllegalVectorType(Ty)) {
4968 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004969 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004970 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004971 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4972 return ABIArgInfo::getDirect(ResType);
4973 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004974 if (Size <= 32) {
4975 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004976 return ABIArgInfo::getDirect(ResType);
4977 }
4978 if (Size == 64) {
4979 llvm::Type *ResType =
4980 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004981 return ABIArgInfo::getDirect(ResType);
4982 }
4983 if (Size == 128) {
4984 llvm::Type *ResType =
4985 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004986 return ABIArgInfo::getDirect(ResType);
4987 }
John McCall7f416cc2015-09-08 08:05:57 +00004988 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004989 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004990
4991 if (!isAggregateTypeForABI(Ty)) {
4992 // Treat an enum type as its underlying type.
4993 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4994 Ty = EnumTy->getDecl()->getIntegerType();
4995
Tim Northovera2ee4332014-03-29 15:09:45 +00004996 return (Ty->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00004997 ? ABIArgInfo::getExtend(Ty)
Tim Northovera2ee4332014-03-29 15:09:45 +00004998 : ABIArgInfo::getDirect());
4999 }
5000
5001 // Structures with either a non-trivial destructor or a non-trivial
5002 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00005003 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005004 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5005 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00005006 }
5007
5008 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5009 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00005010 uint64_t Size = getContext().getTypeSize(Ty);
5011 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5012 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005013 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5014 return ABIArgInfo::getIgnore();
5015
Tim Northover23bcad22017-05-05 22:36:06 +00005016 // GNU C mode. The only argument that gets ignored is an empty one with size
5017 // 0.
5018 if (IsEmpty && Size == 0)
5019 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00005020 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5021 }
5022
5023 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005024 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005025 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005026 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005027 return ABIArgInfo::getDirect(
5028 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005029 }
5030
5031 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005032 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005033 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5034 // same size and alignment.
5035 if (getTarget().isRenderScriptTarget()) {
5036 return coerceToIntArray(Ty, getContext(), getVMContext());
5037 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00005038 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005039 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005040
Tim Northovera2ee4332014-03-29 15:09:45 +00005041 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5042 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005043 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005044 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5045 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5046 }
5047 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5048 }
5049
John McCall7f416cc2015-09-08 08:05:57 +00005050 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005051}
5052
Tim Northover573cbee2014-05-24 12:52:07 +00005053ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005054 if (RetTy->isVoidType())
5055 return ABIArgInfo::getIgnore();
5056
5057 // Large vector types should be returned via memory.
5058 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005059 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005060
5061 if (!isAggregateTypeForABI(RetTy)) {
5062 // Treat an enum type as its underlying type.
5063 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5064 RetTy = EnumTy->getDecl()->getIntegerType();
5065
Tim Northover4dab6982014-04-18 13:46:08 +00005066 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005067 ? ABIArgInfo::getExtend(RetTy)
Tim Northover4dab6982014-04-18 13:46:08 +00005068 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005069 }
5070
Tim Northover23bcad22017-05-05 22:36:06 +00005071 uint64_t Size = getContext().getTypeSize(RetTy);
5072 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005073 return ABIArgInfo::getIgnore();
5074
Craig Topper8a13c412014-05-21 05:09:00 +00005075 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005076 uint64_t Members = 0;
5077 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005078 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5079 return ABIArgInfo::getDirect();
5080
5081 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005082 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005083 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5084 // same size and alignment.
5085 if (getTarget().isRenderScriptTarget()) {
5086 return coerceToIntArray(RetTy, getContext(), getVMContext());
5087 }
Pete Cooper635b5092015-04-17 22:16:24 +00005088 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005089 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005090
5091 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5092 // For aggregates with 16-byte alignment, we use i128.
5093 if (Alignment < 128 && Size == 128) {
5094 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5095 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5096 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005097 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5098 }
5099
John McCall7f416cc2015-09-08 08:05:57 +00005100 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005101}
5102
Tim Northover573cbee2014-05-24 12:52:07 +00005103/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5104bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005105 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5106 // Check whether VT is legal.
5107 unsigned NumElements = VT->getNumElements();
5108 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005109 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005110 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005111 return true;
5112 return Size != 64 && (Size != 128 || NumElements == 1);
5113 }
5114 return false;
5115}
5116
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005117bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5118 llvm::Type *eltTy,
5119 unsigned elts) const {
5120 if (!llvm::isPowerOf2_32(elts))
5121 return false;
5122 if (totalSize.getQuantity() != 8 &&
5123 (totalSize.getQuantity() != 16 || elts == 1))
5124 return false;
5125 return true;
5126}
5127
Reid Klecknere9f6a712014-10-31 17:10:41 +00005128bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5129 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5130 // point type or a short-vector type. This is the same as the 32-bit ABI,
5131 // but with the difference that any floating-point type is allowed,
5132 // including __fp16.
5133 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5134 if (BT->isFloatingPoint())
5135 return true;
5136 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5137 unsigned VecSize = getContext().getTypeSize(VT);
5138 if (VecSize == 64 || VecSize == 128)
5139 return true;
5140 }
5141 return false;
5142}
5143
5144bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5145 uint64_t Members) const {
5146 return Members <= 4;
5147}
5148
John McCall7f416cc2015-09-08 08:05:57 +00005149Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005150 QualType Ty,
5151 CodeGenFunction &CGF) const {
5152 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005153 bool IsIndirect = AI.isIndirect();
5154
Tim Northoverb047bfa2014-11-27 21:02:49 +00005155 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5156 if (IsIndirect)
5157 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5158 else if (AI.getCoerceToType())
5159 BaseTy = AI.getCoerceToType();
5160
5161 unsigned NumRegs = 1;
5162 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5163 BaseTy = ArrTy->getElementType();
5164 NumRegs = ArrTy->getNumElements();
5165 }
5166 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5167
Tim Northovera2ee4332014-03-29 15:09:45 +00005168 // The AArch64 va_list type and handling is specified in the Procedure Call
5169 // Standard, section B.4:
5170 //
5171 // struct {
5172 // void *__stack;
5173 // void *__gr_top;
5174 // void *__vr_top;
5175 // int __gr_offs;
5176 // int __vr_offs;
5177 // };
5178
5179 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5180 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5181 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5182 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005183
John McCall7f416cc2015-09-08 08:05:57 +00005184 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5185 CharUnits TyAlign = TyInfo.second;
5186
5187 Address reg_offs_p = Address::invalid();
5188 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005189 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005190 CharUnits reg_top_offset;
5191 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005192 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005193 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005194 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005195 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5196 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005197 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5198 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005199 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005200 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005201 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005202 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005203 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005204 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5205 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005206 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5207 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005208 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005209 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005210 }
5211
5212 //=======================================
5213 // Find out where argument was passed
5214 //=======================================
5215
5216 // If reg_offs >= 0 we're already using the stack for this type of
5217 // argument. We don't want to keep updating reg_offs (in case it overflows,
5218 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5219 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005220 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005221 UsingStack = CGF.Builder.CreateICmpSGE(
5222 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5223
5224 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5225
5226 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005227 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005228 CGF.EmitBlock(MaybeRegBlock);
5229
5230 // Integer arguments may need to correct register alignment (for example a
5231 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5232 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005233 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5234 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005235
5236 reg_offs = CGF.Builder.CreateAdd(
5237 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5238 "align_regoffs");
5239 reg_offs = CGF.Builder.CreateAnd(
5240 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5241 "aligned_regoffs");
5242 }
5243
5244 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005245 // The fact that this is done unconditionally reflects the fact that
5246 // allocating an argument to the stack also uses up all the remaining
5247 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005248 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005249 NewOffset = CGF.Builder.CreateAdd(
5250 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5251 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5252
5253 // Now we're in a position to decide whether this argument really was in
5254 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005255 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005256 InRegs = CGF.Builder.CreateICmpSLE(
5257 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5258
5259 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5260
5261 //=======================================
5262 // Argument was in registers
5263 //=======================================
5264
5265 // Now we emit the code for if the argument was originally passed in
5266 // registers. First start the appropriate block:
5267 CGF.EmitBlock(InRegBlock);
5268
John McCall7f416cc2015-09-08 08:05:57 +00005269 llvm::Value *reg_top = nullptr;
5270 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5271 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005272 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005273 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5274 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5275 Address RegAddr = Address::invalid();
5276 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005277
5278 if (IsIndirect) {
5279 // If it's been passed indirectly (actually a struct), whatever we find from
5280 // stored registers or on the stack will actually be a struct **.
5281 MemTy = llvm::PointerType::getUnqual(MemTy);
5282 }
5283
Craig Topper8a13c412014-05-21 05:09:00 +00005284 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005285 uint64_t NumMembers = 0;
5286 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005287 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005288 // Homogeneous aggregates passed in registers will have their elements split
5289 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5290 // qN+1, ...). We reload and store into a temporary local variable
5291 // contiguously.
5292 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005293 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005294 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5295 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005296 Address Tmp = CGF.CreateTempAlloca(HFATy,
5297 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005298
John McCall7f416cc2015-09-08 08:05:57 +00005299 // On big-endian platforms, the value will be right-aligned in its slot.
5300 int Offset = 0;
5301 if (CGF.CGM.getDataLayout().isBigEndian() &&
5302 BaseTyInfo.first.getQuantity() < 16)
5303 Offset = 16 - BaseTyInfo.first.getQuantity();
5304
Tim Northovera2ee4332014-03-29 15:09:45 +00005305 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005306 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5307 Address LoadAddr =
5308 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5309 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5310
5311 Address StoreAddr =
5312 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005313
5314 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5315 CGF.Builder.CreateStore(Elem, StoreAddr);
5316 }
5317
John McCall7f416cc2015-09-08 08:05:57 +00005318 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005319 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005320 // Otherwise the object is contiguous in memory.
5321
5322 // It might be right-aligned in its slot.
5323 CharUnits SlotSize = BaseAddr.getAlignment();
5324 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005325 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005326 TyInfo.first < SlotSize) {
5327 CharUnits Offset = SlotSize - TyInfo.first;
5328 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005329 }
5330
John McCall7f416cc2015-09-08 08:05:57 +00005331 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005332 }
5333
5334 CGF.EmitBranch(ContBlock);
5335
5336 //=======================================
5337 // Argument was on the stack
5338 //=======================================
5339 CGF.EmitBlock(OnStackBlock);
5340
John McCall7f416cc2015-09-08 08:05:57 +00005341 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5342 CharUnits::Zero(), "stack_p");
5343 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005344
John McCall7f416cc2015-09-08 08:05:57 +00005345 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005346 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005347 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5348 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005349
John McCall7f416cc2015-09-08 08:05:57 +00005350 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005351
John McCall7f416cc2015-09-08 08:05:57 +00005352 OnStackPtr = CGF.Builder.CreateAdd(
5353 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005354 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005355 OnStackPtr = CGF.Builder.CreateAnd(
5356 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005357 "align_stack");
5358
John McCall7f416cc2015-09-08 08:05:57 +00005359 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005360 }
John McCall7f416cc2015-09-08 08:05:57 +00005361 Address OnStackAddr(OnStackPtr,
5362 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005363
John McCall7f416cc2015-09-08 08:05:57 +00005364 // All stack slots are multiples of 8 bytes.
5365 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5366 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005367 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005368 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005369 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005370 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005371
John McCall7f416cc2015-09-08 08:05:57 +00005372 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005373 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005374 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005375
5376 // Write the new value of __stack for the next call to va_arg
5377 CGF.Builder.CreateStore(NewStack, stack_p);
5378
5379 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005380 TyInfo.first < StackSlotSize) {
5381 CharUnits Offset = StackSlotSize - TyInfo.first;
5382 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005383 }
5384
John McCall7f416cc2015-09-08 08:05:57 +00005385 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005386
5387 CGF.EmitBranch(ContBlock);
5388
5389 //=======================================
5390 // Tidy up
5391 //=======================================
5392 CGF.EmitBlock(ContBlock);
5393
John McCall7f416cc2015-09-08 08:05:57 +00005394 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5395 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005396
5397 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005398 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5399 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005400
5401 return ResAddr;
5402}
5403
John McCall7f416cc2015-09-08 08:05:57 +00005404Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5405 CodeGenFunction &CGF) const {
5406 // The backend's lowering doesn't support va_arg for aggregates or
5407 // illegal vector types. Lower VAArg here for these cases and use
5408 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005409 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005410 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005411
John McCall7f416cc2015-09-08 08:05:57 +00005412 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005413
John McCall7f416cc2015-09-08 08:05:57 +00005414 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005415 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005416 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5417 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5418 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005419 }
5420
John McCall7f416cc2015-09-08 08:05:57 +00005421 // The size of the actual thing passed, which might end up just
5422 // being a pointer for indirect types.
5423 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5424
5425 // Arguments bigger than 16 bytes which aren't homogeneous
5426 // aggregates should be passed indirectly.
5427 bool IsIndirect = false;
5428 if (TyInfo.first.getQuantity() > 16) {
5429 const Type *Base = nullptr;
5430 uint64_t Members = 0;
5431 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005432 }
5433
John McCall7f416cc2015-09-08 08:05:57 +00005434 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5435 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005436}
5437
Martin Storsjo502de222017-07-13 17:59:14 +00005438Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5439 QualType Ty) const {
5440 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5441 CGF.getContext().getTypeInfoInChars(Ty),
5442 CharUnits::fromQuantity(8),
5443 /*allowHigherAlign*/ false);
5444}
5445
Tim Northovera2ee4332014-03-29 15:09:45 +00005446//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005447// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005448//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005449
5450namespace {
5451
John McCall12f23522016-04-04 18:33:08 +00005452class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005453public:
5454 enum ABIKind {
5455 APCS = 0,
5456 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005457 AAPCS_VFP = 2,
5458 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005459 };
5460
5461private:
5462 ABIKind Kind;
5463
5464public:
John McCall12f23522016-04-04 18:33:08 +00005465 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5466 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005467 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005468 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005469
John McCall3480ef22011-08-30 01:42:09 +00005470 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005471 switch (getTarget().getTriple().getEnvironment()) {
5472 case llvm::Triple::Android:
5473 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005474 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005475 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005476 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005477 case llvm::Triple::MuslEABI:
5478 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005479 return true;
5480 default:
5481 return false;
5482 }
John McCall3480ef22011-08-30 01:42:09 +00005483 }
5484
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005485 bool isEABIHF() const {
5486 switch (getTarget().getTriple().getEnvironment()) {
5487 case llvm::Triple::EABIHF:
5488 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005489 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005490 return true;
5491 default:
5492 return false;
5493 }
5494 }
5495
Daniel Dunbar020daa92009-09-12 01:00:39 +00005496 ABIKind getABIKind() const { return Kind; }
5497
Tim Northovera484bc02013-10-01 14:34:25 +00005498private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005499 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005500 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005501 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005502
Reid Klecknere9f6a712014-10-31 17:10:41 +00005503 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5504 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5505 uint64_t Members) const override;
5506
Craig Topper4f12f102014-03-12 06:41:41 +00005507 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005508
John McCall7f416cc2015-09-08 08:05:57 +00005509 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5510 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005511
5512 llvm::CallingConv::ID getLLVMDefaultCC() const;
5513 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005514 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005515
John McCall56331e22018-01-07 06:28:49 +00005516 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005517 bool asReturnValue) const override {
5518 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5519 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005520 bool isSwiftErrorInRegister() const override {
5521 return true;
5522 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005523 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5524 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005525};
5526
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005527class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5528public:
Chris Lattner2b037972010-07-29 02:01:43 +00005529 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5530 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005531
John McCall3480ef22011-08-30 01:42:09 +00005532 const ARMABIInfo &getABIInfo() const {
5533 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5534 }
5535
Craig Topper4f12f102014-03-12 06:41:41 +00005536 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005537 return 13;
5538 }
Roman Divackyc1617352011-05-18 19:36:54 +00005539
Craig Topper4f12f102014-03-12 06:41:41 +00005540 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005541 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005542 }
5543
Roman Divackyc1617352011-05-18 19:36:54 +00005544 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005545 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005546 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005547
5548 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005549 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005550 return false;
5551 }
John McCall3480ef22011-08-30 01:42:09 +00005552
Craig Topper4f12f102014-03-12 06:41:41 +00005553 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005554 if (getABIInfo().isEABI()) return 88;
5555 return TargetCodeGenInfo::getSizeOfUnwindException();
5556 }
Tim Northovera484bc02013-10-01 14:34:25 +00005557
Eric Christopher162c91c2015-06-05 22:03:00 +00005558 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005559 CodeGen::CodeGenModule &CGM,
5560 ForDefinition_t IsForDefinition) const override {
5561 if (!IsForDefinition)
5562 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005563 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005564 if (!FD)
5565 return;
5566
5567 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5568 if (!Attr)
5569 return;
5570
5571 const char *Kind;
5572 switch (Attr->getInterrupt()) {
5573 case ARMInterruptAttr::Generic: Kind = ""; break;
5574 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5575 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5576 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5577 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5578 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5579 }
5580
5581 llvm::Function *Fn = cast<llvm::Function>(GV);
5582
5583 Fn->addFnAttr("interrupt", Kind);
5584
Tim Northover5627d392015-10-30 16:30:45 +00005585 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5586 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005587 return;
5588
5589 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5590 // however this is not necessarily true on taking any interrupt. Instruct
5591 // the backend to perform a realignment as part of the function prologue.
5592 llvm::AttrBuilder B;
5593 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005594 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005595 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005596};
5597
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005598class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005599public:
5600 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5601 : ARMTargetCodeGenInfo(CGT, K) {}
5602
Eric Christopher162c91c2015-06-05 22:03:00 +00005603 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005604 CodeGen::CodeGenModule &CGM,
5605 ForDefinition_t IsForDefinition) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005606
5607 void getDependentLibraryOption(llvm::StringRef Lib,
5608 llvm::SmallString<24> &Opt) const override {
5609 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5610 }
5611
5612 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5613 llvm::SmallString<32> &Opt) const override {
5614 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5615 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005616};
5617
Eric Christopher162c91c2015-06-05 22:03:00 +00005618void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005619 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
5620 ForDefinition_t IsForDefinition) const {
5621 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
5622 if (!IsForDefinition)
5623 return;
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005624 addStackProbeSizeTargetAttribute(D, GV, CGM);
5625}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005626}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005627
Chris Lattner22326a12010-07-29 02:31:05 +00005628void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005629 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005630 FI.getReturnInfo() =
5631 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005632
Tim Northoverbc784d12015-02-24 17:22:40 +00005633 for (auto &I : FI.arguments())
5634 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005635
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005636 // Always honor user-specified calling convention.
5637 if (FI.getCallingConvention() != llvm::CallingConv::C)
5638 return;
5639
John McCall882987f2013-02-28 19:01:20 +00005640 llvm::CallingConv::ID cc = getRuntimeCC();
5641 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005642 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005643}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005644
John McCall882987f2013-02-28 19:01:20 +00005645/// Return the default calling convention that LLVM will use.
5646llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5647 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005648 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005649 return llvm::CallingConv::ARM_AAPCS_VFP;
5650 else if (isEABI())
5651 return llvm::CallingConv::ARM_AAPCS;
5652 else
5653 return llvm::CallingConv::ARM_APCS;
5654}
5655
5656/// Return the calling convention that our ABI would like us to use
5657/// as the C calling convention.
5658llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005659 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005660 case APCS: return llvm::CallingConv::ARM_APCS;
5661 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5662 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005663 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005664 }
John McCall882987f2013-02-28 19:01:20 +00005665 llvm_unreachable("bad ABI kind");
5666}
5667
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005668void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005669 assert(getRuntimeCC() == llvm::CallingConv::C);
5670
5671 // Don't muddy up the IR with a ton of explicit annotations if
5672 // they'd just match what LLVM will infer from the triple.
5673 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5674 if (abiCC != getLLVMDefaultCC())
5675 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005676
Tim Northover5627d392015-10-30 16:30:45 +00005677 // AAPCS apparently requires runtime support functions to be soft-float, but
5678 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5679 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
Peter Smith32e26752017-07-27 10:43:53 +00005680
5681 // The Run-time ABI for the ARM Architecture section 4.1.2 requires
5682 // AEABI-complying FP helper functions to use the base AAPCS.
5683 // These AEABI functions are expanded in the ARM llvm backend, all the builtin
5684 // support functions emitted by clang such as the _Complex helpers follow the
5685 // abiCC.
5686 if (abiCC != getLLVMDefaultCC())
Tim Northover5627d392015-10-30 16:30:45 +00005687 BuiltinCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005688}
5689
Tim Northoverbc784d12015-02-24 17:22:40 +00005690ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5691 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005692 // 6.1.2.1 The following argument types are VFP CPRCs:
5693 // A single-precision floating-point type (including promoted
5694 // half-precision types); A double-precision floating-point type;
5695 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5696 // with a Base Type of a single- or double-precision floating-point type,
5697 // 64-bit containerized vectors or 128-bit containerized vectors with one
5698 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005699 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005700
Reid Klecknerb1be6832014-11-15 01:41:41 +00005701 Ty = useFirstFieldIfTransparentUnion(Ty);
5702
Manman Renfef9e312012-10-16 19:18:39 +00005703 // Handle illegal vector types here.
5704 if (isIllegalVectorType(Ty)) {
5705 uint64_t Size = getContext().getTypeSize(Ty);
5706 if (Size <= 32) {
5707 llvm::Type *ResType =
5708 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005709 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005710 }
5711 if (Size == 64) {
5712 llvm::Type *ResType = llvm::VectorType::get(
5713 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005714 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005715 }
5716 if (Size == 128) {
5717 llvm::Type *ResType = llvm::VectorType::get(
5718 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005719 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005720 }
John McCall7f416cc2015-09-08 08:05:57 +00005721 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005722 }
5723
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005724 // _Float16 and __fp16 get passed as if it were an int or float, but with
5725 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5726 // half type natively, and does not need to interwork with AAPCS code.
5727 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5728 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005729 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5730 llvm::Type::getFloatTy(getVMContext()) :
5731 llvm::Type::getInt32Ty(getVMContext());
5732 return ABIArgInfo::getDirect(ResType);
5733 }
5734
John McCalla1dee5302010-08-22 10:59:02 +00005735 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005736 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005737 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005738 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005739 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005740
Alex Bradburye41a5e22018-01-12 20:08:16 +00005741 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
Tim Northover5a1558e2014-11-07 22:30:50 +00005742 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005743 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005744
Oliver Stannard405bded2014-02-11 09:25:50 +00005745 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005746 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005747 }
Tim Northover1060eae2013-06-21 22:49:34 +00005748
Daniel Dunbar09d33622009-09-14 21:54:03 +00005749 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005750 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005751 return ABIArgInfo::getIgnore();
5752
Tim Northover5a1558e2014-11-07 22:30:50 +00005753 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005754 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5755 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005756 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005757 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005758 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005759 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005760 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005761 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005762 }
Tim Northover5627d392015-10-30 16:30:45 +00005763 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5764 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5765 // this convention even for a variadic function: the backend will use GPRs
5766 // if needed.
5767 const Type *Base = nullptr;
5768 uint64_t Members = 0;
5769 if (isHomogeneousAggregate(Ty, Base, Members)) {
5770 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5771 llvm::Type *Ty =
5772 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5773 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5774 }
5775 }
5776
5777 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5778 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5779 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5780 // bigger than 128-bits, they get placed in space allocated by the caller,
5781 // and a pointer is passed.
5782 return ABIArgInfo::getIndirect(
5783 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005784 }
5785
Manman Ren6c30e132012-08-13 21:23:55 +00005786 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005787 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5788 // most 8-byte. We realign the indirect argument if type alignment is bigger
5789 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005790 uint64_t ABIAlign = 4;
5791 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5792 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005793 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005794 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005795
Manman Ren8cd99812012-11-06 04:58:01 +00005796 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005797 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005798 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5799 /*ByVal=*/true,
5800 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005801 }
5802
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005803 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5804 // same size and alignment.
5805 if (getTarget().isRenderScriptTarget()) {
5806 return coerceToIntArray(Ty, getContext(), getVMContext());
5807 }
5808
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005809 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005810 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005811 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005812 // FIXME: Try to match the types of the arguments more accurately where
5813 // we can.
5814 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005815 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5816 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005817 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005818 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5819 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005820 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005821
Tim Northover5a1558e2014-11-07 22:30:50 +00005822 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005823}
5824
Chris Lattner458b2aa2010-07-29 02:16:43 +00005825static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005826 llvm::LLVMContext &VMContext) {
5827 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5828 // is called integer-like if its size is less than or equal to one word, and
5829 // the offset of each of its addressable sub-fields is zero.
5830
5831 uint64_t Size = Context.getTypeSize(Ty);
5832
5833 // Check that the type fits in a word.
5834 if (Size > 32)
5835 return false;
5836
5837 // FIXME: Handle vector types!
5838 if (Ty->isVectorType())
5839 return false;
5840
Daniel Dunbard53bac72009-09-14 02:20:34 +00005841 // Float types are never treated as "integer like".
5842 if (Ty->isRealFloatingType())
5843 return false;
5844
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005845 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005846 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005847 return true;
5848
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005849 // Small complex integer types are "integer like".
5850 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5851 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005852
5853 // Single element and zero sized arrays should be allowed, by the definition
5854 // above, but they are not.
5855
5856 // Otherwise, it must be a record type.
5857 const RecordType *RT = Ty->getAs<RecordType>();
5858 if (!RT) return false;
5859
5860 // Ignore records with flexible arrays.
5861 const RecordDecl *RD = RT->getDecl();
5862 if (RD->hasFlexibleArrayMember())
5863 return false;
5864
5865 // Check that all sub-fields are at offset 0, and are themselves "integer
5866 // like".
5867 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5868
5869 bool HadField = false;
5870 unsigned idx = 0;
5871 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5872 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005873 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005874
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005875 // Bit-fields are not addressable, we only need to verify they are "integer
5876 // like". We still have to disallow a subsequent non-bitfield, for example:
5877 // struct { int : 0; int x }
5878 // is non-integer like according to gcc.
5879 if (FD->isBitField()) {
5880 if (!RD->isUnion())
5881 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005882
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005883 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5884 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005885
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005886 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005887 }
5888
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005889 // Check if this field is at offset 0.
5890 if (Layout.getFieldOffset(idx) != 0)
5891 return false;
5892
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005893 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5894 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005895
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005896 // Only allow at most one field in a structure. This doesn't match the
5897 // wording above, but follows gcc in situations with a field following an
5898 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005899 if (!RD->isUnion()) {
5900 if (HadField)
5901 return false;
5902
5903 HadField = true;
5904 }
5905 }
5906
5907 return true;
5908}
5909
Oliver Stannard405bded2014-02-11 09:25:50 +00005910ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5911 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005912 bool IsEffectivelyAAPCS_VFP =
5913 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005914
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005915 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005916 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005917
Daniel Dunbar19964db2010-09-23 01:54:32 +00005918 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005919 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005920 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005921 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005922
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005923 // _Float16 and __fp16 get returned as if it were an int or float, but with
5924 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5925 // half type natively, and does not need to interwork with AAPCS code.
5926 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
5927 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005928 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5929 llvm::Type::getFloatTy(getVMContext()) :
5930 llvm::Type::getInt32Ty(getVMContext());
5931 return ABIArgInfo::getDirect(ResType);
5932 }
5933
John McCalla1dee5302010-08-22 10:59:02 +00005934 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005935 // Treat an enum type as its underlying type.
5936 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5937 RetTy = EnumTy->getDecl()->getIntegerType();
5938
Alex Bradburye41a5e22018-01-12 20:08:16 +00005939 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
Tim Northover5a1558e2014-11-07 22:30:50 +00005940 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005941 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005942
5943 // Are we following APCS?
5944 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005945 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005946 return ABIArgInfo::getIgnore();
5947
Daniel Dunbareedf1512010-02-01 23:31:19 +00005948 // Complex types are all returned as packed integers.
5949 //
5950 // FIXME: Consider using 2 x vector types if the back end handles them
5951 // correctly.
5952 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005953 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5954 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005955
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005956 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005957 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005958 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005959 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005960 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005961 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005962 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005963 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5964 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005965 }
5966
5967 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005968 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005969 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005970
5971 // Otherwise this is an AAPCS variant.
5972
Chris Lattner458b2aa2010-07-29 02:16:43 +00005973 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005974 return ABIArgInfo::getIgnore();
5975
Bob Wilson1d9269a2011-11-02 04:51:36 +00005976 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005977 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005978 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005979 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005980 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005981 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005982 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005983 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005984 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005985 }
5986
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005987 // Aggregates <= 4 bytes are returned in r0; other aggregates
5988 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005989 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005990 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005991 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5992 // same size and alignment.
5993 if (getTarget().isRenderScriptTarget()) {
5994 return coerceToIntArray(RetTy, getContext(), getVMContext());
5995 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005996 if (getDataLayout().isBigEndian())
5997 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005998 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005999
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006000 // Return in the smallest viable integer type.
6001 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00006002 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006003 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00006004 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6005 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00006006 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6007 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6008 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00006009 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00006010 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006011 }
6012
John McCall7f416cc2015-09-08 08:05:57 +00006013 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006014}
6015
Manman Renfef9e312012-10-16 19:18:39 +00006016/// isIllegalVector - check whether Ty is an illegal vector type.
6017bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00006018 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6019 if (isAndroid()) {
6020 // Android shipped using Clang 3.1, which supported a slightly different
6021 // vector ABI. The primary differences were that 3-element vector types
6022 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6023 // accepts that legacy behavior for Android only.
6024 // Check whether VT is legal.
6025 unsigned NumElements = VT->getNumElements();
6026 // NumElements should be power of 2 or equal to 3.
6027 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6028 return true;
6029 } else {
6030 // Check whether VT is legal.
6031 unsigned NumElements = VT->getNumElements();
6032 uint64_t Size = getContext().getTypeSize(VT);
6033 // NumElements should be power of 2.
6034 if (!llvm::isPowerOf2_32(NumElements))
6035 return true;
6036 // Size should be greater than 32 bits.
6037 return Size <= 32;
6038 }
Manman Renfef9e312012-10-16 19:18:39 +00006039 }
6040 return false;
6041}
6042
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006043bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6044 llvm::Type *eltTy,
6045 unsigned numElts) const {
6046 if (!llvm::isPowerOf2_32(numElts))
6047 return false;
6048 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6049 if (size > 64)
6050 return false;
6051 if (vectorSize.getQuantity() != 8 &&
6052 (vectorSize.getQuantity() != 16 || numElts == 1))
6053 return false;
6054 return true;
6055}
6056
Reid Klecknere9f6a712014-10-31 17:10:41 +00006057bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6058 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6059 // double, or 64-bit or 128-bit vectors.
6060 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6061 if (BT->getKind() == BuiltinType::Float ||
6062 BT->getKind() == BuiltinType::Double ||
6063 BT->getKind() == BuiltinType::LongDouble)
6064 return true;
6065 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6066 unsigned VecSize = getContext().getTypeSize(VT);
6067 if (VecSize == 64 || VecSize == 128)
6068 return true;
6069 }
6070 return false;
6071}
6072
6073bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6074 uint64_t Members) const {
6075 return Members <= 4;
6076}
6077
John McCall7f416cc2015-09-08 08:05:57 +00006078Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6079 QualType Ty) const {
6080 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006081
John McCall7f416cc2015-09-08 08:05:57 +00006082 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006083 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006084 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6085 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6086 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006087 }
6088
John McCall7f416cc2015-09-08 08:05:57 +00006089 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6090 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006091
John McCall7f416cc2015-09-08 08:05:57 +00006092 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6093 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006094 const Type *Base = nullptr;
6095 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006096 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6097 IsIndirect = true;
6098
Tim Northover5627d392015-10-30 16:30:45 +00006099 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6100 // allocated by the caller.
6101 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6102 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6103 !isHomogeneousAggregate(Ty, Base, Members)) {
6104 IsIndirect = true;
6105
John McCall7f416cc2015-09-08 08:05:57 +00006106 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006107 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6108 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006109 // Our callers should be prepared to handle an under-aligned address.
6110 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6111 getABIKind() == ARMABIInfo::AAPCS) {
6112 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6113 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006114 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6115 // ARMv7k allows type alignment up to 16 bytes.
6116 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6117 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006118 } else {
6119 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006120 }
John McCall7f416cc2015-09-08 08:05:57 +00006121 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006122
John McCall7f416cc2015-09-08 08:05:57 +00006123 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6124 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006125}
6126
Chris Lattner0cf24192010-06-28 20:05:43 +00006127//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006128// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006129//===----------------------------------------------------------------------===//
6130
6131namespace {
6132
Justin Holewinski83e96682012-05-24 17:43:12 +00006133class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006134public:
Justin Holewinski36837432013-03-30 14:38:24 +00006135 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006136
6137 ABIArgInfo classifyReturnType(QualType RetTy) const;
6138 ABIArgInfo classifyArgumentType(QualType Ty) const;
6139
Craig Topper4f12f102014-03-12 06:41:41 +00006140 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006141 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6142 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006143};
6144
Justin Holewinski83e96682012-05-24 17:43:12 +00006145class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006146public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006147 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6148 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006149
Eric Christopher162c91c2015-06-05 22:03:00 +00006150 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006151 CodeGen::CodeGenModule &M,
6152 ForDefinition_t IsForDefinition) const override;
6153
Justin Holewinski36837432013-03-30 14:38:24 +00006154private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006155 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6156 // resulting MDNode to the nvvm.annotations MDNode.
6157 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006158};
6159
Justin Holewinski83e96682012-05-24 17:43:12 +00006160ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006161 if (RetTy->isVoidType())
6162 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006163
6164 // note: this is different from default ABI
6165 if (!RetTy->isScalarType())
6166 return ABIArgInfo::getDirect();
6167
6168 // Treat an enum type as its underlying type.
6169 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6170 RetTy = EnumTy->getDecl()->getIntegerType();
6171
Alex Bradburye41a5e22018-01-12 20:08:16 +00006172 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6173 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006174}
6175
Justin Holewinski83e96682012-05-24 17:43:12 +00006176ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006177 // Treat an enum type as its underlying type.
6178 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6179 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006180
Eli Bendersky95338a02014-10-29 13:43:21 +00006181 // Return aggregates type as indirect by value
6182 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006183 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006184
Alex Bradburye41a5e22018-01-12 20:08:16 +00006185 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6186 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006187}
6188
Justin Holewinski83e96682012-05-24 17:43:12 +00006189void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006190 if (!getCXXABI().classifyReturnType(FI))
6191 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006192 for (auto &I : FI.arguments())
6193 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006194
6195 // Always honor user-specified calling convention.
6196 if (FI.getCallingConvention() != llvm::CallingConv::C)
6197 return;
6198
John McCall882987f2013-02-28 19:01:20 +00006199 FI.setEffectiveCallingConvention(getRuntimeCC());
6200}
6201
John McCall7f416cc2015-09-08 08:05:57 +00006202Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6203 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006204 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006205}
6206
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006207void NVPTXTargetCodeGenInfo::setTargetAttributes(
6208 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6209 ForDefinition_t IsForDefinition) const {
6210 if (!IsForDefinition)
6211 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006212 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006213 if (!FD) return;
6214
6215 llvm::Function *F = cast<llvm::Function>(GV);
6216
6217 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006218 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006219 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006220 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006221 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006222 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006223 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6224 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006225 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006226 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006227 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006228 }
Justin Holewinski38031972011-10-05 17:58:44 +00006229
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006230 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006231 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006232 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006233 // __global__ functions cannot be called from the device, we do not
6234 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006235 if (FD->hasAttr<CUDAGlobalAttr>()) {
6236 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6237 addNVVMMetadata(F, "kernel", 1);
6238 }
Artem Belevich7093e402015-04-21 22:55:54 +00006239 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006240 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006241 llvm::APSInt MaxThreads(32);
6242 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6243 if (MaxThreads > 0)
6244 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6245
6246 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6247 // not specified in __launch_bounds__ or if the user specified a 0 value,
6248 // we don't have to add a PTX directive.
6249 if (Attr->getMinBlocks()) {
6250 llvm::APSInt MinBlocks(32);
6251 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6252 if (MinBlocks > 0)
6253 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6254 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006255 }
6256 }
Justin Holewinski38031972011-10-05 17:58:44 +00006257 }
6258}
6259
Eli Benderskye06a2c42014-04-15 16:57:05 +00006260void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6261 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006262 llvm::Module *M = F->getParent();
6263 llvm::LLVMContext &Ctx = M->getContext();
6264
6265 // Get "nvvm.annotations" metadata node
6266 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6267
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006268 llvm::Metadata *MDVals[] = {
6269 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6270 llvm::ConstantAsMetadata::get(
6271 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006272 // Append metadata to nvvm.annotations
6273 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6274}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006275}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006276
6277//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006278// SystemZ ABI Implementation
6279//===----------------------------------------------------------------------===//
6280
6281namespace {
6282
Bryan Chane3f1ed52016-04-28 13:56:43 +00006283class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006284 bool HasVector;
6285
Ulrich Weigand47445072013-05-06 16:26:41 +00006286public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006287 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006288 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006289
6290 bool isPromotableIntegerType(QualType Ty) const;
6291 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006292 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006293 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006294 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006295
6296 ABIArgInfo classifyReturnType(QualType RetTy) const;
6297 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6298
Craig Topper4f12f102014-03-12 06:41:41 +00006299 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006300 if (!getCXXABI().classifyReturnType(FI))
6301 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006302 for (auto &I : FI.arguments())
6303 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006304 }
6305
John McCall7f416cc2015-09-08 08:05:57 +00006306 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6307 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006308
John McCall56331e22018-01-07 06:28:49 +00006309 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
Bryan Chane3f1ed52016-04-28 13:56:43 +00006310 bool asReturnValue) const override {
6311 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6312 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006313 bool isSwiftErrorInRegister() const override {
Arnold Schwaighofer612d6932017-11-07 16:40:51 +00006314 return false;
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006315 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006316};
6317
6318class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6319public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006320 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6321 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006322};
6323
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006324}
Ulrich Weigand47445072013-05-06 16:26:41 +00006325
6326bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6327 // Treat an enum type as its underlying type.
6328 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6329 Ty = EnumTy->getDecl()->getIntegerType();
6330
6331 // Promotable integer types are required to be promoted by the ABI.
6332 if (Ty->isPromotableIntegerType())
6333 return true;
6334
6335 // 32-bit values must also be promoted.
6336 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6337 switch (BT->getKind()) {
6338 case BuiltinType::Int:
6339 case BuiltinType::UInt:
6340 return true;
6341 default:
6342 return false;
6343 }
6344 return false;
6345}
6346
6347bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006348 return (Ty->isAnyComplexType() ||
6349 Ty->isVectorType() ||
6350 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006351}
6352
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006353bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6354 return (HasVector &&
6355 Ty->isVectorType() &&
6356 getContext().getTypeSize(Ty) <= 128);
6357}
6358
Ulrich Weigand47445072013-05-06 16:26:41 +00006359bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6360 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6361 switch (BT->getKind()) {
6362 case BuiltinType::Float:
6363 case BuiltinType::Double:
6364 return true;
6365 default:
6366 return false;
6367 }
6368
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006369 return false;
6370}
6371
6372QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006373 if (const RecordType *RT = Ty->getAsStructureType()) {
6374 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006375 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006376
6377 // If this is a C++ record, check the bases first.
6378 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006379 for (const auto &I : CXXRD->bases()) {
6380 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006381
6382 // Empty bases don't affect things either way.
6383 if (isEmptyRecord(getContext(), Base, true))
6384 continue;
6385
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006386 if (!Found.isNull())
6387 return Ty;
6388 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006389 }
6390
6391 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006392 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006393 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006394 // Unlike isSingleElementStruct(), empty structure and array fields
6395 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006396 if (getContext().getLangOpts().CPlusPlus &&
6397 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6398 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006399
6400 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006401 // Nested structures still do though.
6402 if (!Found.isNull())
6403 return Ty;
6404 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006405 }
6406
6407 // Unlike isSingleElementStruct(), trailing padding is allowed.
6408 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006409 if (!Found.isNull())
6410 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006411 }
6412
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006413 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006414}
6415
John McCall7f416cc2015-09-08 08:05:57 +00006416Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6417 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006418 // Assume that va_list type is correct; should be pointer to LLVM type:
6419 // struct {
6420 // i64 __gpr;
6421 // i64 __fpr;
6422 // i8 *__overflow_arg_area;
6423 // i8 *__reg_save_area;
6424 // };
6425
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006426 // Every non-vector argument occupies 8 bytes and is passed by preference
6427 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6428 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006429 Ty = getContext().getCanonicalType(Ty);
6430 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006431 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006432 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006433 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006434 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006435 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006436 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006437 CharUnits UnpaddedSize;
6438 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006439 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006440 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6441 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006442 } else {
6443 if (AI.getCoerceToType())
6444 ArgTy = AI.getCoerceToType();
6445 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006446 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006447 UnpaddedSize = TyInfo.first;
6448 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006449 }
John McCall7f416cc2015-09-08 08:05:57 +00006450 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6451 if (IsVector && UnpaddedSize > PaddedSize)
6452 PaddedSize = CharUnits::fromQuantity(16);
6453 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006454
John McCall7f416cc2015-09-08 08:05:57 +00006455 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006456
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006457 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006458 llvm::Value *PaddedSizeV =
6459 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006460
6461 if (IsVector) {
6462 // Work out the address of a vector argument on the stack.
6463 // Vector arguments are always passed in the high bits of a
6464 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006465 Address OverflowArgAreaPtr =
6466 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006467 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006468 Address OverflowArgArea =
6469 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6470 TyInfo.second);
6471 Address MemAddr =
6472 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006473
6474 // Update overflow_arg_area_ptr pointer
6475 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006476 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6477 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006478 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6479
6480 return MemAddr;
6481 }
6482
John McCall7f416cc2015-09-08 08:05:57 +00006483 assert(PaddedSize.getQuantity() == 8);
6484
6485 unsigned MaxRegs, RegCountField, RegSaveIndex;
6486 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006487 if (InFPRs) {
6488 MaxRegs = 4; // Maximum of 4 FPR arguments
6489 RegCountField = 1; // __fpr
6490 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006491 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006492 } else {
6493 MaxRegs = 5; // Maximum of 5 GPR arguments
6494 RegCountField = 0; // __gpr
6495 RegSaveIndex = 2; // save offset for r2
6496 RegPadding = Padding; // values are passed in the low bits of a GPR
6497 }
6498
John McCall7f416cc2015-09-08 08:05:57 +00006499 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6500 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6501 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006502 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006503 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6504 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006505 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006506
6507 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6508 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6509 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6510 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6511
6512 // Emit code to load the value if it was passed in registers.
6513 CGF.EmitBlock(InRegBlock);
6514
6515 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006516 llvm::Value *ScaledRegCount =
6517 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6518 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006519 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6520 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006521 llvm::Value *RegOffset =
6522 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006523 Address RegSaveAreaPtr =
6524 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6525 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006526 llvm::Value *RegSaveArea =
6527 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006528 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6529 "raw_reg_addr"),
6530 PaddedSize);
6531 Address RegAddr =
6532 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006533
6534 // Update the register count
6535 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6536 llvm::Value *NewRegCount =
6537 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6538 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6539 CGF.EmitBranch(ContBlock);
6540
6541 // Emit code to load the value if it was passed in memory.
6542 CGF.EmitBlock(InMemBlock);
6543
6544 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006545 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6546 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6547 Address OverflowArgArea =
6548 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6549 PaddedSize);
6550 Address RawMemAddr =
6551 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6552 Address MemAddr =
6553 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006554
6555 // Update overflow_arg_area_ptr pointer
6556 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006557 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6558 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006559 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6560 CGF.EmitBranch(ContBlock);
6561
6562 // Return the appropriate result.
6563 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006564 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6565 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006566
6567 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006568 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6569 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006570
6571 return ResAddr;
6572}
6573
Ulrich Weigand47445072013-05-06 16:26:41 +00006574ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6575 if (RetTy->isVoidType())
6576 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006577 if (isVectorArgumentType(RetTy))
6578 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006579 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006580 return getNaturalAlignIndirect(RetTy);
Alex Bradburye41a5e22018-01-12 20:08:16 +00006581 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6582 : ABIArgInfo::getDirect());
Ulrich Weigand47445072013-05-06 16:26:41 +00006583}
6584
6585ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6586 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006587 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006588 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006589
6590 // Integers and enums are extended to full register width.
6591 if (isPromotableIntegerType(Ty))
Alex Bradburye41a5e22018-01-12 20:08:16 +00006592 return ABIArgInfo::getExtend(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006593
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006594 // Handle vector types and vector-like structure types. Note that
6595 // as opposed to float-like structure types, we do not allow any
6596 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006597 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006598 QualType SingleElementTy = GetSingleElementType(Ty);
6599 if (isVectorArgumentType(SingleElementTy) &&
6600 getContext().getTypeSize(SingleElementTy) == Size)
6601 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6602
6603 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006604 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006605 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006606
6607 // Handle small structures.
6608 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6609 // Structures with flexible arrays have variable length, so really
6610 // fail the size test above.
6611 const RecordDecl *RD = RT->getDecl();
6612 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006613 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006614
6615 // The structure is passed as an unextended integer, a float, or a double.
6616 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006617 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006618 assert(Size == 32 || Size == 64);
6619 if (Size == 32)
6620 PassTy = llvm::Type::getFloatTy(getVMContext());
6621 else
6622 PassTy = llvm::Type::getDoubleTy(getVMContext());
6623 } else
6624 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6625 return ABIArgInfo::getDirect(PassTy);
6626 }
6627
6628 // Non-structure compounds are passed indirectly.
6629 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006630 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006631
Craig Topper8a13c412014-05-21 05:09:00 +00006632 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006633}
6634
6635//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006636// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006637//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006638
6639namespace {
6640
6641class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6642public:
Chris Lattner2b037972010-07-29 02:01:43 +00006643 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6644 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006645 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006646 CodeGen::CodeGenModule &M,
6647 ForDefinition_t IsForDefinition) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006648};
6649
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006650}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006651
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006652void MSP430TargetCodeGenInfo::setTargetAttributes(
6653 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6654 ForDefinition_t IsForDefinition) const {
6655 if (!IsForDefinition)
6656 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006657 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006658 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6659 // Handle 'interrupt' attribute:
6660 llvm::Function *F = cast<llvm::Function>(GV);
6661
6662 // Step 1: Set ISR calling convention.
6663 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6664
6665 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006666 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006667
6668 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006669 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006670 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6671 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006672 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006673 }
6674}
6675
Chris Lattner0cf24192010-06-28 20:05:43 +00006676//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006677// MIPS ABI Implementation. This works for both little-endian and
6678// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006679//===----------------------------------------------------------------------===//
6680
John McCall943fae92010-05-27 06:19:26 +00006681namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006682class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006683 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006684 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6685 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006686 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006687 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006688 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006689 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006690public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006691 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006692 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006693 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006694
6695 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006696 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006697 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006698 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6699 QualType Ty) const override;
Alex Bradburye41a5e22018-01-12 20:08:16 +00006700 ABIArgInfo extendType(QualType Ty) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006701};
6702
John McCall943fae92010-05-27 06:19:26 +00006703class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006704 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006705public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006706 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6707 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006708 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006709
Craig Topper4f12f102014-03-12 06:41:41 +00006710 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006711 return 29;
6712 }
6713
Eric Christopher162c91c2015-06-05 22:03:00 +00006714 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006715 CodeGen::CodeGenModule &CGM,
6716 ForDefinition_t IsForDefinition) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006717 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006718 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006719 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006720
6721 if (FD->hasAttr<MipsLongCallAttr>())
6722 Fn->addFnAttr("long-call");
6723 else if (FD->hasAttr<MipsShortCallAttr>())
6724 Fn->addFnAttr("short-call");
6725
6726 // Other attributes do not have a meaning for declarations.
6727 if (!IsForDefinition)
6728 return;
6729
Reed Kotler3d5966f2013-03-13 20:40:30 +00006730 if (FD->hasAttr<Mips16Attr>()) {
6731 Fn->addFnAttr("mips16");
6732 }
6733 else if (FD->hasAttr<NoMips16Attr>()) {
6734 Fn->addFnAttr("nomips16");
6735 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006736
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006737 if (FD->hasAttr<MicroMipsAttr>())
6738 Fn->addFnAttr("micromips");
6739 else if (FD->hasAttr<NoMicroMipsAttr>())
6740 Fn->addFnAttr("nomicromips");
6741
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006742 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6743 if (!Attr)
6744 return;
6745
6746 const char *Kind;
6747 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006748 case MipsInterruptAttr::eic: Kind = "eic"; break;
6749 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6750 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6751 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6752 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6753 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6754 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6755 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6756 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6757 }
6758
6759 Fn->addFnAttr("interrupt", Kind);
6760
Reed Kotler373feca2013-01-16 17:10:28 +00006761 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006762
John McCall943fae92010-05-27 06:19:26 +00006763 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006764 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006765
Craig Topper4f12f102014-03-12 06:41:41 +00006766 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006767 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006768 }
John McCall943fae92010-05-27 06:19:26 +00006769};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006770}
John McCall943fae92010-05-27 06:19:26 +00006771
Eric Christopher7565e0d2015-05-29 23:09:49 +00006772void MipsABIInfo::CoerceToIntArgs(
6773 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006774 llvm::IntegerType *IntTy =
6775 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006776
6777 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6778 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6779 ArgList.push_back(IntTy);
6780
6781 // If necessary, add one more integer type to ArgList.
6782 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6783
6784 if (R)
6785 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006786}
6787
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006788// In N32/64, an aligned double precision floating point field is passed in
6789// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006790llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006791 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6792
6793 if (IsO32) {
6794 CoerceToIntArgs(TySize, ArgList);
6795 return llvm::StructType::get(getVMContext(), ArgList);
6796 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006797
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006798 if (Ty->isComplexType())
6799 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006800
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006801 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006802
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006803 // Unions/vectors are passed in integer registers.
6804 if (!RT || !RT->isStructureOrClassType()) {
6805 CoerceToIntArgs(TySize, ArgList);
6806 return llvm::StructType::get(getVMContext(), ArgList);
6807 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006808
6809 const RecordDecl *RD = RT->getDecl();
6810 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006811 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006812
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006813 uint64_t LastOffset = 0;
6814 unsigned idx = 0;
6815 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6816
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006817 // Iterate over fields in the struct/class and check if there are any aligned
6818 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006819 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6820 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006821 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006822 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6823
6824 if (!BT || BT->getKind() != BuiltinType::Double)
6825 continue;
6826
6827 uint64_t Offset = Layout.getFieldOffset(idx);
6828 if (Offset % 64) // Ignore doubles that are not aligned.
6829 continue;
6830
6831 // Add ((Offset - LastOffset) / 64) args of type i64.
6832 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6833 ArgList.push_back(I64);
6834
6835 // Add double type.
6836 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6837 LastOffset = Offset + 64;
6838 }
6839
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006840 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6841 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006842
6843 return llvm::StructType::get(getVMContext(), ArgList);
6844}
6845
Akira Hatanakaddd66342013-10-29 18:41:15 +00006846llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6847 uint64_t Offset) const {
6848 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006849 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006850
Akira Hatanakaddd66342013-10-29 18:41:15 +00006851 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006852}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006853
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006854ABIArgInfo
6855MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006856 Ty = useFirstFieldIfTransparentUnion(Ty);
6857
Akira Hatanaka1632af62012-01-09 19:31:25 +00006858 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006859 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006860 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006861
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006862 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6863 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006864 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6865 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006866
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006867 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006868 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006869 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006870 return ABIArgInfo::getIgnore();
6871
Mark Lacey3825e832013-10-06 01:33:34 +00006872 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006873 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006874 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006875 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006876
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006877 // If we have reached here, aggregates are passed directly by coercing to
6878 // another structure type. Padding is inserted if the offset of the
6879 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006880 ABIArgInfo ArgInfo =
6881 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6882 getPaddingType(OrigOffset, CurrOffset));
6883 ArgInfo.setInReg(true);
6884 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006885 }
6886
6887 // Treat an enum type as its underlying type.
6888 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6889 Ty = EnumTy->getDecl()->getIntegerType();
6890
Daniel Sanders5b445b32014-10-24 14:42:42 +00006891 // All integral types are promoted to the GPR width.
6892 if (Ty->isIntegralOrEnumerationType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00006893 return extendType(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006894
Akira Hatanakaddd66342013-10-29 18:41:15 +00006895 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006896 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006897}
6898
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006899llvm::Type*
6900MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006901 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006902 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006903
Akira Hatanakab6f74432012-02-09 18:49:26 +00006904 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006905 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006906 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6907 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006908
Akira Hatanakab6f74432012-02-09 18:49:26 +00006909 // N32/64 returns struct/classes in floating point registers if the
6910 // following conditions are met:
6911 // 1. The size of the struct/class is no larger than 128-bit.
6912 // 2. The struct/class has one or two fields all of which are floating
6913 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006914 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006915 //
6916 // Any other composite results are returned in integer registers.
6917 //
6918 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6919 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6920 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006921 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006922
Akira Hatanakab6f74432012-02-09 18:49:26 +00006923 if (!BT || !BT->isFloatingPoint())
6924 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006925
David Blaikie2d7c57e2012-04-30 02:36:29 +00006926 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006927 }
6928
6929 if (b == e)
6930 return llvm::StructType::get(getVMContext(), RTList,
6931 RD->hasAttr<PackedAttr>());
6932
6933 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006934 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006935 }
6936
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006937 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006938 return llvm::StructType::get(getVMContext(), RTList);
6939}
6940
Akira Hatanakab579fe52011-06-02 00:09:17 +00006941ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006942 uint64_t Size = getContext().getTypeSize(RetTy);
6943
Daniel Sandersed39f582014-09-04 13:28:14 +00006944 if (RetTy->isVoidType())
6945 return ABIArgInfo::getIgnore();
6946
6947 // O32 doesn't treat zero-sized structs differently from other structs.
6948 // However, N32/N64 ignores zero sized return values.
6949 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006950 return ABIArgInfo::getIgnore();
6951
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006952 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006953 if (Size <= 128) {
6954 if (RetTy->isAnyComplexType())
6955 return ABIArgInfo::getDirect();
6956
Daniel Sanderse5018b62014-09-04 15:05:39 +00006957 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006958 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006959 if (!IsO32 ||
6960 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6961 ABIArgInfo ArgInfo =
6962 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6963 ArgInfo.setInReg(true);
6964 return ArgInfo;
6965 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006966 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006967
John McCall7f416cc2015-09-08 08:05:57 +00006968 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006969 }
6970
6971 // Treat an enum type as its underlying type.
6972 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6973 RetTy = EnumTy->getDecl()->getIntegerType();
6974
Alex Bradburye41a5e22018-01-12 20:08:16 +00006975 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6976 : ABIArgInfo::getDirect());
Akira Hatanakab579fe52011-06-02 00:09:17 +00006977}
6978
6979void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006980 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006981 if (!getCXXABI().classifyReturnType(FI))
6982 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006983
Eric Christopher7565e0d2015-05-29 23:09:49 +00006984 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006985 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006986
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006987 for (auto &I : FI.arguments())
6988 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006989}
6990
John McCall7f416cc2015-09-08 08:05:57 +00006991Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6992 QualType OrigTy) const {
6993 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006994
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006995 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6996 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006997 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006998 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006999 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007000 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00007001 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007002 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00007003 DidPromote = true;
7004 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7005 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00007006 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00007007
John McCall7f416cc2015-09-08 08:05:57 +00007008 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007009
John McCall7f416cc2015-09-08 08:05:57 +00007010 // The alignment of things in the argument area is never larger than
7011 // StackAlignInBytes.
7012 TyInfo.second =
7013 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7014
7015 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7016 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7017
7018 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7019 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7020
7021
7022 // If there was a promotion, "unpromote" into a temporary.
7023 // TODO: can we just use a pointer into a subset of the original slot?
7024 if (DidPromote) {
7025 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7026 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7027
7028 // Truncate down to the right width.
7029 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7030 : CGF.IntPtrTy);
7031 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7032 if (OrigTy->isPointerType())
7033 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7034
7035 CGF.Builder.CreateStore(V, Temp);
7036 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007037 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007038
John McCall7f416cc2015-09-08 08:05:57 +00007039 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007040}
7041
Alex Bradburye41a5e22018-01-12 20:08:16 +00007042ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007043 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007044
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007045 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7046 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
Alex Bradburye41a5e22018-01-12 20:08:16 +00007047 return ABIArgInfo::getSignExtend(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007048
Alex Bradburye41a5e22018-01-12 20:08:16 +00007049 return ABIArgInfo::getExtend(Ty);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007050}
7051
John McCall943fae92010-05-27 06:19:26 +00007052bool
7053MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7054 llvm::Value *Address) const {
7055 // This information comes from gcc's implementation, which seems to
7056 // as canonical as it gets.
7057
John McCall943fae92010-05-27 06:19:26 +00007058 // Everything on MIPS is 4 bytes. Double-precision FP registers
7059 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007060 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007061
7062 // 0-31 are the general purpose registers, $0 - $31.
7063 // 32-63 are the floating-point registers, $f0 - $f31.
7064 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7065 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007066 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007067
7068 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7069 // They are one bit wide and ignored here.
7070
7071 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7072 // (coprocessor 1 is the FP unit)
7073 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7074 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7075 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007076 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007077 return false;
7078}
7079
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007080//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007081// AVR ABI Implementation.
7082//===----------------------------------------------------------------------===//
7083
7084namespace {
7085class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7086public:
7087 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7088 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7089
7090 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007091 CodeGen::CodeGenModule &CGM,
7092 ForDefinition_t IsForDefinition) const override {
7093 if (!IsForDefinition)
7094 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007095 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7096 if (!FD) return;
7097 auto *Fn = cast<llvm::Function>(GV);
7098
7099 if (FD->getAttr<AVRInterruptAttr>())
7100 Fn->addFnAttr("interrupt");
7101
7102 if (FD->getAttr<AVRSignalAttr>())
7103 Fn->addFnAttr("signal");
7104 }
7105};
7106}
7107
7108//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007109// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007110// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007111// handling.
7112//===----------------------------------------------------------------------===//
7113
7114namespace {
7115
7116class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7117public:
7118 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7119 : DefaultTargetCodeGenInfo(CGT) {}
7120
Eric Christopher162c91c2015-06-05 22:03:00 +00007121 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007122 CodeGen::CodeGenModule &M,
7123 ForDefinition_t IsForDefinition) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007124};
7125
Eric Christopher162c91c2015-06-05 22:03:00 +00007126void TCETargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007127 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7128 ForDefinition_t IsForDefinition) const {
7129 if (!IsForDefinition)
7130 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007131 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007132 if (!FD) return;
7133
7134 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007135
David Blaikiebbafb8a2012-03-11 07:00:24 +00007136 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007137 if (FD->hasAttr<OpenCLKernelAttr>()) {
7138 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007139 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007140 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7141 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007142 // Convert the reqd_work_group_size() attributes to metadata.
7143 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007144 llvm::NamedMDNode *OpenCLMetadata =
7145 M.getModule().getOrInsertNamedMetadata(
7146 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007147
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007148 SmallVector<llvm::Metadata *, 5> Operands;
7149 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007150
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007151 Operands.push_back(
7152 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7153 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7154 Operands.push_back(
7155 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7156 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7157 Operands.push_back(
7158 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7159 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007160
Eric Christopher7565e0d2015-05-29 23:09:49 +00007161 // Add a boolean constant operand for "required" (true) or "hint"
7162 // (false) for implementing the work_group_size_hint attr later.
7163 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007164 Operands.push_back(
7165 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007166 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7167 }
7168 }
7169 }
7170}
7171
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007172}
John McCall943fae92010-05-27 06:19:26 +00007173
Tony Linthicum76329bf2011-12-12 21:14:55 +00007174//===----------------------------------------------------------------------===//
7175// Hexagon ABI Implementation
7176//===----------------------------------------------------------------------===//
7177
7178namespace {
7179
7180class HexagonABIInfo : public ABIInfo {
7181
7182
7183public:
7184 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7185
7186private:
7187
7188 ABIArgInfo classifyReturnType(QualType RetTy) const;
7189 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7190
Craig Topper4f12f102014-03-12 06:41:41 +00007191 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007192
John McCall7f416cc2015-09-08 08:05:57 +00007193 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7194 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007195};
7196
7197class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7198public:
7199 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7200 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7201
Craig Topper4f12f102014-03-12 06:41:41 +00007202 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007203 return 29;
7204 }
7205};
7206
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007207}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007208
7209void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007210 if (!getCXXABI().classifyReturnType(FI))
7211 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007212 for (auto &I : FI.arguments())
7213 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007214}
7215
7216ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7217 if (!isAggregateTypeForABI(Ty)) {
7218 // Treat an enum type as its underlying type.
7219 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7220 Ty = EnumTy->getDecl()->getIntegerType();
7221
Alex Bradburye41a5e22018-01-12 20:08:16 +00007222 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7223 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007224 }
7225
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007226 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7227 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7228
Tony Linthicum76329bf2011-12-12 21:14:55 +00007229 // Ignore empty records.
7230 if (isEmptyRecord(getContext(), Ty, true))
7231 return ABIArgInfo::getIgnore();
7232
Tony Linthicum76329bf2011-12-12 21:14:55 +00007233 uint64_t Size = getContext().getTypeSize(Ty);
7234 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007235 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007236 // Pass in the smallest viable integer type.
7237 else if (Size > 32)
7238 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7239 else if (Size > 16)
7240 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7241 else if (Size > 8)
7242 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7243 else
7244 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7245}
7246
7247ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7248 if (RetTy->isVoidType())
7249 return ABIArgInfo::getIgnore();
7250
7251 // Large vector types should be returned via memory.
7252 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007253 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007254
7255 if (!isAggregateTypeForABI(RetTy)) {
7256 // Treat an enum type as its underlying type.
7257 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7258 RetTy = EnumTy->getDecl()->getIntegerType();
7259
Alex Bradburye41a5e22018-01-12 20:08:16 +00007260 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7261 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007262 }
7263
Tony Linthicum76329bf2011-12-12 21:14:55 +00007264 if (isEmptyRecord(getContext(), RetTy, true))
7265 return ABIArgInfo::getIgnore();
7266
7267 // Aggregates <= 8 bytes are returned in r0; other aggregates
7268 // are returned indirectly.
7269 uint64_t Size = getContext().getTypeSize(RetTy);
7270 if (Size <= 64) {
7271 // Return in the smallest viable integer type.
7272 if (Size <= 8)
7273 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7274 if (Size <= 16)
7275 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7276 if (Size <= 32)
7277 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7278 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7279 }
7280
John McCall7f416cc2015-09-08 08:05:57 +00007281 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007282}
7283
John McCall7f416cc2015-09-08 08:05:57 +00007284Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7285 QualType Ty) const {
7286 // FIXME: Someone needs to audit that this handle alignment correctly.
7287 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7288 getContext().getTypeInfoInChars(Ty),
7289 CharUnits::fromQuantity(4),
7290 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007291}
7292
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007293//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007294// Lanai ABI Implementation
7295//===----------------------------------------------------------------------===//
7296
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007297namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007298class LanaiABIInfo : public DefaultABIInfo {
7299public:
7300 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7301
7302 bool shouldUseInReg(QualType Ty, CCState &State) const;
7303
7304 void computeInfo(CGFunctionInfo &FI) const override {
7305 CCState State(FI.getCallingConvention());
7306 // Lanai uses 4 registers to pass arguments unless the function has the
7307 // regparm attribute set.
7308 if (FI.getHasRegParm()) {
7309 State.FreeRegs = FI.getRegParm();
7310 } else {
7311 State.FreeRegs = 4;
7312 }
7313
7314 if (!getCXXABI().classifyReturnType(FI))
7315 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7316 for (auto &I : FI.arguments())
7317 I.info = classifyArgumentType(I.type, State);
7318 }
7319
Jacques Pienaare74d9132016-04-26 00:09:29 +00007320 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007321 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7322};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007323} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007324
7325bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7326 unsigned Size = getContext().getTypeSize(Ty);
7327 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7328
7329 if (SizeInRegs == 0)
7330 return false;
7331
7332 if (SizeInRegs > State.FreeRegs) {
7333 State.FreeRegs = 0;
7334 return false;
7335 }
7336
7337 State.FreeRegs -= SizeInRegs;
7338
7339 return true;
7340}
7341
Jacques Pienaare74d9132016-04-26 00:09:29 +00007342ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7343 CCState &State) const {
7344 if (!ByVal) {
7345 if (State.FreeRegs) {
7346 --State.FreeRegs; // Non-byval indirects just use one pointer.
7347 return getNaturalAlignIndirectInReg(Ty);
7348 }
7349 return getNaturalAlignIndirect(Ty, false);
7350 }
7351
7352 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007353 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007354 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7355 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7356 /*Realign=*/TypeAlign >
7357 MinABIStackAlignInBytes);
7358}
7359
Jacques Pienaard964cc22016-03-28 21:02:54 +00007360ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7361 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007362 // Check with the C++ ABI first.
7363 const RecordType *RT = Ty->getAs<RecordType>();
7364 if (RT) {
7365 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7366 if (RAA == CGCXXABI::RAA_Indirect) {
7367 return getIndirectResult(Ty, /*ByVal=*/false, State);
7368 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7369 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7370 }
7371 }
7372
7373 if (isAggregateTypeForABI(Ty)) {
7374 // Structures with flexible arrays are always indirect.
7375 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7376 return getIndirectResult(Ty, /*ByVal=*/true, State);
7377
7378 // Ignore empty structs/unions.
7379 if (isEmptyRecord(getContext(), Ty, true))
7380 return ABIArgInfo::getIgnore();
7381
7382 llvm::LLVMContext &LLVMContext = getVMContext();
7383 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7384 if (SizeInRegs <= State.FreeRegs) {
7385 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7386 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7387 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7388 State.FreeRegs -= SizeInRegs;
7389 return ABIArgInfo::getDirectInReg(Result);
7390 } else {
7391 State.FreeRegs = 0;
7392 }
7393 return getIndirectResult(Ty, true, State);
7394 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007395
7396 // Treat an enum type as its underlying type.
7397 if (const auto *EnumTy = Ty->getAs<EnumType>())
7398 Ty = EnumTy->getDecl()->getIntegerType();
7399
Jacques Pienaare74d9132016-04-26 00:09:29 +00007400 bool InReg = shouldUseInReg(Ty, State);
7401 if (Ty->isPromotableIntegerType()) {
7402 if (InReg)
7403 return ABIArgInfo::getDirectInReg();
Alex Bradburye41a5e22018-01-12 20:08:16 +00007404 return ABIArgInfo::getExtend(Ty);
Jacques Pienaare74d9132016-04-26 00:09:29 +00007405 }
7406 if (InReg)
7407 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007408 return ABIArgInfo::getDirect();
7409}
7410
7411namespace {
7412class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7413public:
7414 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7415 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7416};
7417}
7418
7419//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007420// AMDGPU ABI Implementation
7421//===----------------------------------------------------------------------===//
7422
7423namespace {
7424
Matt Arsenault88d7da02016-08-22 19:25:59 +00007425class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007426private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007427 static const unsigned MaxNumRegsForArgsRet = 16;
7428
Matt Arsenault3fe73952017-08-09 21:44:58 +00007429 unsigned numRegsForType(QualType Ty) const;
7430
7431 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7432 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7433 uint64_t Members) const override;
7434
7435public:
7436 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7437 DefaultABIInfo(CGT) {}
7438
7439 ABIArgInfo classifyReturnType(QualType RetTy) const;
7440 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7441 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007442
7443 void computeInfo(CGFunctionInfo &FI) const override;
7444};
7445
Matt Arsenault3fe73952017-08-09 21:44:58 +00007446bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7447 return true;
7448}
7449
7450bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7451 const Type *Base, uint64_t Members) const {
7452 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7453
7454 // Homogeneous Aggregates may occupy at most 16 registers.
7455 return Members * NumRegs <= MaxNumRegsForArgsRet;
7456}
7457
Matt Arsenault3fe73952017-08-09 21:44:58 +00007458/// Estimate number of registers the type will use when passed in registers.
7459unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7460 unsigned NumRegs = 0;
7461
7462 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7463 // Compute from the number of elements. The reported size is based on the
7464 // in-memory size, which includes the padding 4th element for 3-vectors.
7465 QualType EltTy = VT->getElementType();
7466 unsigned EltSize = getContext().getTypeSize(EltTy);
7467
7468 // 16-bit element vectors should be passed as packed.
7469 if (EltSize == 16)
7470 return (VT->getNumElements() + 1) / 2;
7471
7472 unsigned EltNumRegs = (EltSize + 31) / 32;
7473 return EltNumRegs * VT->getNumElements();
7474 }
7475
7476 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7477 const RecordDecl *RD = RT->getDecl();
7478 assert(!RD->hasFlexibleArrayMember());
7479
7480 for (const FieldDecl *Field : RD->fields()) {
7481 QualType FieldTy = Field->getType();
7482 NumRegs += numRegsForType(FieldTy);
7483 }
7484
7485 return NumRegs;
7486 }
7487
7488 return (getContext().getTypeSize(Ty) + 31) / 32;
7489}
7490
Matt Arsenault88d7da02016-08-22 19:25:59 +00007491void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007492 llvm::CallingConv::ID CC = FI.getCallingConvention();
7493
Matt Arsenault88d7da02016-08-22 19:25:59 +00007494 if (!getCXXABI().classifyReturnType(FI))
7495 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7496
Matt Arsenault3fe73952017-08-09 21:44:58 +00007497 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7498 for (auto &Arg : FI.arguments()) {
7499 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7500 Arg.info = classifyKernelArgumentType(Arg.type);
7501 } else {
7502 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7503 }
7504 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007505}
7506
Matt Arsenault3fe73952017-08-09 21:44:58 +00007507ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7508 if (isAggregateTypeForABI(RetTy)) {
7509 // Records with non-trivial destructors/copy-constructors should not be
7510 // returned by value.
7511 if (!getRecordArgABI(RetTy, getCXXABI())) {
7512 // Ignore empty structs/unions.
7513 if (isEmptyRecord(getContext(), RetTy, true))
7514 return ABIArgInfo::getIgnore();
7515
7516 // Lower single-element structs to just return a regular value.
7517 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7518 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7519
7520 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7521 const RecordDecl *RD = RT->getDecl();
7522 if (RD->hasFlexibleArrayMember())
7523 return DefaultABIInfo::classifyReturnType(RetTy);
7524 }
7525
7526 // Pack aggregates <= 4 bytes into single VGPR or pair.
7527 uint64_t Size = getContext().getTypeSize(RetTy);
7528 if (Size <= 16)
7529 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7530
7531 if (Size <= 32)
7532 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7533
7534 if (Size <= 64) {
7535 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7536 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7537 }
7538
7539 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7540 return ABIArgInfo::getDirect();
7541 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007542 }
7543
Matt Arsenault3fe73952017-08-09 21:44:58 +00007544 // Otherwise just do the default thing.
7545 return DefaultABIInfo::classifyReturnType(RetTy);
7546}
7547
7548/// For kernels all parameters are really passed in a special buffer. It doesn't
7549/// make sense to pass anything byval, so everything must be direct.
7550ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7551 Ty = useFirstFieldIfTransparentUnion(Ty);
7552
7553 // TODO: Can we omit empty structs?
7554
Matt Arsenault88d7da02016-08-22 19:25:59 +00007555 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007556 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7557 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007558
7559 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7560 // individual elements, which confuses the Clover OpenCL backend; therefore we
7561 // have to set it to false here. Other args of getDirect() are just defaults.
7562 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7563}
7564
Matt Arsenault3fe73952017-08-09 21:44:58 +00007565ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7566 unsigned &NumRegsLeft) const {
7567 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7568
7569 Ty = useFirstFieldIfTransparentUnion(Ty);
7570
7571 if (isAggregateTypeForABI(Ty)) {
7572 // Records with non-trivial destructors/copy-constructors should not be
7573 // passed by value.
7574 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7575 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7576
7577 // Ignore empty structs/unions.
7578 if (isEmptyRecord(getContext(), Ty, true))
7579 return ABIArgInfo::getIgnore();
7580
7581 // Lower single-element structs to just pass a regular value. TODO: We
7582 // could do reasonable-size multiple-element structs too, using getExpand(),
7583 // though watch out for things like bitfields.
7584 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7585 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7586
7587 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7588 const RecordDecl *RD = RT->getDecl();
7589 if (RD->hasFlexibleArrayMember())
7590 return DefaultABIInfo::classifyArgumentType(Ty);
7591 }
7592
7593 // Pack aggregates <= 8 bytes into single VGPR or pair.
7594 uint64_t Size = getContext().getTypeSize(Ty);
7595 if (Size <= 64) {
7596 unsigned NumRegs = (Size + 31) / 32;
7597 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7598
7599 if (Size <= 16)
7600 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7601
7602 if (Size <= 32)
7603 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7604
7605 // XXX: Should this be i64 instead, and should the limit increase?
7606 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7607 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7608 }
7609
7610 if (NumRegsLeft > 0) {
7611 unsigned NumRegs = numRegsForType(Ty);
7612 if (NumRegsLeft >= NumRegs) {
7613 NumRegsLeft -= NumRegs;
7614 return ABIArgInfo::getDirect();
7615 }
7616 }
7617 }
7618
7619 // Otherwise just do the default thing.
7620 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7621 if (!ArgInfo.isIndirect()) {
7622 unsigned NumRegs = numRegsForType(Ty);
7623 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7624 }
7625
7626 return ArgInfo;
7627}
7628
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007629class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7630public:
7631 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007632 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007633 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007634 CodeGen::CodeGenModule &M,
7635 ForDefinition_t IsForDefinition) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007636 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007637
Yaxun Liu402804b2016-12-15 08:09:08 +00007638 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7639 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007640
Alexander Richardson6d989432017-10-15 18:48:14 +00007641 LangAS getASTAllocaAddressSpace() const override {
7642 return getLangASFromTargetAS(
7643 getABIInfo().getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007644 }
Alexander Richardson6d989432017-10-15 18:48:14 +00007645 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7646 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007647 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7648 llvm::LLVMContext &C) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007649 llvm::Function *
7650 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7651 llvm::Function *BlockInvokeFunc,
7652 llvm::Value *BlockLiteral) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007653};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007654}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007655
Eric Christopher162c91c2015-06-05 22:03:00 +00007656void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007657 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7658 ForDefinition_t IsForDefinition) const {
7659 if (!IsForDefinition)
7660 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007661 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007662 if (!FD)
7663 return;
7664
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007665 llvm::Function *F = cast<llvm::Function>(GV);
7666
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007667 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7668 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7669 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7670 if (ReqdWGS || FlatWGS) {
7671 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7672 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7673 if (ReqdWGS && Min == 0 && Max == 0)
7674 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007675
7676 if (Min != 0) {
7677 assert(Min <= Max && "Min must be less than or equal Max");
7678
7679 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7680 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7681 } else
7682 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007683 }
7684
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007685 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7686 unsigned Min = Attr->getMin();
7687 unsigned Max = Attr->getMax();
7688
7689 if (Min != 0) {
7690 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7691
7692 std::string AttrVal = llvm::utostr(Min);
7693 if (Max != 0)
7694 AttrVal = AttrVal + "," + llvm::utostr(Max);
7695 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7696 } else
7697 assert(Max == 0 && "Max must be zero");
7698 }
7699
7700 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007701 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007702
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007703 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007704 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7705 }
7706
7707 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7708 uint32_t NumVGPR = Attr->getNumVGPR();
7709
7710 if (NumVGPR != 0)
7711 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007712 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007713}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007714
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007715unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7716 return llvm::CallingConv::AMDGPU_KERNEL;
7717}
7718
Yaxun Liu402804b2016-12-15 08:09:08 +00007719// Currently LLVM assumes null pointers always have value 0,
7720// which results in incorrectly transformed IR. Therefore, instead of
7721// emitting null pointers in private and local address spaces, a null
7722// pointer in generic address space is emitted which is casted to a
7723// pointer in local or private address space.
7724llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7725 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7726 QualType QT) const {
7727 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7728 return llvm::ConstantPointerNull::get(PT);
7729
7730 auto &Ctx = CGM.getContext();
7731 auto NPT = llvm::PointerType::get(PT->getElementType(),
7732 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7733 return llvm::ConstantExpr::getAddrSpaceCast(
7734 llvm::ConstantPointerNull::get(NPT), PT);
7735}
7736
Alexander Richardson6d989432017-10-15 18:48:14 +00007737LangAS
Yaxun Liucbf647c2017-07-08 13:24:52 +00007738AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7739 const VarDecl *D) const {
7740 assert(!CGM.getLangOpts().OpenCL &&
7741 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7742 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +00007743 LangAS DefaultGlobalAS = getLangASFromTargetAS(
7744 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007745 if (!D)
7746 return DefaultGlobalAS;
7747
Alexander Richardson6d989432017-10-15 18:48:14 +00007748 LangAS AddrSpace = D->getType().getAddressSpace();
7749 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007750 if (AddrSpace != LangAS::Default)
7751 return AddrSpace;
7752
7753 if (CGM.isTypeConstant(D->getType(), false)) {
7754 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7755 return ConstAS.getValue();
7756 }
7757 return DefaultGlobalAS;
7758}
7759
Yaxun Liu39195062017-08-04 18:16:31 +00007760llvm::SyncScope::ID
7761AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7762 llvm::LLVMContext &C) const {
7763 StringRef Name;
7764 switch (S) {
7765 case SyncScope::OpenCLWorkGroup:
7766 Name = "workgroup";
7767 break;
7768 case SyncScope::OpenCLDevice:
7769 Name = "agent";
7770 break;
7771 case SyncScope::OpenCLAllSVMDevices:
7772 Name = "";
7773 break;
7774 case SyncScope::OpenCLSubGroup:
7775 Name = "subgroup";
7776 }
7777 return C.getOrInsertSyncScopeID(Name);
7778}
7779
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007780//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007781// SPARC v8 ABI Implementation.
7782// Based on the SPARC Compliance Definition version 2.4.1.
7783//
7784// Ensures that complex values are passed in registers.
7785//
7786namespace {
7787class SparcV8ABIInfo : public DefaultABIInfo {
7788public:
7789 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7790
7791private:
7792 ABIArgInfo classifyReturnType(QualType RetTy) const;
7793 void computeInfo(CGFunctionInfo &FI) const override;
7794};
7795} // end anonymous namespace
7796
7797
7798ABIArgInfo
7799SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7800 if (Ty->isAnyComplexType()) {
7801 return ABIArgInfo::getDirect();
7802 }
7803 else {
7804 return DefaultABIInfo::classifyReturnType(Ty);
7805 }
7806}
7807
7808void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7809
7810 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7811 for (auto &Arg : FI.arguments())
7812 Arg.info = classifyArgumentType(Arg.type);
7813}
7814
7815namespace {
7816class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7817public:
7818 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7819 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7820};
7821} // end anonymous namespace
7822
7823//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007824// SPARC v9 ABI Implementation.
7825// Based on the SPARC Compliance Definition version 2.4.1.
7826//
7827// Function arguments a mapped to a nominal "parameter array" and promoted to
7828// registers depending on their type. Each argument occupies 8 or 16 bytes in
7829// the array, structs larger than 16 bytes are passed indirectly.
7830//
7831// One case requires special care:
7832//
7833// struct mixed {
7834// int i;
7835// float f;
7836// };
7837//
7838// When a struct mixed is passed by value, it only occupies 8 bytes in the
7839// parameter array, but the int is passed in an integer register, and the float
7840// is passed in a floating point register. This is represented as two arguments
7841// with the LLVM IR inreg attribute:
7842//
7843// declare void f(i32 inreg %i, float inreg %f)
7844//
7845// The code generator will only allocate 4 bytes from the parameter array for
7846// the inreg arguments. All other arguments are allocated a multiple of 8
7847// bytes.
7848//
7849namespace {
7850class SparcV9ABIInfo : public ABIInfo {
7851public:
7852 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7853
7854private:
7855 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007856 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007857 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7858 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007859
7860 // Coercion type builder for structs passed in registers. The coercion type
7861 // serves two purposes:
7862 //
7863 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7864 // in registers.
7865 // 2. Expose aligned floating point elements as first-level elements, so the
7866 // code generator knows to pass them in floating point registers.
7867 //
7868 // We also compute the InReg flag which indicates that the struct contains
7869 // aligned 32-bit floats.
7870 //
7871 struct CoerceBuilder {
7872 llvm::LLVMContext &Context;
7873 const llvm::DataLayout &DL;
7874 SmallVector<llvm::Type*, 8> Elems;
7875 uint64_t Size;
7876 bool InReg;
7877
7878 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7879 : Context(c), DL(dl), Size(0), InReg(false) {}
7880
7881 // Pad Elems with integers until Size is ToSize.
7882 void pad(uint64_t ToSize) {
7883 assert(ToSize >= Size && "Cannot remove elements");
7884 if (ToSize == Size)
7885 return;
7886
7887 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007888 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007889 if (Aligned > Size && Aligned <= ToSize) {
7890 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7891 Size = Aligned;
7892 }
7893
7894 // Add whole 64-bit words.
7895 while (Size + 64 <= ToSize) {
7896 Elems.push_back(llvm::Type::getInt64Ty(Context));
7897 Size += 64;
7898 }
7899
7900 // Final in-word padding.
7901 if (Size < ToSize) {
7902 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7903 Size = ToSize;
7904 }
7905 }
7906
7907 // Add a floating point element at Offset.
7908 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7909 // Unaligned floats are treated as integers.
7910 if (Offset % Bits)
7911 return;
7912 // The InReg flag is only required if there are any floats < 64 bits.
7913 if (Bits < 64)
7914 InReg = true;
7915 pad(Offset);
7916 Elems.push_back(Ty);
7917 Size = Offset + Bits;
7918 }
7919
7920 // Add a struct type to the coercion type, starting at Offset (in bits).
7921 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7922 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7923 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7924 llvm::Type *ElemTy = StrTy->getElementType(i);
7925 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7926 switch (ElemTy->getTypeID()) {
7927 case llvm::Type::StructTyID:
7928 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7929 break;
7930 case llvm::Type::FloatTyID:
7931 addFloat(ElemOffset, ElemTy, 32);
7932 break;
7933 case llvm::Type::DoubleTyID:
7934 addFloat(ElemOffset, ElemTy, 64);
7935 break;
7936 case llvm::Type::FP128TyID:
7937 addFloat(ElemOffset, ElemTy, 128);
7938 break;
7939 case llvm::Type::PointerTyID:
7940 if (ElemOffset % 64 == 0) {
7941 pad(ElemOffset);
7942 Elems.push_back(ElemTy);
7943 Size += 64;
7944 }
7945 break;
7946 default:
7947 break;
7948 }
7949 }
7950 }
7951
7952 // Check if Ty is a usable substitute for the coercion type.
7953 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007954 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007955 }
7956
7957 // Get the coercion type as a literal struct type.
7958 llvm::Type *getType() const {
7959 if (Elems.size() == 1)
7960 return Elems.front();
7961 else
7962 return llvm::StructType::get(Context, Elems);
7963 }
7964 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007965};
7966} // end anonymous namespace
7967
7968ABIArgInfo
7969SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7970 if (Ty->isVoidType())
7971 return ABIArgInfo::getIgnore();
7972
7973 uint64_t Size = getContext().getTypeSize(Ty);
7974
7975 // Anything too big to fit in registers is passed with an explicit indirect
7976 // pointer / sret pointer.
7977 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007978 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007979
7980 // Treat an enum type as its underlying type.
7981 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7982 Ty = EnumTy->getDecl()->getIntegerType();
7983
7984 // Integer types smaller than a register are extended.
7985 if (Size < 64 && Ty->isIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00007986 return ABIArgInfo::getExtend(Ty);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007987
7988 // Other non-aggregates go in registers.
7989 if (!isAggregateTypeForABI(Ty))
7990 return ABIArgInfo::getDirect();
7991
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007992 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7993 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7994 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007995 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007996
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007997 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007998 // Build a coercion type from the LLVM struct type.
7999 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8000 if (!StrTy)
8001 return ABIArgInfo::getDirect();
8002
8003 CoerceBuilder CB(getVMContext(), getDataLayout());
8004 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00008005 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008006
8007 // Try to use the original type for coercion.
8008 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8009
8010 if (CB.InReg)
8011 return ABIArgInfo::getDirectInReg(CoerceTy);
8012 else
8013 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008014}
8015
John McCall7f416cc2015-09-08 08:05:57 +00008016Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8017 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008018 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8019 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8020 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8021 AI.setCoerceToType(ArgTy);
8022
John McCall7f416cc2015-09-08 08:05:57 +00008023 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008024
John McCall7f416cc2015-09-08 08:05:57 +00008025 CGBuilderTy &Builder = CGF.Builder;
8026 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8027 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8028
8029 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8030
8031 Address ArgAddr = Address::invalid();
8032 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008033 switch (AI.getKind()) {
8034 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008035 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008036 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008037 llvm_unreachable("Unsupported ABI kind for va_arg");
8038
John McCall7f416cc2015-09-08 08:05:57 +00008039 case ABIArgInfo::Extend: {
8040 Stride = SlotSize;
8041 CharUnits Offset = SlotSize - TypeInfo.first;
8042 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008043 break;
John McCall7f416cc2015-09-08 08:05:57 +00008044 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008045
John McCall7f416cc2015-09-08 08:05:57 +00008046 case ABIArgInfo::Direct: {
8047 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008048 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008049 ArgAddr = Addr;
8050 break;
John McCall7f416cc2015-09-08 08:05:57 +00008051 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008052
8053 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008054 Stride = SlotSize;
8055 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8056 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8057 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008058 break;
8059
8060 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008061 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008062 }
8063
8064 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008065 llvm::Value *NextPtr =
8066 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8067 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008068
John McCall7f416cc2015-09-08 08:05:57 +00008069 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008070}
8071
8072void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8073 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008074 for (auto &I : FI.arguments())
8075 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008076}
8077
8078namespace {
8079class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8080public:
8081 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8082 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008083
Craig Topper4f12f102014-03-12 06:41:41 +00008084 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008085 return 14;
8086 }
8087
8088 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008089 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008090};
8091} // end anonymous namespace
8092
Roman Divackyf02c9942014-02-24 18:46:27 +00008093bool
8094SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8095 llvm::Value *Address) const {
8096 // This is calculated from the LLVM and GCC tables and verified
8097 // against gcc output. AFAIK all ABIs use the same encoding.
8098
8099 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8100
8101 llvm::IntegerType *i8 = CGF.Int8Ty;
8102 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8103 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8104
8105 // 0-31: the 8-byte general-purpose registers
8106 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8107
8108 // 32-63: f0-31, the 4-byte floating-point registers
8109 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8110
8111 // Y = 64
8112 // PSR = 65
8113 // WIM = 66
8114 // TBR = 67
8115 // PC = 68
8116 // NPC = 69
8117 // FSR = 70
8118 // CSR = 71
8119 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008120
Roman Divackyf02c9942014-02-24 18:46:27 +00008121 // 72-87: d0-15, the 8-byte floating-point registers
8122 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8123
8124 return false;
8125}
8126
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008127
Robert Lytton0e076492013-08-13 09:43:10 +00008128//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008129// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008130//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008131
Robert Lytton0e076492013-08-13 09:43:10 +00008132namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008133
8134/// A SmallStringEnc instance is used to build up the TypeString by passing
8135/// it by reference between functions that append to it.
8136typedef llvm::SmallString<128> SmallStringEnc;
8137
8138/// TypeStringCache caches the meta encodings of Types.
8139///
8140/// The reason for caching TypeStrings is two fold:
8141/// 1. To cache a type's encoding for later uses;
8142/// 2. As a means to break recursive member type inclusion.
8143///
8144/// A cache Entry can have a Status of:
8145/// NonRecursive: The type encoding is not recursive;
8146/// Recursive: The type encoding is recursive;
8147/// Incomplete: An incomplete TypeString;
8148/// IncompleteUsed: An incomplete TypeString that has been used in a
8149/// Recursive type encoding.
8150///
8151/// A NonRecursive entry will have all of its sub-members expanded as fully
8152/// as possible. Whilst it may contain types which are recursive, the type
8153/// itself is not recursive and thus its encoding may be safely used whenever
8154/// the type is encountered.
8155///
8156/// A Recursive entry will have all of its sub-members expanded as fully as
8157/// possible. The type itself is recursive and it may contain other types which
8158/// are recursive. The Recursive encoding must not be used during the expansion
8159/// of a recursive type's recursive branch. For simplicity the code uses
8160/// IncompleteCount to reject all usage of Recursive encodings for member types.
8161///
8162/// An Incomplete entry is always a RecordType and only encodes its
8163/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8164/// are placed into the cache during type expansion as a means to identify and
8165/// handle recursive inclusion of types as sub-members. If there is recursion
8166/// the entry becomes IncompleteUsed.
8167///
8168/// During the expansion of a RecordType's members:
8169///
8170/// If the cache contains a NonRecursive encoding for the member type, the
8171/// cached encoding is used;
8172///
8173/// If the cache contains a Recursive encoding for the member type, the
8174/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8175///
8176/// If the member is a RecordType, an Incomplete encoding is placed into the
8177/// cache to break potential recursive inclusion of itself as a sub-member;
8178///
8179/// Once a member RecordType has been expanded, its temporary incomplete
8180/// entry is removed from the cache. If a Recursive encoding was swapped out
8181/// it is swapped back in;
8182///
8183/// If an incomplete entry is used to expand a sub-member, the incomplete
8184/// entry is marked as IncompleteUsed. The cache keeps count of how many
8185/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8186///
8187/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8188/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8189/// Else the member is part of a recursive type and thus the recursion has
8190/// been exited too soon for the encoding to be correct for the member.
8191///
8192class TypeStringCache {
8193 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8194 struct Entry {
8195 std::string Str; // The encoded TypeString for the type.
8196 enum Status State; // Information about the encoding in 'Str'.
8197 std::string Swapped; // A temporary place holder for a Recursive encoding
8198 // during the expansion of RecordType's members.
8199 };
8200 std::map<const IdentifierInfo *, struct Entry> Map;
8201 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8202 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8203public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008204 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008205 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8206 bool removeIncomplete(const IdentifierInfo *ID);
8207 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8208 bool IsRecursive);
8209 StringRef lookupStr(const IdentifierInfo *ID);
8210};
8211
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008212/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008213/// FieldEncoding is a helper for this ordering process.
8214class FieldEncoding {
8215 bool HasName;
8216 std::string Enc;
8217public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008218 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008219 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008220 bool operator<(const FieldEncoding &rhs) const {
8221 if (HasName != rhs.HasName) return HasName;
8222 return Enc < rhs.Enc;
8223 }
8224};
8225
Robert Lytton7d1db152013-08-19 09:46:39 +00008226class XCoreABIInfo : public DefaultABIInfo {
8227public:
8228 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008229 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8230 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008231};
8232
Robert Lyttond21e2d72014-03-03 13:45:29 +00008233class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008234 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008235public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008236 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008237 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008238 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8239 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008240};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008241
Robert Lytton2d196952013-10-11 10:29:34 +00008242} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008243
James Y Knight29b5f082016-02-24 02:59:33 +00008244// TODO: this implementation is likely now redundant with the default
8245// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008246Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8247 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008248 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008249
Robert Lytton2d196952013-10-11 10:29:34 +00008250 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008251 CharUnits SlotSize = CharUnits::fromQuantity(4);
8252 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008253
Robert Lytton2d196952013-10-11 10:29:34 +00008254 // Handle the argument.
8255 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008256 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008257 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8258 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8259 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008260 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008261
8262 Address Val = Address::invalid();
8263 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008264 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008265 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008266 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008267 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008268 llvm_unreachable("Unsupported ABI kind for va_arg");
8269 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008270 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8271 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008272 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008273 case ABIArgInfo::Extend:
8274 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008275 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8276 ArgSize = CharUnits::fromQuantity(
8277 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008278 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008279 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008280 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008281 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8282 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8283 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008284 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008285 }
Robert Lytton2d196952013-10-11 10:29:34 +00008286
8287 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008288 if (!ArgSize.isZero()) {
8289 llvm::Value *APN =
8290 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8291 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008292 }
John McCall7f416cc2015-09-08 08:05:57 +00008293
Robert Lytton2d196952013-10-11 10:29:34 +00008294 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008295}
Robert Lytton0e076492013-08-13 09:43:10 +00008296
Robert Lytton844aeeb2014-05-02 09:33:20 +00008297/// During the expansion of a RecordType, an incomplete TypeString is placed
8298/// into the cache as a means to identify and break recursion.
8299/// If there is a Recursive encoding in the cache, it is swapped out and will
8300/// be reinserted by removeIncomplete().
8301/// All other types of encoding should have been used rather than arriving here.
8302void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8303 std::string StubEnc) {
8304 if (!ID)
8305 return;
8306 Entry &E = Map[ID];
8307 assert( (E.Str.empty() || E.State == Recursive) &&
8308 "Incorrectly use of addIncomplete");
8309 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8310 E.Swapped.swap(E.Str); // swap out the Recursive
8311 E.Str.swap(StubEnc);
8312 E.State = Incomplete;
8313 ++IncompleteCount;
8314}
8315
8316/// Once the RecordType has been expanded, the temporary incomplete TypeString
8317/// must be removed from the cache.
8318/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8319/// Returns true if the RecordType was defined recursively.
8320bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8321 if (!ID)
8322 return false;
8323 auto I = Map.find(ID);
8324 assert(I != Map.end() && "Entry not present");
8325 Entry &E = I->second;
8326 assert( (E.State == Incomplete ||
8327 E.State == IncompleteUsed) &&
8328 "Entry must be an incomplete type");
8329 bool IsRecursive = false;
8330 if (E.State == IncompleteUsed) {
8331 // We made use of our Incomplete encoding, thus we are recursive.
8332 IsRecursive = true;
8333 --IncompleteUsedCount;
8334 }
8335 if (E.Swapped.empty())
8336 Map.erase(I);
8337 else {
8338 // Swap the Recursive back.
8339 E.Swapped.swap(E.Str);
8340 E.Swapped.clear();
8341 E.State = Recursive;
8342 }
8343 --IncompleteCount;
8344 return IsRecursive;
8345}
8346
8347/// Add the encoded TypeString to the cache only if it is NonRecursive or
8348/// Recursive (viz: all sub-members were expanded as fully as possible).
8349void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8350 bool IsRecursive) {
8351 if (!ID || IncompleteUsedCount)
8352 return; // No key or it is is an incomplete sub-type so don't add.
8353 Entry &E = Map[ID];
8354 if (IsRecursive && !E.Str.empty()) {
8355 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8356 "This is not the same Recursive entry");
8357 // The parent container was not recursive after all, so we could have used
8358 // this Recursive sub-member entry after all, but we assumed the worse when
8359 // we started viz: IncompleteCount!=0.
8360 return;
8361 }
8362 assert(E.Str.empty() && "Entry already present");
8363 E.Str = Str.str();
8364 E.State = IsRecursive? Recursive : NonRecursive;
8365}
8366
8367/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8368/// are recursively expanding a type (IncompleteCount != 0) and the cached
8369/// encoding is Recursive, return an empty StringRef.
8370StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8371 if (!ID)
8372 return StringRef(); // We have no key.
8373 auto I = Map.find(ID);
8374 if (I == Map.end())
8375 return StringRef(); // We have no encoding.
8376 Entry &E = I->second;
8377 if (E.State == Recursive && IncompleteCount)
8378 return StringRef(); // We don't use Recursive encodings for member types.
8379
8380 if (E.State == Incomplete) {
8381 // The incomplete type is being used to break out of recursion.
8382 E.State = IncompleteUsed;
8383 ++IncompleteUsedCount;
8384 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008385 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008386}
8387
8388/// The XCore ABI includes a type information section that communicates symbol
8389/// type information to the linker. The linker uses this information to verify
8390/// safety/correctness of things such as array bound and pointers et al.
8391/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8392/// This type information (TypeString) is emitted into meta data for all global
8393/// symbols: definitions, declarations, functions & variables.
8394///
8395/// The TypeString carries type, qualifier, name, size & value details.
8396/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008397/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008398/// The output is tested by test/CodeGen/xcore-stringtype.c.
8399///
8400static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8401 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8402
8403/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8404void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8405 CodeGen::CodeGenModule &CGM) const {
8406 SmallStringEnc Enc;
8407 if (getTypeString(Enc, D, CGM, TSC)) {
8408 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008409 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8410 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008411 llvm::NamedMDNode *MD =
8412 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8413 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8414 }
8415}
8416
Xiuli Pan972bea82016-03-24 03:57:17 +00008417//===----------------------------------------------------------------------===//
8418// SPIR ABI Implementation
8419//===----------------------------------------------------------------------===//
8420
8421namespace {
8422class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8423public:
8424 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8425 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008426 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008427};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008428
Xiuli Pan972bea82016-03-24 03:57:17 +00008429} // End anonymous namespace.
8430
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008431namespace clang {
8432namespace CodeGen {
8433void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8434 DefaultABIInfo SPIRABI(CGM.getTypes());
8435 SPIRABI.computeInfo(FI);
8436}
8437}
8438}
8439
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008440unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8441 return llvm::CallingConv::SPIR_KERNEL;
8442}
8443
Robert Lytton844aeeb2014-05-02 09:33:20 +00008444static bool appendType(SmallStringEnc &Enc, QualType QType,
8445 const CodeGen::CodeGenModule &CGM,
8446 TypeStringCache &TSC);
8447
8448/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008449/// Builds a SmallVector containing the encoded field types in declaration
8450/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008451static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8452 const RecordDecl *RD,
8453 const CodeGen::CodeGenModule &CGM,
8454 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008455 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008456 SmallStringEnc Enc;
8457 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008458 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008459 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008460 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008461 Enc += "b(";
8462 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008463 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008464 Enc += ':';
8465 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008466 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008467 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008468 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008469 Enc += ')';
8470 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008471 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008472 }
8473 return true;
8474}
8475
8476/// Appends structure and union types to Enc and adds encoding to cache.
8477/// Recursively calls appendType (via extractFieldType) for each field.
8478/// Union types have their fields ordered according to the ABI.
8479static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8480 const CodeGen::CodeGenModule &CGM,
8481 TypeStringCache &TSC, const IdentifierInfo *ID) {
8482 // Append the cached TypeString if we have one.
8483 StringRef TypeString = TSC.lookupStr(ID);
8484 if (!TypeString.empty()) {
8485 Enc += TypeString;
8486 return true;
8487 }
8488
8489 // Start to emit an incomplete TypeString.
8490 size_t Start = Enc.size();
8491 Enc += (RT->isUnionType()? 'u' : 's');
8492 Enc += '(';
8493 if (ID)
8494 Enc += ID->getName();
8495 Enc += "){";
8496
8497 // We collect all encoded fields and order as necessary.
8498 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008499 const RecordDecl *RD = RT->getDecl()->getDefinition();
8500 if (RD && !RD->field_empty()) {
8501 // An incomplete TypeString stub is placed in the cache for this RecordType
8502 // so that recursive calls to this RecordType will use it whilst building a
8503 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008504 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008505 std::string StubEnc(Enc.substr(Start).str());
8506 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8507 TSC.addIncomplete(ID, std::move(StubEnc));
8508 if (!extractFieldType(FE, RD, CGM, TSC)) {
8509 (void) TSC.removeIncomplete(ID);
8510 return false;
8511 }
8512 IsRecursive = TSC.removeIncomplete(ID);
8513 // The ABI requires unions to be sorted but not structures.
8514 // See FieldEncoding::operator< for sort algorithm.
8515 if (RT->isUnionType())
8516 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008517 // We can now complete the TypeString.
8518 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008519 for (unsigned I = 0; I != E; ++I) {
8520 if (I)
8521 Enc += ',';
8522 Enc += FE[I].str();
8523 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008524 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008525 Enc += '}';
8526 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8527 return true;
8528}
8529
8530/// Appends enum types to Enc and adds the encoding to the cache.
8531static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8532 TypeStringCache &TSC,
8533 const IdentifierInfo *ID) {
8534 // Append the cached TypeString if we have one.
8535 StringRef TypeString = TSC.lookupStr(ID);
8536 if (!TypeString.empty()) {
8537 Enc += TypeString;
8538 return true;
8539 }
8540
8541 size_t Start = Enc.size();
8542 Enc += "e(";
8543 if (ID)
8544 Enc += ID->getName();
8545 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008546
8547 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008548 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008549 SmallVector<FieldEncoding, 16> FE;
8550 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8551 ++I) {
8552 SmallStringEnc EnumEnc;
8553 EnumEnc += "m(";
8554 EnumEnc += I->getName();
8555 EnumEnc += "){";
8556 I->getInitVal().toString(EnumEnc);
8557 EnumEnc += '}';
8558 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8559 }
8560 std::sort(FE.begin(), FE.end());
8561 unsigned E = FE.size();
8562 for (unsigned I = 0; I != E; ++I) {
8563 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008564 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008565 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008566 }
8567 }
8568 Enc += '}';
8569 TSC.addIfComplete(ID, Enc.substr(Start), false);
8570 return true;
8571}
8572
8573/// Appends type's qualifier to Enc.
8574/// This is done prior to appending the type's encoding.
8575static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8576 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008577 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008578 int Lookup = 0;
8579 if (QT.isConstQualified())
8580 Lookup += 1<<0;
8581 if (QT.isRestrictQualified())
8582 Lookup += 1<<1;
8583 if (QT.isVolatileQualified())
8584 Lookup += 1<<2;
8585 Enc += Table[Lookup];
8586}
8587
8588/// Appends built-in types to Enc.
8589static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8590 const char *EncType;
8591 switch (BT->getKind()) {
8592 case BuiltinType::Void:
8593 EncType = "0";
8594 break;
8595 case BuiltinType::Bool:
8596 EncType = "b";
8597 break;
8598 case BuiltinType::Char_U:
8599 EncType = "uc";
8600 break;
8601 case BuiltinType::UChar:
8602 EncType = "uc";
8603 break;
8604 case BuiltinType::SChar:
8605 EncType = "sc";
8606 break;
8607 case BuiltinType::UShort:
8608 EncType = "us";
8609 break;
8610 case BuiltinType::Short:
8611 EncType = "ss";
8612 break;
8613 case BuiltinType::UInt:
8614 EncType = "ui";
8615 break;
8616 case BuiltinType::Int:
8617 EncType = "si";
8618 break;
8619 case BuiltinType::ULong:
8620 EncType = "ul";
8621 break;
8622 case BuiltinType::Long:
8623 EncType = "sl";
8624 break;
8625 case BuiltinType::ULongLong:
8626 EncType = "ull";
8627 break;
8628 case BuiltinType::LongLong:
8629 EncType = "sll";
8630 break;
8631 case BuiltinType::Float:
8632 EncType = "ft";
8633 break;
8634 case BuiltinType::Double:
8635 EncType = "d";
8636 break;
8637 case BuiltinType::LongDouble:
8638 EncType = "ld";
8639 break;
8640 default:
8641 return false;
8642 }
8643 Enc += EncType;
8644 return true;
8645}
8646
8647/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8648static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8649 const CodeGen::CodeGenModule &CGM,
8650 TypeStringCache &TSC) {
8651 Enc += "p(";
8652 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8653 return false;
8654 Enc += ')';
8655 return true;
8656}
8657
8658/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008659static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8660 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008661 const CodeGen::CodeGenModule &CGM,
8662 TypeStringCache &TSC, StringRef NoSizeEnc) {
8663 if (AT->getSizeModifier() != ArrayType::Normal)
8664 return false;
8665 Enc += "a(";
8666 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8667 CAT->getSize().toStringUnsigned(Enc);
8668 else
8669 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8670 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008671 // The Qualifiers should be attached to the type rather than the array.
8672 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008673 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8674 return false;
8675 Enc += ')';
8676 return true;
8677}
8678
8679/// Appends a function encoding to Enc, calling appendType for the return type
8680/// and the arguments.
8681static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8682 const CodeGen::CodeGenModule &CGM,
8683 TypeStringCache &TSC) {
8684 Enc += "f{";
8685 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8686 return false;
8687 Enc += "}(";
8688 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8689 // N.B. we are only interested in the adjusted param types.
8690 auto I = FPT->param_type_begin();
8691 auto E = FPT->param_type_end();
8692 if (I != E) {
8693 do {
8694 if (!appendType(Enc, *I, CGM, TSC))
8695 return false;
8696 ++I;
8697 if (I != E)
8698 Enc += ',';
8699 } while (I != E);
8700 if (FPT->isVariadic())
8701 Enc += ",va";
8702 } else {
8703 if (FPT->isVariadic())
8704 Enc += "va";
8705 else
8706 Enc += '0';
8707 }
8708 }
8709 Enc += ')';
8710 return true;
8711}
8712
8713/// Handles the type's qualifier before dispatching a call to handle specific
8714/// type encodings.
8715static bool appendType(SmallStringEnc &Enc, QualType QType,
8716 const CodeGen::CodeGenModule &CGM,
8717 TypeStringCache &TSC) {
8718
8719 QualType QT = QType.getCanonicalType();
8720
Robert Lytton6adb20f2014-06-05 09:06:21 +00008721 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8722 // The Qualifiers should be attached to the type rather than the array.
8723 // Thus we don't call appendQualifier() here.
8724 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8725
Robert Lytton844aeeb2014-05-02 09:33:20 +00008726 appendQualifier(Enc, QT);
8727
8728 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8729 return appendBuiltinType(Enc, BT);
8730
Robert Lytton844aeeb2014-05-02 09:33:20 +00008731 if (const PointerType *PT = QT->getAs<PointerType>())
8732 return appendPointerType(Enc, PT, CGM, TSC);
8733
8734 if (const EnumType *ET = QT->getAs<EnumType>())
8735 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8736
8737 if (const RecordType *RT = QT->getAsStructureType())
8738 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8739
8740 if (const RecordType *RT = QT->getAsUnionType())
8741 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8742
8743 if (const FunctionType *FT = QT->getAs<FunctionType>())
8744 return appendFunctionType(Enc, FT, CGM, TSC);
8745
8746 return false;
8747}
8748
8749static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8750 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8751 if (!D)
8752 return false;
8753
8754 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8755 if (FD->getLanguageLinkage() != CLanguageLinkage)
8756 return false;
8757 return appendType(Enc, FD->getType(), CGM, TSC);
8758 }
8759
8760 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8761 if (VD->getLanguageLinkage() != CLanguageLinkage)
8762 return false;
8763 QualType QT = VD->getType().getCanonicalType();
8764 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8765 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008766 // The Qualifiers should be attached to the type rather than the array.
8767 // Thus we don't call appendQualifier() here.
8768 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008769 }
8770 return appendType(Enc, QT, CGM, TSC);
8771 }
8772 return false;
8773}
8774
Alex Bradbury8cbdd482018-01-15 17:54:52 +00008775//===----------------------------------------------------------------------===//
8776// RISCV ABI Implementation
8777//===----------------------------------------------------------------------===//
8778
8779namespace {
8780class RISCVABIInfo : public DefaultABIInfo {
8781private:
8782 unsigned XLen; // Size of the integer ('x') registers in bits.
8783 static const int NumArgGPRs = 8;
8784
8785public:
8786 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
8787 : DefaultABIInfo(CGT), XLen(XLen) {}
8788
8789 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
8790 // non-virtual, but computeInfo is virtual, so we overload it.
8791 void computeInfo(CGFunctionInfo &FI) const override;
8792
8793 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed,
8794 int &ArgGPRsLeft) const;
8795 ABIArgInfo classifyReturnType(QualType RetTy) const;
8796
8797 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8798 QualType Ty) const override;
8799
8800 ABIArgInfo extendType(QualType Ty) const;
8801};
8802} // end anonymous namespace
8803
8804void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
8805 QualType RetTy = FI.getReturnType();
8806 if (!getCXXABI().classifyReturnType(FI))
8807 FI.getReturnInfo() = classifyReturnType(RetTy);
8808
8809 // IsRetIndirect is true if classifyArgumentType indicated the value should
8810 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128
8811 // is passed direct in LLVM IR, relying on the backend lowering code to
8812 // rewrite the argument list and pass indirectly on RV32.
8813 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect ||
8814 getContext().getTypeSize(RetTy) > (2 * XLen);
8815
8816 // We must track the number of GPRs used in order to conform to the RISC-V
8817 // ABI, as integer scalars passed in registers should have signext/zeroext
8818 // when promoted, but are anyext if passed on the stack. As GPR usage is
8819 // different for variadic arguments, we must also track whether we are
8820 // examining a vararg or not.
8821 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
8822 int NumFixedArgs = FI.getNumRequiredArgs();
8823
8824 int ArgNum = 0;
8825 for (auto &ArgInfo : FI.arguments()) {
8826 bool IsFixed = ArgNum < NumFixedArgs;
8827 ArgInfo.info = classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft);
8828 ArgNum++;
8829 }
8830}
8831
8832ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
8833 int &ArgGPRsLeft) const {
8834 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
8835 Ty = useFirstFieldIfTransparentUnion(Ty);
8836
8837 // Structures with either a non-trivial destructor or a non-trivial
8838 // copy constructor are always passed indirectly.
8839 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8840 if (ArgGPRsLeft)
8841 ArgGPRsLeft -= 1;
8842 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
8843 CGCXXABI::RAA_DirectInMemory);
8844 }
8845
8846 // Ignore empty structs/unions.
8847 if (isEmptyRecord(getContext(), Ty, true))
8848 return ABIArgInfo::getIgnore();
8849
8850 uint64_t Size = getContext().getTypeSize(Ty);
8851 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
8852 bool MustUseStack = false;
8853 // Determine the number of GPRs needed to pass the current argument
8854 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
8855 // register pairs, so may consume 3 registers.
8856 int NeededArgGPRs = 1;
8857 if (!IsFixed && NeededAlign == 2 * XLen)
8858 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
8859 else if (Size > XLen && Size <= 2 * XLen)
8860 NeededArgGPRs = 2;
8861
8862 if (NeededArgGPRs > ArgGPRsLeft) {
8863 MustUseStack = true;
8864 NeededArgGPRs = ArgGPRsLeft;
8865 }
8866
8867 ArgGPRsLeft -= NeededArgGPRs;
8868
8869 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
8870 // Treat an enum type as its underlying type.
8871 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8872 Ty = EnumTy->getDecl()->getIntegerType();
8873
8874 // All integral types are promoted to XLen width, unless passed on the
8875 // stack.
8876 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
8877 return extendType(Ty);
8878 }
8879
8880 return ABIArgInfo::getDirect();
8881 }
8882
8883 // Aggregates which are <= 2*XLen will be passed in registers if possible,
8884 // so coerce to integers.
8885 if (Size <= 2 * XLen) {
8886 unsigned Alignment = getContext().getTypeAlign(Ty);
8887
8888 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
8889 // required, and a 2-element XLen array if only XLen alignment is required.
8890 if (Size <= XLen) {
8891 return ABIArgInfo::getDirect(
8892 llvm::IntegerType::get(getVMContext(), XLen));
8893 } else if (Alignment == 2 * XLen) {
8894 return ABIArgInfo::getDirect(
8895 llvm::IntegerType::get(getVMContext(), 2 * XLen));
8896 } else {
8897 return ABIArgInfo::getDirect(llvm::ArrayType::get(
8898 llvm::IntegerType::get(getVMContext(), XLen), 2));
8899 }
8900 }
8901 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
8902}
8903
8904ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
8905 if (RetTy->isVoidType())
8906 return ABIArgInfo::getIgnore();
8907
8908 int ArgGPRsLeft = 2;
8909
8910 // The rules for return and argument types are the same, so defer to
8911 // classifyArgumentType.
8912 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft);
8913}
8914
8915Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8916 QualType Ty) const {
8917 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
8918
8919 // Empty records are ignored for parameter passing purposes.
8920 if (isEmptyRecord(getContext(), Ty, true)) {
8921 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
8922 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
8923 return Addr;
8924 }
8925
8926 std::pair<CharUnits, CharUnits> SizeAndAlign =
8927 getContext().getTypeInfoInChars(Ty);
8928
8929 // Arguments bigger than 2*Xlen bytes are passed indirectly.
8930 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
8931
8932 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
8933 SlotSize, /*AllowHigherAlign=*/true);
8934}
8935
8936ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
8937 int TySize = getContext().getTypeSize(Ty);
8938 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
8939 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8940 return ABIArgInfo::getSignExtend(Ty);
8941 return ABIArgInfo::getExtend(Ty);
8942}
8943
8944namespace {
8945class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
8946public:
8947 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
8948 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen)) {}
8949};
8950} // namespace
Robert Lytton844aeeb2014-05-02 09:33:20 +00008951
Robert Lytton0e076492013-08-13 09:43:10 +00008952//===----------------------------------------------------------------------===//
8953// Driver code
8954//===----------------------------------------------------------------------===//
8955
Rafael Espindola9f834732014-09-19 01:54:22 +00008956bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008957 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008958}
8959
Chris Lattner2b037972010-07-29 02:01:43 +00008960const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008961 if (TheTargetCodeGenInfo)
8962 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008963
Reid Kleckner9305fd12016-04-13 23:37:17 +00008964 // Helper to set the unique_ptr while still keeping the return value.
8965 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8966 this->TheTargetCodeGenInfo.reset(P);
8967 return *P;
8968 };
8969
John McCallc8e01702013-04-16 22:48:15 +00008970 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008971 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008972 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008973 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008974
Derek Schuff09338a22012-09-06 17:37:28 +00008975 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008976 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008977 case llvm::Triple::mips:
8978 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008979 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008980 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8981 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008982
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008983 case llvm::Triple::mips64:
8984 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008985 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008986
Dylan McKaye8232d72017-02-08 05:09:26 +00008987 case llvm::Triple::avr:
8988 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8989
Tim Northover25e8a672014-05-24 12:51:25 +00008990 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008991 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008992 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008993 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008994 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00008995 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00008996 return SetCGInfo(
8997 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00008998
Reid Kleckner9305fd12016-04-13 23:37:17 +00008999 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00009000 }
9001
Dan Gohmanc2853072015-09-03 22:51:53 +00009002 case llvm::Triple::wasm32:
9003 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009004 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00009005
Daniel Dunbard59655c2009-09-12 00:59:49 +00009006 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00009007 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00009008 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009009 case llvm::Triple::thumbeb: {
9010 if (Triple.getOS() == llvm::Triple::Win32) {
9011 return SetCGInfo(
9012 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00009013 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00009014
Reid Kleckner9305fd12016-04-13 23:37:17 +00009015 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9016 StringRef ABIStr = getTarget().getABI();
9017 if (ABIStr == "apcs-gnu")
9018 Kind = ARMABIInfo::APCS;
9019 else if (ABIStr == "aapcs16")
9020 Kind = ARMABIInfo::AAPCS16_VFP;
9021 else if (CodeGenOpts.FloatABI == "hard" ||
9022 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009023 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00009024 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009025 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00009026 Kind = ARMABIInfo::AAPCS_VFP;
9027
9028 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9029 }
9030
John McCallea8d8bb2010-03-11 00:10:12 +00009031 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009032 return SetCGInfo(
9033 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00009034 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00009035 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00009036 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00009037 if (getTarget().getABI() == "elfv2")
9038 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009039 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009040 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009041
Hal Finkel415c2a32016-10-02 02:10:45 +00009042 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9043 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009044 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00009045 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009046 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00009047 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00009048 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009049 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00009050 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009051 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009052 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009053
Hal Finkel415c2a32016-10-02 02:10:45 +00009054 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9055 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009056 }
John McCallea8d8bb2010-03-11 00:10:12 +00009057
Peter Collingbournec947aae2012-05-20 23:28:41 +00009058 case llvm::Triple::nvptx:
9059 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009060 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00009061
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009062 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009063 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00009064
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009065 case llvm::Triple::riscv32:
9066 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 32));
9067 case llvm::Triple::riscv64:
9068 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 64));
9069
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009070 case llvm::Triple::systemz: {
9071 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00009072 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009073 }
Ulrich Weigand47445072013-05-06 16:26:41 +00009074
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009075 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00009076 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009077 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009078
Eli Friedman33465822011-07-08 23:31:17 +00009079 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00009080 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00009081 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00009082 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00009083 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00009084
John McCall1fe2a8c2013-06-18 02:46:29 +00009085 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009086 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9087 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9088 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00009089 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009090 return SetCGInfo(new X86_32TargetCodeGenInfo(
9091 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9092 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
9093 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009094 }
Eli Friedman33465822011-07-08 23:31:17 +00009095 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009096
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009097 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009098 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00009099 X86AVXABILevel AVXLevel =
9100 (ABI == "avx512"
9101 ? X86AVXABILevel::AVX512
9102 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009103
Chris Lattner04dc9572010-08-31 16:44:54 +00009104 switch (Triple.getOS()) {
9105 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009106 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00009107 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009108 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009109 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009110 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009111 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00009112 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00009113 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009114 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00009115 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009116 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00009117 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009118 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00009119 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009120 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00009121 case llvm::Triple::sparc:
9122 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00009123 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009124 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00009125 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009126 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00009127 case llvm::Triple::spir:
9128 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009129 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009130 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009131}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009132
9133/// Create an OpenCL kernel for an enqueued block.
9134///
9135/// The kernel has the same function type as the block invoke function. Its
9136/// name is the name of the block invoke function postfixed with "_kernel".
9137/// It simply calls the block invoke function then returns.
9138llvm::Function *
9139TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
9140 llvm::Function *Invoke,
9141 llvm::Value *BlockLiteral) const {
9142 auto *InvokeFT = Invoke->getFunctionType();
9143 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9144 for (auto &P : InvokeFT->params())
9145 ArgTys.push_back(P);
9146 auto &C = CGF.getLLVMContext();
9147 std::string Name = Invoke->getName().str() + "_kernel";
9148 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9149 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9150 &CGF.CGM.getModule());
9151 auto IP = CGF.Builder.saveIP();
9152 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9153 auto &Builder = CGF.Builder;
9154 Builder.SetInsertPoint(BB);
9155 llvm::SmallVector<llvm::Value *, 2> Args;
9156 for (auto &A : F->args())
9157 Args.push_back(&A);
9158 Builder.CreateCall(Invoke, Args);
9159 Builder.CreateRetVoid();
9160 Builder.restoreIP(IP);
9161 return F;
9162}
9163
9164/// Create an OpenCL kernel for an enqueued block.
9165///
9166/// The type of the first argument (the block literal) is the struct type
9167/// of the block literal instead of a pointer type. The first argument
9168/// (block literal) is passed directly by value to the kernel. The kernel
9169/// allocates the same type of struct on stack and stores the block literal
9170/// to it and passes its pointer to the block invoke function. The kernel
9171/// has "enqueued-block" function attribute and kernel argument metadata.
9172llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
9173 CodeGenFunction &CGF, llvm::Function *Invoke,
9174 llvm::Value *BlockLiteral) const {
9175 auto &Builder = CGF.Builder;
9176 auto &C = CGF.getLLVMContext();
9177
9178 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
9179 auto *InvokeFT = Invoke->getFunctionType();
9180 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9181 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
9182 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
9183 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
9184 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
9185 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
9186 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
9187
9188 ArgTys.push_back(BlockTy);
9189 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9190 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
9191 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9192 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9193 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9194 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
9195 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
9196 ArgTys.push_back(InvokeFT->getParamType(I));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009197 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
9198 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
9199 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9200 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
9201 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9202 ArgNames.push_back(
Yaxun Liu98f0c432017-10-14 12:51:52 +00009203 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009204 }
9205 std::string Name = Invoke->getName().str() + "_kernel";
9206 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9207 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9208 &CGF.CGM.getModule());
9209 F->addFnAttr("enqueued-block");
9210 auto IP = CGF.Builder.saveIP();
9211 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9212 Builder.SetInsertPoint(BB);
9213 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9214 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9215 BlockPtr->setAlignment(BlockAlign);
9216 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9217 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9218 llvm::SmallVector<llvm::Value *, 2> Args;
9219 Args.push_back(Cast);
9220 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9221 Args.push_back(I);
9222 Builder.CreateCall(Invoke, Args);
9223 Builder.CreateRetVoid();
9224 Builder.restoreIP(IP);
9225
9226 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9227 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9228 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9229 F->setMetadata("kernel_arg_base_type",
9230 llvm::MDNode::get(C, ArgBaseTypeNames));
9231 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9232 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9233 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
9234
9235 return F;
9236}