blob: 9fd4a5fb17a7b63504737fb9a7c756a86b71ee85 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006//
7//===----------------------------------------------------------------------===//
8//
9// These classes wrap the information about a call or function
10// definition used to handle ABI compliancy.
11//
12//===----------------------------------------------------------------------===//
13
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000014#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000015#include "ABIInfo.h"
Yaxun Liuc2a87a02017-10-14 12:23:50 +000016#include "CGBlocks.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Reid Kleckner98031782019-12-09 16:11:56 -080020#include "clang/AST/Attr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Richard Trieu63688182018-12-11 03:18:39 +000022#include "clang/Basic/CodeGenOptions.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000024#include "clang/CodeGen/SwiftCallingConv.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"
Reid Kleckner98031782019-12-09 16:11:56 -080032#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());
Akira Hatanakad791e922018-03-19 17:38:40 +0000143 if (!RD) {
144 if (!RT->getDecl()->canPassInRegisters())
145 return CGCXXABI::RAA_Indirect;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000146 return CGCXXABI::RAA_Default;
Akira Hatanakad791e922018-03-19 17:38:40 +0000147 }
Mark Lacey3825e832013-10-06 01:33:34 +0000148 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000149}
150
151static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000152 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000153 const RecordType *RT = T->getAs<RecordType>();
154 if (!RT)
155 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000156 return getRecordArgABI(RT, CXXABI);
157}
158
Akira Hatanakad791e922018-03-19 17:38:40 +0000159static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
160 const ABIInfo &Info) {
161 QualType Ty = FI.getReturnType();
162
163 if (const auto *RT = Ty->getAs<RecordType>())
164 if (!isa<CXXRecordDecl>(RT->getDecl()) &&
165 !RT->getDecl()->canPassInRegisters()) {
166 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
167 return true;
168 }
169
170 return CXXABI.classifyReturnType(FI);
171}
172
Reid Klecknerb1be6832014-11-15 01:41:41 +0000173/// Pass transparent unions as if they were the type of the first element. Sema
174/// should ensure that all elements of the union have the same "machine type".
175static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
176 if (const RecordType *UT = Ty->getAsUnionType()) {
177 const RecordDecl *UD = UT->getDecl();
178 if (UD->hasAttr<TransparentUnionAttr>()) {
179 assert(!UD->field_empty() && "sema created an empty transparent union");
180 return UD->field_begin()->getType();
181 }
182 }
183 return Ty;
184}
185
Mark Lacey3825e832013-10-06 01:33:34 +0000186CGCXXABI &ABIInfo::getCXXABI() const {
187 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000188}
189
Chris Lattner2b037972010-07-29 02:01:43 +0000190ASTContext &ABIInfo::getContext() const {
191 return CGT.getContext();
192}
193
194llvm::LLVMContext &ABIInfo::getVMContext() const {
195 return CGT.getLLVMContext();
196}
197
Micah Villmowdd31ca12012-10-08 16:25:52 +0000198const llvm::DataLayout &ABIInfo::getDataLayout() const {
199 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000200}
201
John McCallc8e01702013-04-16 22:48:15 +0000202const TargetInfo &ABIInfo::getTarget() const {
203 return CGT.getTarget();
204}
Chris Lattner2b037972010-07-29 02:01:43 +0000205
Richard Smithf667ad52017-08-26 01:04:35 +0000206const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
207 return CGT.getCodeGenOpts();
208}
209
210bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000211
Reid Klecknere9f6a712014-10-31 17:10:41 +0000212bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
213 return false;
214}
215
216bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
217 uint64_t Members) const {
218 return false;
219}
220
Yaron Kerencdae9412016-01-29 19:38:18 +0000221LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000222 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000223 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000224 switch (TheKind) {
225 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000226 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000227 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000228 Ty->print(OS);
229 else
230 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000231 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000232 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000233 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000234 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000235 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000236 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000237 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000238 case InAlloca:
239 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
240 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000241 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000242 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000243 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000244 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000245 break;
246 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000247 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000248 break;
John McCallf26e73d2016-03-11 04:30:43 +0000249 case CoerceAndExpand:
250 OS << "CoerceAndExpand Type=";
251 getCoerceAndExpandType()->print(OS);
252 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000253 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000254 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000255}
256
Petar Jovanovic402257b2015-12-04 00:26:47 +0000257// Dynamically round a pointer up to a multiple of the given alignment.
258static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
259 llvm::Value *Ptr,
260 CharUnits Align) {
261 llvm::Value *PtrAsInt = Ptr;
262 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
263 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
264 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
265 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
266 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
267 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
268 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
269 Ptr->getType(),
270 Ptr->getName() + ".aligned");
271 return PtrAsInt;
272}
273
John McCall7f416cc2015-09-08 08:05:57 +0000274/// Emit va_arg for a platform using the common void* representation,
275/// where arguments are simply emitted in an array of slots on the stack.
276///
277/// This version implements the core direct-value passing rules.
278///
279/// \param SlotSize - The size and alignment of a stack slot.
280/// Each argument will be allocated to a multiple of this number of
281/// slots, and all the slots will be aligned to this value.
282/// \param AllowHigherAlign - The slot alignment is not a cap;
283/// an argument type with an alignment greater than the slot size
284/// will be emitted on a higher-alignment address, potentially
285/// leaving one or more empty slots behind as padding. If this
286/// is false, the returned address might be less-aligned than
287/// DirectAlign.
288static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
289 Address VAListAddr,
290 llvm::Type *DirectTy,
291 CharUnits DirectSize,
292 CharUnits DirectAlign,
293 CharUnits SlotSize,
294 bool AllowHigherAlign) {
295 // Cast the element type to i8* if necessary. Some platforms define
296 // va_list as a struct containing an i8* instead of just an i8*.
297 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
298 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
299
300 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
301
302 // If the CC aligns values higher than the slot size, do so if needed.
303 Address Addr = Address::invalid();
304 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000305 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
306 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000307 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000308 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000309 }
310
311 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000312 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
James Y Knight3d2df5a2019-02-05 19:01:33 +0000313 Address NextPtr =
314 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
315 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000316
317 // If the argument is smaller than a slot, and this is a big-endian
318 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000319 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
320 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000321 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
322 }
323
324 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
325 return Addr;
326}
327
328/// Emit va_arg for a platform using the common void* representation,
329/// where arguments are simply emitted in an array of slots on the stack.
330///
331/// \param IsIndirect - Values of this type are passed indirectly.
332/// \param ValueInfo - The size and alignment of this type, generally
333/// computed with getContext().getTypeInfoInChars(ValueTy).
334/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
335/// Each argument will be allocated to a multiple of this number of
336/// slots, and all the slots will be aligned to this value.
337/// \param AllowHigherAlign - The slot alignment is not a cap;
338/// an argument type with an alignment greater than the slot size
339/// will be emitted on a higher-alignment address, potentially
340/// leaving one or more empty slots behind as padding.
341static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
342 QualType ValueTy, bool IsIndirect,
343 std::pair<CharUnits, CharUnits> ValueInfo,
344 CharUnits SlotSizeAndAlign,
345 bool AllowHigherAlign) {
346 // The size and alignment of the value that was passed directly.
347 CharUnits DirectSize, DirectAlign;
348 if (IsIndirect) {
349 DirectSize = CGF.getPointerSize();
350 DirectAlign = CGF.getPointerAlign();
351 } else {
352 DirectSize = ValueInfo.first;
353 DirectAlign = ValueInfo.second;
354 }
355
356 // Cast the address we've calculated to the right type.
357 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
358 if (IsIndirect)
359 DirectTy = DirectTy->getPointerTo(0);
360
361 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
362 DirectSize, DirectAlign,
363 SlotSizeAndAlign,
364 AllowHigherAlign);
365
366 if (IsIndirect) {
367 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
368 }
369
370 return Addr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000371
John McCall7f416cc2015-09-08 08:05:57 +0000372}
373
374static Address emitMergePHI(CodeGenFunction &CGF,
375 Address Addr1, llvm::BasicBlock *Block1,
376 Address Addr2, llvm::BasicBlock *Block2,
377 const llvm::Twine &Name = "") {
378 assert(Addr1.getType() == Addr2.getType());
379 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
380 PHI->addIncoming(Addr1.getPointer(), Block1);
381 PHI->addIncoming(Addr2.getPointer(), Block2);
382 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
383 return Address(PHI, Align);
384}
385
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000386TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
387
John McCall3480ef22011-08-30 01:42:09 +0000388// If someone can figure out a general rule for this, that would be great.
389// It's probably just doomed to be platform-dependent, though.
390unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
391 // Verified for:
392 // x86-64 FreeBSD, Linux, Darwin
393 // x86-32 FreeBSD, Linux, Darwin
394 // PowerPC Linux, Darwin
395 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000396 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000397 return 32;
398}
399
John McCalla729c622012-02-17 03:33:10 +0000400bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
401 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000402 // The following conventions are known to require this to be false:
403 // x86_stdcall
404 // MIPS
405 // For everything else, we just prefer false unless we opt out.
406 return false;
407}
408
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000409void
410TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
411 llvm::SmallString<24> &Opt) const {
412 // This assumes the user is passing a library name like "rt" instead of a
413 // filename like "librt.a/so", and that they don't care whether it's static or
414 // dynamic.
415 Opt = "-l";
416 Opt += Lib;
417}
418
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000419unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000420 // OpenCL kernels are called via an explicit runtime API with arguments
421 // set with clSetKernelArg(), not as normal sub-functions.
422 // Return SPIR_KERNEL by default as the kernel calling convention to
423 // ensure the fingerprint is fixed such way that each OpenCL argument
424 // gets one matching argument in the produced kernel function argument
425 // list to enable feasible implementation of clSetKernelArg() with
426 // aggregates etc. In case we would use the default C calling conv here,
427 // clSetKernelArg() might break depending on the target-specific
428 // conventions; different targets might split structs passed as values
429 // to multiple function arguments etc.
430 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000431}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000432
Yaxun Liu402804b2016-12-15 08:09:08 +0000433llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
434 llvm::PointerType *T, QualType QT) const {
435 return llvm::ConstantPointerNull::get(T);
436}
437
Alexander Richardson6d989432017-10-15 18:48:14 +0000438LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
439 const VarDecl *D) const {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000440 assert(!CGM.getLangOpts().OpenCL &&
441 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
442 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +0000443 return D ? D->getType().getAddressSpace() : LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000444}
445
Yaxun Liu402804b2016-12-15 08:09:08 +0000446llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Alexander Richardson6d989432017-10-15 18:48:14 +0000447 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
448 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000449 // Since target may map different address spaces in AST to the same address
450 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000451 if (auto *C = dyn_cast<llvm::Constant>(Src))
452 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Vyacheslav Zakharinde811d12019-07-10 17:10:05 +0000453 // Try to preserve the source's name to make IR more readable.
454 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
455 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
Yaxun Liu402804b2016-12-15 08:09:08 +0000456}
457
Yaxun Liucbf647c2017-07-08 13:24:52 +0000458llvm::Constant *
459TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
Alexander Richardson6d989432017-10-15 18:48:14 +0000460 LangAS SrcAddr, LangAS DestAddr,
Yaxun Liucbf647c2017-07-08 13:24:52 +0000461 llvm::Type *DestTy) const {
462 // Since target may map different address spaces in AST to the same address
463 // space, an address space conversion may end up as a bitcast.
464 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
465}
466
Yaxun Liu39195062017-08-04 18:16:31 +0000467llvm::SyncScope::ID
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +0000468TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
469 SyncScope Scope,
470 llvm::AtomicOrdering Ordering,
471 llvm::LLVMContext &Ctx) const {
472 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
Yaxun Liu39195062017-08-04 18:16:31 +0000473}
474
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000475static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000476
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000477/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000478/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000479static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
480 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000481 if (FD->isUnnamedBitfield())
482 return true;
483
484 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000485
Eli Friedman0b3f2012011-11-18 03:47:20 +0000486 // Constant arrays of empty records count as empty, strip them off.
487 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000488 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000489 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
490 if (AT->getSize() == 0)
491 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000492 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000493 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000494
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000495 const RecordType *RT = FT->getAs<RecordType>();
496 if (!RT)
497 return false;
498
499 // C++ record fields are never empty, at least in the Itanium ABI.
500 //
501 // FIXME: We should use a predicate for whether this behavior is true in the
502 // current ABI.
503 if (isa<CXXRecordDecl>(RT->getDecl()))
504 return false;
505
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000506 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000507}
508
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000509/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000510/// fields. Note that a structure with a flexible array member is not
511/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000512static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000513 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000514 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000515 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000516 const RecordDecl *RD = RT->getDecl();
517 if (RD->hasFlexibleArrayMember())
518 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000519
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000520 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000521 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000522 for (const auto &I : CXXRD->bases())
523 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000524 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000525
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000526 for (const auto *I : RD->fields())
527 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000528 return false;
529 return true;
530}
531
532/// isSingleElementStruct - Determine if a structure is a "single
533/// element struct", i.e. it has exactly one non-empty field or
534/// exactly one field which is itself a single element
535/// struct. Structures with flexible array members are never
536/// considered single element structs.
537///
538/// \return The field declaration for the single non-empty field, if
539/// it exists.
540static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000541 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000542 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000543 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000544
545 const RecordDecl *RD = RT->getDecl();
546 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000547 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000548
Craig Topper8a13c412014-05-21 05:09:00 +0000549 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000550
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000551 // If this is a C++ record, check the bases first.
552 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000553 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000554 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000555 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000556 continue;
557
558 // If we already found an element then this isn't a single-element struct.
559 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000560 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000561
562 // If this is non-empty and not a single element struct, the composite
563 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000564 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000565 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000566 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000567 }
568 }
569
570 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000571 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000572 QualType FT = FD->getType();
573
574 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000575 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000576 continue;
577
578 // If we already found an element then this isn't a single-element
579 // struct.
580 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000581 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000582
583 // Treat single element arrays as the element.
584 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
585 if (AT->getSize().getZExtValue() != 1)
586 break;
587 FT = AT->getElementType();
588 }
589
John McCalla1dee5302010-08-22 10:59:02 +0000590 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000591 Found = FT.getTypePtr();
592 } else {
593 Found = isSingleElementStruct(FT, Context);
594 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000595 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000596 }
597 }
598
Eli Friedmanee945342011-11-18 01:25:50 +0000599 // We don't consider a struct a single-element struct if it has
600 // padding beyond the element type.
601 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000602 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000603
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000604 return Found;
605}
606
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000607namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000608Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
609 const ABIArgInfo &AI) {
610 // This default implementation defers to the llvm backend's va_arg
611 // instruction. It can handle only passing arguments directly
612 // (typically only handled in the backend for primitive types), or
613 // aggregates passed indirectly by pointer (NOTE: if the "byval"
614 // flag has ABI impact in the callee, this implementation cannot
615 // work.)
616
617 // Only a few cases are covered here at the moment -- those needed
618 // by the default abi.
619 llvm::Value *Val;
620
621 if (AI.isIndirect()) {
622 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000623 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000624 assert(
625 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000626 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000627
628 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
629 CharUnits TyAlignForABI = TyInfo.second;
630
631 llvm::Type *BaseTy =
632 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
633 llvm::Value *Addr =
634 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
635 return Address(Addr, TyAlignForABI);
636 } else {
637 assert((AI.isDirect() || AI.isExtend()) &&
638 "Unexpected ArgInfo Kind in generic VAArg emitter!");
639
640 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000641 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000642 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000643 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000644 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000645 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000646 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000647 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000648
649 Address Temp = CGF.CreateMemTemp(Ty, "varet");
650 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
651 CGF.Builder.CreateStore(Val, Temp);
652 return Temp;
653 }
654}
655
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000656/// DefaultABIInfo - The default implementation for ABI specific
657/// details. This implementation provides information which results in
658/// self-consistent and sensible LLVM IR generation, but does not
659/// conform to any particular ABI.
660class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000661public:
662 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000663
Chris Lattner458b2aa2010-07-29 02:16:43 +0000664 ABIArgInfo classifyReturnType(QualType RetTy) const;
665 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000666
Craig Topper4f12f102014-03-12 06:41:41 +0000667 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000668 if (!getCXXABI().classifyReturnType(FI))
669 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000670 for (auto &I : FI.arguments())
671 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000672 }
673
John McCall7f416cc2015-09-08 08:05:57 +0000674 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000675 QualType Ty) const override {
676 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
677 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000678};
679
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000680class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
681public:
Chris Lattner2b037972010-07-29 02:01:43 +0000682 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
683 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000684};
685
Chris Lattner458b2aa2010-07-29 02:16:43 +0000686ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000687 Ty = useFirstFieldIfTransparentUnion(Ty);
688
689 if (isAggregateTypeForABI(Ty)) {
690 // Records with non-trivial destructors/copy-constructors should not be
691 // passed by value.
692 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000693 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000694
John McCall7f416cc2015-09-08 08:05:57 +0000695 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000696 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000697
Chris Lattner9723d6c2010-03-11 18:19:55 +0000698 // Treat an enum type as its underlying type.
699 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
700 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000701
Alex Bradburye41a5e22018-01-12 20:08:16 +0000702 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
703 : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000704}
705
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000706ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
707 if (RetTy->isVoidType())
708 return ABIArgInfo::getIgnore();
709
710 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000711 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000712
713 // Treat an enum type as its underlying type.
714 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
715 RetTy = EnumTy->getDecl()->getIntegerType();
716
Alex Bradburye41a5e22018-01-12 20:08:16 +0000717 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
718 : ABIArgInfo::getDirect());
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000719}
720
Derek Schuff09338a22012-09-06 17:37:28 +0000721//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000722// WebAssembly ABI Implementation
723//
724// This is a very simple ABI that relies a lot on DefaultABIInfo.
725//===----------------------------------------------------------------------===//
726
Daniel Dunbara39bab32019-01-03 23:24:50 +0000727class WebAssemblyABIInfo final : public SwiftABIInfo {
728 DefaultABIInfo defaultInfo;
729
Dan Gohmanc2853072015-09-03 22:51:53 +0000730public:
731 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
Daniel Dunbara39bab32019-01-03 23:24:50 +0000732 : SwiftABIInfo(CGT), defaultInfo(CGT) {}
Dan Gohmanc2853072015-09-03 22:51:53 +0000733
734private:
735 ABIArgInfo classifyReturnType(QualType RetTy) const;
736 ABIArgInfo classifyArgumentType(QualType Ty) const;
737
738 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000739 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000740 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000741 void computeInfo(CGFunctionInfo &FI) const override {
742 if (!getCXXABI().classifyReturnType(FI))
743 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
744 for (auto &Arg : FI.arguments())
745 Arg.info = classifyArgumentType(Arg.type);
746 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000747
748 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
749 QualType Ty) const override;
Daniel Dunbara39bab32019-01-03 23:24:50 +0000750
751 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
752 bool asReturnValue) const override {
753 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
754 }
755
756 bool isSwiftErrorInRegister() const override {
757 return false;
758 }
Dan Gohmanc2853072015-09-03 22:51:53 +0000759};
760
761class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
762public:
763 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
764 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
Sam Clegg6fd7d682018-06-25 18:47:32 +0000765
766 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
767 CodeGen::CodeGenModule &CGM) const override {
Dan Gohmanb4323692019-01-24 21:08:30 +0000768 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
769 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
770 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
771 llvm::Function *Fn = cast<llvm::Function>(GV);
772 llvm::AttrBuilder B;
Dan Gohmancae84592019-02-01 22:25:23 +0000773 B.addAttribute("wasm-import-module", Attr->getImportModule());
774 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
775 }
776 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
777 llvm::Function *Fn = cast<llvm::Function>(GV);
778 llvm::AttrBuilder B;
779 B.addAttribute("wasm-import-name", Attr->getImportName());
Dan Gohmanb4323692019-01-24 21:08:30 +0000780 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
781 }
Sam Clegg881d8772019-11-05 10:15:56 -0800782 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
783 llvm::Function *Fn = cast<llvm::Function>(GV);
784 llvm::AttrBuilder B;
785 B.addAttribute("wasm-export-name", Attr->getExportName());
786 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
787 }
Dan Gohmanb4323692019-01-24 21:08:30 +0000788 }
789
Sam Clegg6fd7d682018-06-25 18:47:32 +0000790 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
791 llvm::Function *Fn = cast<llvm::Function>(GV);
792 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
793 Fn->addFnAttr("no-prototype");
794 }
795 }
Dan Gohmanc2853072015-09-03 22:51:53 +0000796};
797
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000798/// Classify argument of given type \p Ty.
Dan Gohmanc2853072015-09-03 22:51:53 +0000799ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
800 Ty = useFirstFieldIfTransparentUnion(Ty);
801
802 if (isAggregateTypeForABI(Ty)) {
803 // Records with non-trivial destructors/copy-constructors should not be
804 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000805 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000806 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000807 // Ignore empty structs/unions.
808 if (isEmptyRecord(getContext(), Ty, true))
809 return ABIArgInfo::getIgnore();
810 // Lower single-element structs to just pass a regular value. TODO: We
811 // could do reasonable-size multiple-element structs too, using getExpand(),
812 // though watch out for things like bitfields.
813 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
814 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000815 }
816
817 // Otherwise just do the default thing.
Daniel Dunbara39bab32019-01-03 23:24:50 +0000818 return defaultInfo.classifyArgumentType(Ty);
Dan Gohmanc2853072015-09-03 22:51:53 +0000819}
820
821ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
822 if (isAggregateTypeForABI(RetTy)) {
823 // Records with non-trivial destructors/copy-constructors should not be
824 // returned by value.
825 if (!getRecordArgABI(RetTy, getCXXABI())) {
826 // Ignore empty structs/unions.
827 if (isEmptyRecord(getContext(), RetTy, true))
828 return ABIArgInfo::getIgnore();
829 // Lower single-element structs to just return a regular value. TODO: We
830 // could do reasonable-size multiple-element structs too, using
831 // ABIArgInfo::getDirect().
832 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
833 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
834 }
835 }
836
837 // Otherwise just do the default thing.
Daniel Dunbara39bab32019-01-03 23:24:50 +0000838 return defaultInfo.classifyReturnType(RetTy);
Dan Gohmanc2853072015-09-03 22:51:53 +0000839}
840
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000841Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
842 QualType Ty) const {
Guanzhong Chen82bfd1d2019-08-15 19:33:36 +0000843 bool IsIndirect = isAggregateTypeForABI(Ty) &&
844 !isEmptyRecord(getContext(), Ty, true) &&
845 !isSingleElementStruct(Ty, getContext());
Guanzhong Chen8a503e42019-08-13 21:41:11 +0000846 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000847 getContext().getTypeInfoInChars(Ty),
848 CharUnits::fromQuantity(4),
Guanzhong Chen8a503e42019-08-13 21:41:11 +0000849 /*AllowHigherAlign=*/true);
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000850}
851
Dan Gohmanc2853072015-09-03 22:51:53 +0000852//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000853// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000854//
855// This is a simplified version of the x86_32 ABI. Arguments and return values
856// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000857//===----------------------------------------------------------------------===//
858
859class PNaClABIInfo : public ABIInfo {
860 public:
861 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
862
863 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000864 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000865
Craig Topper4f12f102014-03-12 06:41:41 +0000866 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000867 Address EmitVAArg(CodeGenFunction &CGF,
868 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000869};
870
871class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
872 public:
873 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
874 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
875};
876
877void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000878 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000879 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
880
Reid Kleckner40ca9132014-05-13 22:05:45 +0000881 for (auto &I : FI.arguments())
882 I.info = classifyArgumentType(I.type);
883}
Derek Schuff09338a22012-09-06 17:37:28 +0000884
John McCall7f416cc2015-09-08 08:05:57 +0000885Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
886 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000887 // The PNaCL ABI is a bit odd, in that varargs don't use normal
888 // function classification. Structs get passed directly for varargs
889 // functions, through a rewriting transform in
890 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
891 // this target to actually support a va_arg instructions with an
892 // aggregate type, unlike other targets.
893 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000894}
895
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000896/// Classify argument of given type \p Ty.
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000897ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000898 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000899 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000900 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
901 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000902 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
903 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000904 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000905 } else if (Ty->isFloatingType()) {
906 // Floating-point types don't go inreg.
907 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000908 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000909
Alex Bradburye41a5e22018-01-12 20:08:16 +0000910 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
911 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000912}
913
914ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
915 if (RetTy->isVoidType())
916 return ABIArgInfo::getIgnore();
917
Eli Benderskye20dad62013-04-04 22:49:35 +0000918 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000919 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000920 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000921
922 // Treat an enum type as its underlying type.
923 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
924 RetTy = EnumTy->getDecl()->getIntegerType();
925
Alex Bradburye41a5e22018-01-12 20:08:16 +0000926 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
927 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000928}
929
Hans Wennborgd874c052019-06-19 11:34:08 +0000930/// IsX86_MMXType - Return true if this is an MMX type.
931bool IsX86_MMXType(llvm::Type *IRType) {
932 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
933 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
934 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
935 IRType->getScalarSizeInBits() != 64;
936}
937
Jay Foad7c57be32011-07-11 09:56:20 +0000938static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000939 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000940 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000941 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
942 .Cases("y", "&y", "^Ym", true)
943 .Default(false);
944 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000945 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
946 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000947 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000948 }
949
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000950 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000951 }
952
953 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000954 return Ty;
955}
956
Reid Kleckner80944df2014-10-31 22:00:51 +0000957/// Returns true if this type can be passed in SSE registers with the
958/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
959static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
960 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000961 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
962 if (BT->getKind() == BuiltinType::LongDouble) {
963 if (&Context.getTargetInfo().getLongDoubleFormat() ==
964 &llvm::APFloat::x87DoubleExtended())
965 return false;
966 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000967 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000968 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000969 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
970 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
971 // registers specially.
972 unsigned VecSize = Context.getTypeSize(VT);
973 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
974 return true;
975 }
976 return false;
977}
978
979/// Returns true if this aggregate is small enough to be passed in SSE registers
980/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
981static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
982 return NumMembers <= 4;
983}
984
Erich Keane521ed962017-01-05 00:20:51 +0000985/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
986static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
987 auto AI = ABIArgInfo::getDirect(T);
988 AI.setInReg(true);
989 AI.setCanBeFlattened(false);
990 return AI;
991}
992
Chris Lattner0cf24192010-06-28 20:05:43 +0000993//===----------------------------------------------------------------------===//
994// X86-32 ABI Implementation
995//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000996
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000997/// Similar to llvm::CCState, but for Clang.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000998struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000999 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +00001000
1001 unsigned CC;
1002 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +00001003 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001004};
1005
Erich Keane521ed962017-01-05 00:20:51 +00001006enum {
1007 // Vectorcall only allows the first 6 parameters to be passed in registers.
1008 VectorcallMaxParamNumAsReg = 6
1009};
1010
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001011/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001012class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001013 enum Class {
1014 Integer,
1015 Float
1016 };
1017
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001018 static const unsigned MinABIStackAlignInBytes = 4;
1019
David Chisnallde3a0692009-08-17 23:08:21 +00001020 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +00001021 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001022 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001023 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +00001024 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001025 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001026
1027 static bool isRegisterSize(unsigned Size) {
1028 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1029 }
1030
Reid Kleckner80944df2014-10-31 22:00:51 +00001031 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1032 // FIXME: Assumes vectorcall is in use.
1033 return isX86VectorTypeForVectorCall(getContext(), Ty);
1034 }
1035
1036 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1037 uint64_t NumMembers) const override {
1038 // FIXME: Assumes vectorcall is in use.
1039 return isX86VectorCallAggregateSmallEnough(NumMembers);
1040 }
1041
Reid Kleckner40ca9132014-05-13 22:05:45 +00001042 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001043
Daniel Dunbar557893d2010-04-21 19:10:51 +00001044 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1045 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +00001046 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1047
John McCall7f416cc2015-09-08 08:05:57 +00001048 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +00001049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001050 /// Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001051 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001052
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001053 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +00001054 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001055 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +00001056
Fangrui Song6907ce22018-07-30 19:24:48 +00001057 /// Updates the number of available free registers, returns
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001058 /// true if any registers were allocated.
1059 bool updateFreeRegs(QualType Ty, CCState &State) const;
1060
1061 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1062 bool &NeedsPadding) const;
1063 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001064
Reid Kleckner04046052016-05-02 17:41:07 +00001065 bool canExpandIndirectArgument(QualType Ty) const;
1066
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001067 /// Rewrite the function info so that all memory arguments use
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001068 /// inalloca.
1069 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1070
1071 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001072 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001073 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001074 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1075 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001076
Rafael Espindola75419dc2012-07-23 23:30:29 +00001077public:
1078
Craig Topper4f12f102014-03-12 06:41:41 +00001079 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001080 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1081 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001082
Michael Kupersteindc745202015-10-19 07:52:25 +00001083 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1084 bool RetSmallStructInRegABI, bool Win32StructABI,
Hans Wennborgd874c052019-06-19 11:34:08 +00001085 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001086 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Fangrui Song6907ce22018-07-30 19:24:48 +00001087 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001088 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001089 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001090 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Hans Wennborgd874c052019-06-19 11:34:08 +00001091 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001092
John McCall56331e22018-01-07 06:28:49 +00001093 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00001094 bool asReturnValue) const override {
1095 // LLVM's x86-32 lowering currently only assigns up to three
1096 // integer registers and three fp registers. Oddly, it'll use up to
1097 // four vector registers for vectors, but those can overlap with the
1098 // scalar registers.
1099 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
Fangrui Song6907ce22018-07-30 19:24:48 +00001100 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001101
1102 bool isSwiftErrorInRegister() const override {
1103 // x86-32 lowering does not support passing swifterror in a register.
1104 return false;
1105 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001106};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001107
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001108class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1109public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001110 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1111 bool RetSmallStructInRegABI, bool Win32StructABI,
Hans Wennborgd874c052019-06-19 11:34:08 +00001112 unsigned NumRegisterParameters, bool SoftFloatABI)
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001113 : TargetCodeGenInfo(new X86_32ABIInfo(
1114 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
Hans Wennborgd874c052019-06-19 11:34:08 +00001115 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001116
John McCall1fe2a8c2013-06-18 02:46:29 +00001117 static bool isStructReturnInRegABI(
1118 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1119
Eric Christopher162c91c2015-06-05 22:03:00 +00001120 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001121 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001122
Craig Topper4f12f102014-03-12 06:41:41 +00001123 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001124 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001125 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001126 return 4;
1127 }
1128
1129 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001130 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001131
Jay Foad7c57be32011-07-11 09:56:20 +00001132 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001133 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001134 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001135 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1136 }
1137
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001138 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1139 std::string &Constraints,
1140 std::vector<llvm::Type *> &ResultRegTypes,
1141 std::vector<llvm::Type *> &ResultTruncRegTypes,
1142 std::vector<LValue> &ResultRegDests,
1143 std::string &AsmString,
1144 unsigned NumOutputs) const override;
1145
Craig Topper4f12f102014-03-12 06:41:41 +00001146 llvm::Constant *
1147 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001148 unsigned Sig = (0xeb << 0) | // jmp rel8
1149 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001150 ('v' << 16) |
1151 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001152 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1153 }
John McCall01391782016-02-05 21:37:38 +00001154
1155 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1156 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001157 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001158 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001159};
1160
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001161}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001162
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001163/// Rewrite input constraint references after adding some output constraints.
1164/// In the case where there is one output and one input and we add one output,
1165/// we need to replace all operand references greater than or equal to 1:
1166/// mov $0, $1
1167/// mov eax, $1
1168/// The result will be:
1169/// mov $0, $2
1170/// mov eax, $2
1171static void rewriteInputConstraintReferences(unsigned FirstIn,
1172 unsigned NumNewOuts,
1173 std::string &AsmString) {
1174 std::string Buf;
1175 llvm::raw_string_ostream OS(Buf);
1176 size_t Pos = 0;
1177 while (Pos < AsmString.size()) {
1178 size_t DollarStart = AsmString.find('$', Pos);
1179 if (DollarStart == std::string::npos)
1180 DollarStart = AsmString.size();
1181 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1182 if (DollarEnd == std::string::npos)
1183 DollarEnd = AsmString.size();
1184 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1185 Pos = DollarEnd;
1186 size_t NumDollars = DollarEnd - DollarStart;
1187 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1188 // We have an operand reference.
1189 size_t DigitStart = Pos;
1190 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1191 if (DigitEnd == std::string::npos)
1192 DigitEnd = AsmString.size();
1193 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1194 unsigned OperandIndex;
1195 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1196 if (OperandIndex >= FirstIn)
1197 OperandIndex += NumNewOuts;
1198 OS << OperandIndex;
1199 } else {
1200 OS << OperandStr;
1201 }
1202 Pos = DigitEnd;
1203 }
1204 }
1205 AsmString = std::move(OS.str());
1206}
1207
1208/// Add output constraints for EAX:EDX because they are return registers.
1209void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1210 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1211 std::vector<llvm::Type *> &ResultRegTypes,
1212 std::vector<llvm::Type *> &ResultTruncRegTypes,
1213 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1214 unsigned NumOutputs) const {
1215 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1216
1217 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1218 // larger.
1219 if (!Constraints.empty())
1220 Constraints += ',';
1221 if (RetWidth <= 32) {
1222 Constraints += "={eax}";
1223 ResultRegTypes.push_back(CGF.Int32Ty);
1224 } else {
1225 // Use the 'A' constraint for EAX:EDX.
1226 Constraints += "=A";
1227 ResultRegTypes.push_back(CGF.Int64Ty);
1228 }
1229
1230 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1231 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1232 ResultTruncRegTypes.push_back(CoerceTy);
1233
1234 // Coerce the integer by bitcasting the return slot pointer.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001235 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001236 CoerceTy->getPointerTo()));
1237 ResultRegDests.push_back(ReturnSlot);
1238
1239 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1240}
1241
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001242/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001243/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001244bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1245 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001246 uint64_t Size = Context.getTypeSize(Ty);
1247
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001248 // For i386, type must be register sized.
1249 // For the MCU ABI, it only needs to be <= 8-byte
1250 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1251 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001252
1253 if (Ty->isVectorType()) {
1254 // 64- and 128- bit vectors inside structures are not returned in
1255 // registers.
1256 if (Size == 64 || Size == 128)
1257 return false;
1258
1259 return true;
1260 }
1261
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001262 // If this is a builtin, pointer, enum, complex type, member pointer, or
1263 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001264 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001265 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001266 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001267 return true;
1268
1269 // Arrays are treated like records.
1270 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001271 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001272
1273 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001274 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001275 if (!RT) return false;
1276
Anders Carlsson40446e82010-01-27 03:25:19 +00001277 // FIXME: Traverse bases here too.
1278
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001279 // Structure types are passed in register if all fields would be
1280 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001281 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001282 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001283 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001284 continue;
1285
1286 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001287 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001288 return false;
1289 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001290 return true;
1291}
1292
Reid Kleckner04046052016-05-02 17:41:07 +00001293static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1294 // Treat complex types as the element type.
1295 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1296 Ty = CTy->getElementType();
1297
1298 // Check for a type which we know has a simple scalar argument-passing
1299 // convention without any padding. (We're specifically looking for 32
1300 // and 64-bit integer and integer-equivalents, float, and double.)
1301 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1302 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1303 return false;
1304
1305 uint64_t Size = Context.getTypeSize(Ty);
1306 return Size == 32 || Size == 64;
1307}
1308
Reid Kleckner791bbf62017-01-13 17:18:19 +00001309static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1310 uint64_t &Size) {
1311 for (const auto *FD : RD->fields()) {
1312 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1313 // argument is smaller than 32-bits, expanding the struct will create
1314 // alignment padding.
1315 if (!is32Or64BitBasicType(FD->getType(), Context))
1316 return false;
1317
1318 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1319 // how to expand them yet, and the predicate for telling if a bitfield still
1320 // counts as "basic" is more complicated than what we were doing previously.
1321 if (FD->isBitField())
1322 return false;
1323
1324 Size += Context.getTypeSize(FD->getType());
1325 }
1326 return true;
1327}
1328
1329static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1330 uint64_t &Size) {
1331 // Don't do this if there are any non-empty bases.
1332 for (const CXXBaseSpecifier &Base : RD->bases()) {
1333 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1334 Size))
1335 return false;
1336 }
1337 if (!addFieldSizes(Context, RD, Size))
1338 return false;
1339 return true;
1340}
1341
Reid Kleckner04046052016-05-02 17:41:07 +00001342/// Test whether an argument type which is to be passed indirectly (on the
1343/// stack) would have the equivalent layout if it was expanded into separate
1344/// arguments. If so, we prefer to do the latter to avoid inhibiting
1345/// optimizations.
1346bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1347 // We can only expand structure types.
1348 const RecordType *RT = Ty->getAs<RecordType>();
1349 if (!RT)
1350 return false;
1351 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001352 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001353 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001354 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001355 // On non-Windows, we have to conservatively match our old bitcode
1356 // prototypes in order to be ABI-compatible at the bitcode level.
1357 if (!CXXRD->isCLike())
1358 return false;
1359 } else {
1360 // Don't do this for dynamic classes.
1361 if (CXXRD->isDynamicClass())
1362 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001363 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001364 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001365 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001366 } else {
1367 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001368 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001369 }
1370
1371 // We can do this if there was no alignment padding.
1372 return Size == getContext().getTypeSize(Ty);
1373}
1374
John McCall7f416cc2015-09-08 08:05:57 +00001375ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001376 // If the return value is indirect, then the hidden argument is consuming one
1377 // integer register.
1378 if (State.FreeRegs) {
1379 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001380 if (!IsMCUABI)
1381 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001382 }
John McCall7f416cc2015-09-08 08:05:57 +00001383 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001384}
1385
Eric Christopher7565e0d2015-05-29 23:09:49 +00001386ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1387 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001388 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001389 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001390
Reid Kleckner80944df2014-10-31 22:00:51 +00001391 const Type *Base = nullptr;
1392 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001393 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1394 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001395 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1396 // The LLVM struct type for such an aggregate should lower properly.
1397 return ABIArgInfo::getDirect();
1398 }
1399
Chris Lattner458b2aa2010-07-29 02:16:43 +00001400 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001401 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001402 if (IsDarwinVectorABI) {
Hans Wennborgd874c052019-06-19 11:34:08 +00001403 uint64_t Size = getContext().getTypeSize(RetTy);
1404
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001405 // 128-bit vectors are a special case; they are returned in
1406 // registers and we need to make sure to pick a type the LLVM
1407 // backend will like.
1408 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001409 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001410 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001411
1412 // Always return in register if it fits in a general purpose
1413 // register, or if it is 64 bits and has a single element.
1414 if ((Size == 8 || Size == 16 || Size == 32) ||
1415 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001416 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001417 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001418
John McCall7f416cc2015-09-08 08:05:57 +00001419 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001420 }
1421
1422 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001423 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001424
John McCalla1dee5302010-08-22 10:59:02 +00001425 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001426 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001427 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001428 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001429 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001430 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001431
David Chisnallde3a0692009-08-17 23:08:21 +00001432 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001433 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001434 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001435
Denis Zobnin380b2242016-02-11 11:26:03 +00001436 // Ignore empty structs/unions.
1437 if (isEmptyRecord(getContext(), RetTy, true))
1438 return ABIArgInfo::getIgnore();
1439
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001440 // Small structures which are register sized are generally returned
1441 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001442 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001443 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001444
1445 // As a special-case, if the struct is a "single-element" struct, and
1446 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001447 // floating-point register. (MSVC does not apply this special case.)
1448 // We apply a similar transformation for pointer types to improve the
1449 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001450 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001451 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001452 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001453 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1454
1455 // FIXME: We should be able to narrow this integer in cases with dead
1456 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001457 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001458 }
1459
John McCall7f416cc2015-09-08 08:05:57 +00001460 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001461 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001462
Chris Lattner458b2aa2010-07-29 02:16:43 +00001463 // Treat an enum type as its underlying type.
1464 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1465 RetTy = EnumTy->getDecl()->getIntegerType();
1466
Alex Bradburye41a5e22018-01-12 20:08:16 +00001467 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1468 : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001469}
1470
Eli Friedman7919bea2012-06-05 19:40:46 +00001471static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1472 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1473}
1474
Daniel Dunbared23de32010-09-16 20:42:00 +00001475static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1476 const RecordType *RT = Ty->getAs<RecordType>();
1477 if (!RT)
1478 return 0;
1479 const RecordDecl *RD = RT->getDecl();
1480
1481 // If this is a C++ record, check the bases first.
1482 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001483 for (const auto &I : CXXRD->bases())
1484 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001485 return false;
1486
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001487 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001488 QualType FT = i->getType();
1489
Eli Friedman7919bea2012-06-05 19:40:46 +00001490 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001491 return true;
1492
1493 if (isRecordWithSSEVectorType(Context, FT))
1494 return true;
1495 }
1496
1497 return false;
1498}
1499
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001500unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1501 unsigned Align) const {
1502 // Otherwise, if the alignment is less than or equal to the minimum ABI
1503 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001504 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001505 return 0; // Use default alignment.
1506
Pengfei Wang48387ec2019-05-31 01:50:07 +00001507 // On non-Darwin, the stack type alignment is always 4.
1508 if (!IsDarwinVectorABI) {
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001509 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001510 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001511 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001512
Daniel Dunbared23de32010-09-16 20:42:00 +00001513 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001514 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1515 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001516 return 16;
1517
1518 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001519}
1520
Rafael Espindola703c47f2012-10-19 05:04:37 +00001521ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001522 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001523 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001524 if (State.FreeRegs) {
1525 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001526 if (!IsMCUABI)
1527 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001528 }
John McCall7f416cc2015-09-08 08:05:57 +00001529 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001530 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001531
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001532 // Compute the byval alignment.
1533 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1534 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1535 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001536 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001537
1538 // If the stack alignment is less than the type alignment, realign the
1539 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001540 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001541 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1542 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001543}
1544
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001545X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1546 const Type *T = isSingleElementStruct(Ty, getContext());
1547 if (!T)
1548 T = Ty.getTypePtr();
1549
1550 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1551 BuiltinType::Kind K = BT->getKind();
1552 if (K == BuiltinType::Float || K == BuiltinType::Double)
1553 return Float;
1554 }
1555 return Integer;
1556}
1557
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001558bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001559 if (!IsSoftFloatABI) {
1560 Class C = classify(Ty);
1561 if (C == Float)
1562 return false;
1563 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001564
Rafael Espindola077dd592012-10-24 01:58:58 +00001565 unsigned Size = getContext().getTypeSize(Ty);
1566 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001567
1568 if (SizeInRegs == 0)
1569 return false;
1570
Michael Kuperstein68901882015-10-25 08:18:20 +00001571 if (!IsMCUABI) {
1572 if (SizeInRegs > State.FreeRegs) {
1573 State.FreeRegs = 0;
1574 return false;
1575 }
1576 } else {
1577 // The MCU psABI allows passing parameters in-reg even if there are
1578 // earlier parameters that are passed on the stack. Also,
1579 // it does not allow passing >8-byte structs in-register,
1580 // even if there are 3 free registers available.
1581 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1582 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001583 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001584
Reid Kleckner661f35b2014-01-18 01:12:41 +00001585 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001586 return true;
1587}
1588
Fangrui Song6907ce22018-07-30 19:24:48 +00001589bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001590 bool &InReg,
1591 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001592 // On Windows, aggregates other than HFAs are never passed in registers, and
1593 // they do not consume register slots. Homogenous floating-point aggregates
1594 // (HFAs) have already been dealt with at this point.
1595 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1596 return false;
1597
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001598 NeedsPadding = false;
1599 InReg = !IsMCUABI;
1600
1601 if (!updateFreeRegs(Ty, State))
1602 return false;
1603
1604 if (IsMCUABI)
1605 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001606
Reid Kleckner80944df2014-10-31 22:00:51 +00001607 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001608 State.CC == llvm::CallingConv::X86_VectorCall ||
1609 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001610 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001611 NeedsPadding = true;
1612
Rafael Espindola077dd592012-10-24 01:58:58 +00001613 return false;
1614 }
1615
Rafael Espindola703c47f2012-10-19 05:04:37 +00001616 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001617}
1618
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001619bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1620 if (!updateFreeRegs(Ty, State))
1621 return false;
1622
1623 if (IsMCUABI)
1624 return false;
1625
1626 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001627 State.CC == llvm::CallingConv::X86_VectorCall ||
1628 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001629 if (getContext().getTypeSize(Ty) > 32)
1630 return false;
1631
Fangrui Song6907ce22018-07-30 19:24:48 +00001632 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001633 Ty->isReferenceType());
1634 }
1635
1636 return true;
1637}
1638
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001639ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1640 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001641 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001642
Reid Klecknerb1be6832014-11-15 01:41:41 +00001643 Ty = useFirstFieldIfTransparentUnion(Ty);
1644
Reid Kleckner80944df2014-10-31 22:00:51 +00001645 // Check with the C++ ABI first.
1646 const RecordType *RT = Ty->getAs<RecordType>();
1647 if (RT) {
1648 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1649 if (RAA == CGCXXABI::RAA_Indirect) {
1650 return getIndirectResult(Ty, false, State);
1651 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1652 // The field index doesn't matter, we'll fix it up later.
1653 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1654 }
1655 }
1656
Erich Keane4bd39302017-06-21 16:37:22 +00001657 // Regcall uses the concept of a homogenous vector aggregate, similar
1658 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001659 const Type *Base = nullptr;
1660 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001661 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001662 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001663
Erich Keane4bd39302017-06-21 16:37:22 +00001664 if (State.FreeSSERegs >= NumElts) {
1665 State.FreeSSERegs -= NumElts;
1666 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001667 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001668 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001669 }
Erich Keane4bd39302017-06-21 16:37:22 +00001670 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001671 }
1672
1673 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001674 // Structures with flexible arrays are always indirect.
1675 // FIXME: This should not be byval!
1676 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1677 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001678
Reid Kleckner04046052016-05-02 17:41:07 +00001679 // Ignore empty structs/unions on non-Windows.
1680 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001681 return ABIArgInfo::getIgnore();
1682
Rafael Espindolafad28de2012-10-24 01:59:00 +00001683 llvm::LLVMContext &LLVMContext = getVMContext();
1684 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001685 bool NeedsPadding = false;
1686 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001687 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001688 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001689 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001690 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001691 if (InReg)
1692 return ABIArgInfo::getDirectInReg(Result);
1693 else
1694 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001695 }
Craig Topper8a13c412014-05-21 05:09:00 +00001696 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001697
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001698 // Expand small (<= 128-bit) record types when we know that the stack layout
1699 // of those arguments will match the struct. This is important because the
1700 // LLVM backend isn't smart enough to remove byval, which inhibits many
1701 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001702 // Don't do this for the MCU if there are still free integer registers
1703 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001704 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1705 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001706 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001707 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001708 State.CC == llvm::CallingConv::X86_VectorCall ||
1709 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001710 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001711
Reid Kleckner661f35b2014-01-18 01:12:41 +00001712 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001713 }
1714
Chris Lattnerd774ae92010-08-26 20:05:13 +00001715 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001716 // On Darwin, some vectors are passed in memory, we handle this by passing
1717 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001718 if (IsDarwinVectorABI) {
Hans Wennborgd874c052019-06-19 11:34:08 +00001719 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001720 if ((Size == 8 || Size == 16 || Size == 32) ||
1721 (Size == 64 && VT->getNumElements() == 1))
1722 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1723 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001724 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001725
Hans Wennborgd874c052019-06-19 11:34:08 +00001726 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1727 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1728
Chris Lattnerd774ae92010-08-26 20:05:13 +00001729 return ABIArgInfo::getDirect();
1730 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001731
Hans Wennborgd874c052019-06-19 11:34:08 +00001732
Chris Lattner458b2aa2010-07-29 02:16:43 +00001733 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1734 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001735
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001736 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001737
1738 if (Ty->isPromotableIntegerType()) {
1739 if (InReg)
Alex Bradburye41a5e22018-01-12 20:08:16 +00001740 return ABIArgInfo::getExtendInReg(Ty);
1741 return ABIArgInfo::getExtend(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001742 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001743
Rafael Espindola703c47f2012-10-19 05:04:37 +00001744 if (InReg)
1745 return ABIArgInfo::getDirectInReg();
1746 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001747}
1748
Erich Keane521ed962017-01-05 00:20:51 +00001749void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1750 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001751 // Vectorcall x86 works subtly different than in x64, so the format is
1752 // a bit different than the x64 version. First, all vector types (not HVAs)
1753 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1754 // This differs from the x64 implementation, where the first 6 by INDEX get
1755 // registers.
1756 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1757 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1758 // first take up the remaining YMM/XMM registers. If insufficient registers
1759 // remain but an integer register (ECX/EDX) is available, it will be passed
1760 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001761 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001762 // First pass do all the vector types.
1763 const Type *Base = nullptr;
1764 uint64_t NumElts = 0;
1765 const QualType& Ty = I.type;
1766 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1767 isHomogeneousAggregate(Ty, Base, NumElts)) {
1768 if (State.FreeSSERegs >= NumElts) {
1769 State.FreeSSERegs -= NumElts;
1770 I.info = ABIArgInfo::getDirect();
1771 } else {
1772 I.info = classifyArgumentType(Ty, State);
1773 }
1774 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1775 }
Erich Keane521ed962017-01-05 00:20:51 +00001776 }
Erich Keane4bd39302017-06-21 16:37:22 +00001777
Erich Keane521ed962017-01-05 00:20:51 +00001778 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001779 // Second pass, do the rest!
1780 const Type *Base = nullptr;
1781 uint64_t NumElts = 0;
1782 const QualType& Ty = I.type;
1783 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1784
1785 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1786 // Assign true HVAs (non vector/native FP types).
1787 if (State.FreeSSERegs >= NumElts) {
1788 State.FreeSSERegs -= NumElts;
1789 I.info = getDirectX86Hva();
1790 } else {
1791 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1792 }
1793 } else if (!IsHva) {
1794 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1795 I.info = classifyArgumentType(Ty, State);
1796 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1797 }
Erich Keane521ed962017-01-05 00:20:51 +00001798 }
1799}
1800
Rafael Espindolaa6472962012-07-24 00:01:07 +00001801void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001802 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001803 if (IsMCUABI)
1804 State.FreeRegs = 3;
1805 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001806 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001807 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1808 State.FreeRegs = 2;
1809 State.FreeSSERegs = 6;
1810 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001811 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001812 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1813 State.FreeRegs = 5;
1814 State.FreeSSERegs = 8;
1815 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001816 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001817
Akira Hatanakad791e922018-03-19 17:38:40 +00001818 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001819 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001820 } else if (FI.getReturnInfo().isIndirect()) {
1821 // The C++ ABI is not aware of register usage, so we have to check if the
1822 // return value was sret and put it in a register ourselves if appropriate.
1823 if (State.FreeRegs) {
1824 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001825 if (!IsMCUABI)
1826 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001827 }
1828 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001829
Peter Collingbournef7706832014-12-12 23:41:25 +00001830 // The chain argument effectively gives us another free register.
1831 if (FI.isChainCall())
1832 ++State.FreeRegs;
1833
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001834 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001835 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1836 computeVectorCallArgs(FI, State, UsedInAlloca);
1837 } else {
1838 // If not vectorcall, revert to normal behavior.
1839 for (auto &I : FI.arguments()) {
1840 I.info = classifyArgumentType(I.type, State);
1841 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1842 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001843 }
1844
1845 // If we needed to use inalloca for any argument, do a second pass and rewrite
1846 // all the memory arguments to use inalloca.
1847 if (UsedInAlloca)
1848 rewriteWithInAlloca(FI);
1849}
1850
1851void
1852X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001853 CharUnits &StackOffset, ABIArgInfo &Info,
1854 QualType Type) const {
1855 // Arguments are always 4-byte-aligned.
1856 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1857
1858 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001859 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1860 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001861 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001862
John McCall7f416cc2015-09-08 08:05:57 +00001863 // Insert padding bytes to respect alignment.
1864 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001865 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001866 if (StackOffset != FieldEnd) {
1867 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001868 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001869 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001870 FrameFields.push_back(Ty);
1871 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001872}
1873
Reid Kleckner852361d2014-07-26 00:12:26 +00001874static bool isArgInAlloca(const ABIArgInfo &Info) {
1875 // Leave ignored and inreg arguments alone.
1876 switch (Info.getKind()) {
1877 case ABIArgInfo::InAlloca:
1878 return true;
1879 case ABIArgInfo::Indirect:
1880 assert(Info.getIndirectByVal());
1881 return true;
1882 case ABIArgInfo::Ignore:
1883 return false;
1884 case ABIArgInfo::Direct:
1885 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001886 if (Info.getInReg())
1887 return false;
1888 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001889 case ABIArgInfo::Expand:
1890 case ABIArgInfo::CoerceAndExpand:
1891 // These are aggregate types which are never passed in registers when
1892 // inalloca is involved.
1893 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001894 }
1895 llvm_unreachable("invalid enum");
1896}
1897
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001898void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1899 assert(IsWin32StructABI && "inalloca only supported on win32");
1900
1901 // Build a packed struct type for all of the arguments in memory.
1902 SmallVector<llvm::Type *, 6> FrameFields;
1903
John McCall7f416cc2015-09-08 08:05:57 +00001904 // The stack alignment is always 4.
1905 CharUnits StackAlign = CharUnits::fromQuantity(4);
1906
1907 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001908 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1909
1910 // Put 'this' into the struct before 'sret', if necessary.
1911 bool IsThisCall =
1912 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1913 ABIArgInfo &Ret = FI.getReturnInfo();
1914 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1915 isArgInAlloca(I->info)) {
1916 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1917 ++I;
1918 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001919
1920 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001921 if (Ret.isIndirect() && !Ret.getInReg()) {
1922 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1923 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001924 // On Windows, the hidden sret parameter is always returned in eax.
1925 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001926 }
1927
1928 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001929 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001930 ++I;
1931
1932 // Put arguments passed in memory into the struct.
1933 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001934 if (isArgInAlloca(I->info))
1935 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001936 }
1937
1938 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001939 /*isPacked=*/true),
1940 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001941}
1942
John McCall7f416cc2015-09-08 08:05:57 +00001943Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1944 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001945
John McCall7f416cc2015-09-08 08:05:57 +00001946 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001947
John McCall7f416cc2015-09-08 08:05:57 +00001948 // x86-32 changes the alignment of certain arguments on the stack.
1949 //
1950 // Just messing with TypeInfo like this works because we never pass
1951 // anything indirectly.
1952 TypeInfo.second = CharUnits::fromQuantity(
1953 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001954
John McCall7f416cc2015-09-08 08:05:57 +00001955 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1956 TypeInfo, CharUnits::fromQuantity(4),
1957 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001958}
1959
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001960bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1961 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1962 assert(Triple.getArch() == llvm::Triple::x86);
1963
1964 switch (Opts.getStructReturnConvention()) {
1965 case CodeGenOptions::SRCK_Default:
1966 break;
1967 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1968 return false;
1969 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1970 return true;
1971 }
1972
Michael Kupersteind749f232015-10-27 07:46:22 +00001973 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001974 return true;
1975
1976 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001977 case llvm::Triple::DragonFly:
1978 case llvm::Triple::FreeBSD:
1979 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001980 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001981 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001982 default:
1983 return false;
1984 }
1985}
1986
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001987void X86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001988 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1989 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001990 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001991 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001992 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001993 llvm::Function *Fn = cast<llvm::Function>(GV);
Erich Keaneb127a3942018-04-19 14:27:05 +00001994 Fn->addFnAttr("stackrealign");
Charles Davis4ea31ab2010-02-13 15:54:06 +00001995 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001996 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1997 llvm::Function *Fn = cast<llvm::Function>(GV);
1998 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1999 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00002000 }
2001}
2002
John McCallbeec5a02010-03-06 00:35:14 +00002003bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2004 CodeGen::CodeGenFunction &CGF,
2005 llvm::Value *Address) const {
2006 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00002007
Chris Lattnerece04092012-02-07 00:39:47 +00002008 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002009
John McCallbeec5a02010-03-06 00:35:14 +00002010 // 0-7 are the eight integer registers; the order is different
2011 // on Darwin (for EH), but the range is the same.
2012 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00002013 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00002014
John McCallc8e01702013-04-16 22:48:15 +00002015 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00002016 // 12-16 are st(0..4). Not sure why we stop at 4.
2017 // These have size 16, which is sizeof(long double) on
2018 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00002019 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00002020 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002021
John McCallbeec5a02010-03-06 00:35:14 +00002022 } else {
2023 // 9 is %eflags, which doesn't get a size on Darwin for some
2024 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00002025 Builder.CreateAlignedStore(
2026 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2027 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00002028
2029 // 11-16 are st(0..5). Not sure why we stop at 5.
2030 // These have size 12, which is sizeof(long double) on
2031 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00002032 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00002033 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2034 }
John McCallbeec5a02010-03-06 00:35:14 +00002035
2036 return false;
2037}
2038
Chris Lattner0cf24192010-06-28 20:05:43 +00002039//===----------------------------------------------------------------------===//
2040// X86-64 ABI Implementation
2041//===----------------------------------------------------------------------===//
2042
2043
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002044namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002045/// The AVX ABI level for X86 targets.
2046enum class X86AVXABILevel {
2047 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002048 AVX,
2049 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002050};
2051
2052/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2053static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2054 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002055 case X86AVXABILevel::AVX512:
2056 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002057 case X86AVXABILevel::AVX:
2058 return 256;
2059 case X86AVXABILevel::None:
2060 return 128;
2061 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002062 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002063}
2064
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002065/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002066class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002067 enum Class {
2068 Integer = 0,
2069 SSE,
2070 SSEUp,
2071 X87,
2072 X87Up,
2073 ComplexX87,
2074 NoClass,
2075 Memory
2076 };
2077
2078 /// merge - Implement the X86_64 ABI merging algorithm.
2079 ///
2080 /// Merge an accumulating classification \arg Accum with a field
2081 /// classification \arg Field.
2082 ///
2083 /// \param Accum - The accumulating classification. This should
2084 /// always be either NoClass or the result of a previous merge
2085 /// call. In addition, this should never be Memory (the caller
2086 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002087 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002088
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002089 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2090 ///
2091 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2092 /// final MEMORY or SSE classes when necessary.
2093 ///
2094 /// \param AggregateSize - The size of the current aggregate in
2095 /// the classification process.
2096 ///
2097 /// \param Lo - The classification for the parts of the type
2098 /// residing in the low word of the containing object.
2099 ///
2100 /// \param Hi - The classification for the parts of the type
2101 /// residing in the higher words of the containing object.
2102 ///
2103 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2104
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002105 /// classify - Determine the x86_64 register classes in which the
2106 /// given type T should be passed.
2107 ///
2108 /// \param Lo - The classification for the parts of the type
2109 /// residing in the low word of the containing object.
2110 ///
2111 /// \param Hi - The classification for the parts of the type
2112 /// residing in the high word of the containing object.
2113 ///
2114 /// \param OffsetBase - The bit offset of this type in the
2115 /// containing object. Some parameters are classified different
2116 /// depending on whether they straddle an eightbyte boundary.
2117 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002118 /// \param isNamedArg - Whether the argument in question is a "named"
2119 /// argument, as used in AMD64-ABI 3.5.7.
2120 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002121 /// If a word is unused its result will be NoClass; if a type should
2122 /// be passed in Memory then at least the classification of \arg Lo
2123 /// will be Memory.
2124 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002125 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002126 ///
2127 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2128 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002129 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2130 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002131
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002132 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002133 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2134 unsigned IROffset, QualType SourceTy,
2135 unsigned SourceOffset) const;
2136 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2137 unsigned IROffset, QualType SourceTy,
2138 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002139
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002140 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002141 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002142 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002143
2144 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002145 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002146 ///
2147 /// \param freeIntRegs - The number of free integer registers remaining
2148 /// available.
2149 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002150
Chris Lattner458b2aa2010-07-29 02:16:43 +00002151 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002152
Erich Keane757d3172016-11-02 18:29:35 +00002153 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2154 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002155 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002156
Erich Keane757d3172016-11-02 18:29:35 +00002157 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2158 unsigned &NeededSSE) const;
2159
2160 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2161 unsigned &NeededSSE) const;
2162
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002163 bool IsIllegalVectorType(QualType Ty) const;
2164
John McCalle0fda732011-04-21 01:20:55 +00002165 /// The 0.98 ABI revision clarified a lot of ambiguities,
2166 /// unfortunately in ways that were not always consistent with
2167 /// certain previous compilers. In particular, platforms which
2168 /// required strict binary compatibility with older versions of GCC
2169 /// may need to exempt themselves.
2170 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002171 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002172 }
2173
Richard Smithf667ad52017-08-26 01:04:35 +00002174 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2175 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002176 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002177 // Clang <= 3.8 did not do this.
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002178 if (getContext().getLangOpts().getClangABICompat() <=
2179 LangOptions::ClangABI::Ver3_8)
Richard Smithf667ad52017-08-26 01:04:35 +00002180 return false;
2181
David Majnemere2ae2282016-03-04 05:26:16 +00002182 const llvm::Triple &Triple = getTarget().getTriple();
2183 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2184 return false;
2185 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2186 return false;
2187 return true;
2188 }
2189
Craig Topper6c8a34e2019-09-06 06:02:13 +00002190 // GCC classifies vectors of __int128 as memory.
2191 bool passInt128VectorsInMem() const {
2192 // Clang <= 9.0 did not do this.
2193 if (getContext().getLangOpts().getClangABICompat() <=
2194 LangOptions::ClangABI::Ver9)
2195 return false;
2196
2197 const llvm::Triple &T = getTarget().getTriple();
2198 return T.isOSLinux() || T.isOSNetBSD();
2199 }
2200
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002201 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002202 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2203 // 64-bit hardware.
2204 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002205
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002206public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002207 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002208 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002209 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002210 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002211
John McCalla729c622012-02-17 03:33:10 +00002212 bool isPassedUsingAVXType(QualType type) const {
2213 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002214 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002215 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2216 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002217 if (info.isDirect()) {
2218 llvm::Type *ty = info.getCoerceToType();
2219 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2220 return (vectorTy->getBitWidth() > 128);
2221 }
2222 return false;
2223 }
2224
Craig Topper4f12f102014-03-12 06:41:41 +00002225 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002226
John McCall7f416cc2015-09-08 08:05:57 +00002227 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2228 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002229 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2230 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002231
2232 bool has64BitPointers() const {
2233 return Has64BitPointers;
2234 }
John McCall12f23522016-04-04 18:33:08 +00002235
John McCall56331e22018-01-07 06:28:49 +00002236 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00002237 bool asReturnValue) const override {
2238 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002239 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002240 bool isSwiftErrorInRegister() const override {
2241 return true;
2242 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002243};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002244
Chris Lattner04dc9572010-08-31 16:44:54 +00002245/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002246class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002247public:
Reid Kleckner3fd3de12019-06-20 20:07:20 +00002248 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2249 : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Reid Kleckner11a17192015-10-28 22:29:52 +00002250 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002251
Craig Topper4f12f102014-03-12 06:41:41 +00002252 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002253
John McCall7f416cc2015-09-08 08:05:57 +00002254 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2255 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002256
2257 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2258 // FIXME: Assumes vectorcall is in use.
2259 return isX86VectorTypeForVectorCall(getContext(), Ty);
2260 }
2261
2262 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2263 uint64_t NumMembers) const override {
2264 // FIXME: Assumes vectorcall is in use.
2265 return isX86VectorCallAggregateSmallEnough(NumMembers);
2266 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002267
John McCall56331e22018-01-07 06:28:49 +00002268 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002269 bool asReturnValue) const override {
2270 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2271 }
2272
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002273 bool isSwiftErrorInRegister() const override {
2274 return true;
2275 }
2276
Reid Kleckner11a17192015-10-28 22:29:52 +00002277private:
Erich Keane521ed962017-01-05 00:20:51 +00002278 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2279 bool IsVectorCall, bool IsRegCall) const;
2280 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2281 const ABIArgInfo &current) const;
2282 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2283 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002284
Reid Kleckner3fd3de12019-06-20 20:07:20 +00002285 X86AVXABILevel AVXLevel;
2286
2287 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002288};
2289
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002290class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2291public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002292 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002293 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002294
John McCalla729c622012-02-17 03:33:10 +00002295 const X86_64ABIInfo &getABIInfo() const {
2296 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2297 }
2298
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002299 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2300 /// the autoreleaseRV/retainRV optimization.
2301 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override {
2302 return true;
2303 }
2304
Craig Topper4f12f102014-03-12 06:41:41 +00002305 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002306 return 7;
2307 }
2308
2309 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002310 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002311 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002312
John McCall943fae92010-05-27 06:19:26 +00002313 // 0-15 are the 16 integer registers.
2314 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002315 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002316 return false;
2317 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002318
Jay Foad7c57be32011-07-11 09:56:20 +00002319 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002320 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002321 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002322 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2323 }
2324
John McCalla729c622012-02-17 03:33:10 +00002325 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002326 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002327 // The default CC on x86-64 sets %al to the number of SSA
2328 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002329 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002330 // that when AVX types are involved: the ABI explicitly states it is
2331 // undefined, and it doesn't work in practice because of how the ABI
2332 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002333 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002334 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002335 for (CallArgList::const_iterator
2336 it = args.begin(), ie = args.end(); it != ie; ++it) {
2337 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2338 HasAVXType = true;
2339 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002340 }
2341 }
John McCalla729c622012-02-17 03:33:10 +00002342
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002343 if (!HasAVXType)
2344 return true;
2345 }
John McCallcbc038a2011-09-21 08:08:30 +00002346
John McCalla729c622012-02-17 03:33:10 +00002347 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002348 }
2349
Craig Topper4f12f102014-03-12 06:41:41 +00002350 llvm::Constant *
2351 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002352 unsigned Sig = (0xeb << 0) | // jmp rel8
2353 (0x06 << 8) | // .+0x08
2354 ('v' << 16) |
2355 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002356 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2357 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002358
2359 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002360 CodeGen::CodeGenModule &CGM) const override {
2361 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002362 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002363 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002364 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002365 llvm::Function *Fn = cast<llvm::Function>(GV);
2366 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002367 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002368 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2369 llvm::Function *Fn = cast<llvm::Function>(GV);
2370 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2371 }
2372 }
2373 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002374};
2375
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002376static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002377 // If the argument does not end in .lib, automatically add the suffix.
2378 // If the argument contains a space, enclose it in quotes.
2379 // This matches the behavior of MSVC.
2380 bool Quote = (Lib.find(" ") != StringRef::npos);
2381 std::string ArgStr = Quote ? "\"" : "";
2382 ArgStr += Lib;
Martin Storsjo3cd67c92018-10-10 09:01:00 +00002383 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002384 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002385 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002386 return ArgStr;
2387}
2388
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002389class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2390public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002391 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002392 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2393 unsigned NumRegisterParameters)
2394 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002395 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002396
Eric Christopher162c91c2015-06-05 22:03:00 +00002397 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002398 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002399
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002400 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002401 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002402 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002403 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002404 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002405
2406 void getDetectMismatchOption(llvm::StringRef Name,
2407 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002408 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002409 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002410 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002411};
2412
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002413static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2414 CodeGen::CodeGenModule &CGM) {
2415 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002416
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002417 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
Eric Christopher7565e0d2015-05-29 23:09:49 +00002418 Fn->addFnAttr("stack-probe-size",
2419 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002420 if (CGM.getCodeGenOpts().NoStackArgProbe)
2421 Fn->addFnAttr("no-stack-arg-probe");
Hans Wennborg77dc2362015-01-20 19:45:50 +00002422 }
2423}
2424
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002425void WinX86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002426 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2427 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2428 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002429 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002430 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002431}
2432
Chris Lattner04dc9572010-08-31 16:44:54 +00002433class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2434public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002435 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2436 X86AVXABILevel AVXLevel)
Reid Kleckner3fd3de12019-06-20 20:07:20 +00002437 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT, AVXLevel)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002438
Eric Christopher162c91c2015-06-05 22:03:00 +00002439 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002440 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002441
Craig Topper4f12f102014-03-12 06:41:41 +00002442 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002443 return 7;
2444 }
2445
2446 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002447 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002448 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002449
Chris Lattner04dc9572010-08-31 16:44:54 +00002450 // 0-15 are the 16 integer registers.
2451 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002452 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002453 return false;
2454 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002455
2456 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002457 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002458 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002459 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002460 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002461
2462 void getDetectMismatchOption(llvm::StringRef Name,
2463 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002464 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002465 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002466 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002467};
2468
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002469void WinX86_64TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002470 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2471 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2472 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002473 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002474 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002475 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002476 llvm::Function *Fn = cast<llvm::Function>(GV);
2477 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002478 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002479 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2480 llvm::Function *Fn = cast<llvm::Function>(GV);
2481 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2482 }
2483 }
2484
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002485 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002486}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002487}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002488
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002489void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2490 Class &Hi) const {
2491 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2492 //
2493 // (a) If one of the classes is Memory, the whole argument is passed in
2494 // memory.
2495 //
2496 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2497 // memory.
2498 //
2499 // (c) If the size of the aggregate exceeds two eightbytes and the first
2500 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2501 // argument is passed in memory. NOTE: This is necessary to keep the
2502 // ABI working for processors that don't support the __m256 type.
2503 //
2504 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2505 //
2506 // Some of these are enforced by the merging logic. Others can arise
2507 // only with unions; for example:
2508 // union { _Complex double; unsigned; }
2509 //
2510 // Note that clauses (b) and (c) were added in 0.98.
2511 //
2512 if (Hi == Memory)
2513 Lo = Memory;
2514 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2515 Lo = Memory;
2516 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2517 Lo = Memory;
2518 if (Hi == SSEUp && Lo != SSE)
2519 Hi = SSE;
2520}
2521
Chris Lattnerd776fb12010-06-28 21:43:59 +00002522X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002523 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2524 // classified recursively so that always two fields are
2525 // considered. The resulting class is calculated according to
2526 // the classes of the fields in the eightbyte:
2527 //
2528 // (a) If both classes are equal, this is the resulting class.
2529 //
2530 // (b) If one of the classes is NO_CLASS, the resulting class is
2531 // the other class.
2532 //
2533 // (c) If one of the classes is MEMORY, the result is the MEMORY
2534 // class.
2535 //
2536 // (d) If one of the classes is INTEGER, the result is the
2537 // INTEGER.
2538 //
2539 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2540 // MEMORY is used as class.
2541 //
2542 // (f) Otherwise class SSE is used.
2543
2544 // Accum should never be memory (we should have returned) or
2545 // ComplexX87 (because this cannot be passed in a structure).
2546 assert((Accum != Memory && Accum != ComplexX87) &&
2547 "Invalid accumulated classification during merge.");
2548 if (Accum == Field || Field == NoClass)
2549 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002550 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002551 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002552 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002553 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002554 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002556 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2557 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002558 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002559 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002560}
2561
Chris Lattner5c740f12010-06-30 19:14:05 +00002562void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002563 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002564 // FIXME: This code can be simplified by introducing a simple value class for
2565 // Class pairs with appropriate constructor methods for the various
2566 // situations.
2567
2568 // FIXME: Some of the split computations are wrong; unaligned vectors
2569 // shouldn't be passed in registers for example, so there is no chance they
2570 // can straddle an eightbyte. Verify & simplify.
2571
2572 Lo = Hi = NoClass;
2573
2574 Class &Current = OffsetBase < 64 ? Lo : Hi;
2575 Current = Memory;
2576
John McCall9dd450b2009-09-21 23:43:11 +00002577 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002578 BuiltinType::Kind k = BT->getKind();
2579
2580 if (k == BuiltinType::Void) {
2581 Current = NoClass;
2582 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2583 Lo = Integer;
2584 Hi = Integer;
2585 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2586 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002587 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002588 Current = SSE;
2589 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002590 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002591 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002592 Lo = SSE;
2593 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002594 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002595 Lo = X87;
2596 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002597 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002598 Current = SSE;
2599 } else
2600 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002601 }
2602 // FIXME: _Decimal32 and _Decimal64 are SSE.
2603 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002604 return;
2605 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002606
Chris Lattnerd776fb12010-06-28 21:43:59 +00002607 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002608 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002609 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002610 return;
2611 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002612
Chris Lattnerd776fb12010-06-28 21:43:59 +00002613 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002614 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002615 return;
2616 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002617
Chris Lattnerd776fb12010-06-28 21:43:59 +00002618 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002619 if (Ty->isMemberFunctionPointerType()) {
2620 if (Has64BitPointers) {
2621 // If Has64BitPointers, this is an {i64, i64}, so classify both
2622 // Lo and Hi now.
2623 Lo = Hi = Integer;
2624 } else {
2625 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2626 // straddles an eightbyte boundary, Hi should be classified as well.
2627 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2628 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2629 if (EB_FuncPtr != EB_ThisAdj) {
2630 Lo = Hi = Integer;
2631 } else {
2632 Current = Integer;
2633 }
2634 }
2635 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002636 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002637 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002638 return;
2639 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002640
Chris Lattnerd776fb12010-06-28 21:43:59 +00002641 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002642 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002643 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2644 // gcc passes the following as integer:
2645 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2646 // 2 bytes - <2 x char>, <1 x short>
2647 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002648 Current = Integer;
2649
2650 // If this type crosses an eightbyte boundary, it should be
2651 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002652 uint64_t EB_Lo = (OffsetBase) / 64;
2653 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2654 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002655 Hi = Lo;
2656 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002657 QualType ElementType = VT->getElementType();
2658
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002659 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002660 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661 return;
2662
David Majnemere2ae2282016-03-04 05:26:16 +00002663 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2664 // pass them as integer. For platforms where clang is the de facto
2665 // platform compiler, we must continue to use integer.
2666 if (!classifyIntegerMMXAsSSE() &&
2667 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2668 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2669 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2670 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002671 Current = Integer;
2672 else
2673 Current = SSE;
2674
2675 // If this type crosses an eightbyte boundary, it should be
2676 // split.
2677 if (OffsetBase && OffsetBase != 64)
2678 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002679 } else if (Size == 128 ||
2680 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Craig Topper6c8a34e2019-09-06 06:02:13 +00002681 QualType ElementType = VT->getElementType();
2682
2683 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2684 if (passInt128VectorsInMem() && Size != 128 &&
2685 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2686 ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2687 return;
2688
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002689 // Arguments of 256-bits are split into four eightbyte chunks. The
2690 // least significant one belongs to class SSE and all the others to class
2691 // SSEUP. The original Lo and Hi design considers that types can't be
2692 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2693 // This design isn't correct for 256-bits, but since there're no cases
2694 // where the upper parts would need to be inspected, avoid adding
2695 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002696 //
2697 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2698 // registers if they are "named", i.e. not part of the "..." of a
2699 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002700 //
2701 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2702 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002703 Lo = SSE;
2704 Hi = SSEUp;
2705 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002706 return;
2707 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002708
Chris Lattnerd776fb12010-06-28 21:43:59 +00002709 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002710 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002711
Chris Lattner2b037972010-07-29 02:01:43 +00002712 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002713 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002714 if (Size <= 64)
2715 Current = Integer;
2716 else if (Size <= 128)
2717 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002718 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002719 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002720 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002721 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002722 } else if (ET == getContext().LongDoubleTy) {
2723 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002724 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002725 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002726 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002727 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002728 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002729 Lo = Hi = SSE;
2730 else
2731 llvm_unreachable("unexpected long double representation!");
2732 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002733
2734 // If this complex type crosses an eightbyte boundary then it
2735 // should be split.
2736 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002737 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002738 if (Hi == NoClass && EB_Real != EB_Imag)
2739 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002740
Chris Lattnerd776fb12010-06-28 21:43:59 +00002741 return;
2742 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002743
Chris Lattner2b037972010-07-29 02:01:43 +00002744 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002745 // Arrays are treated like structures.
2746
Chris Lattner2b037972010-07-29 02:01:43 +00002747 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002748
2749 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002750 // than eight eightbytes, ..., it has class MEMORY.
2751 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002752 return;
2753
2754 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2755 // fields, it has class MEMORY.
2756 //
2757 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002758 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002759 return;
2760
2761 // Otherwise implement simplified merge. We could be smarter about
2762 // this, but it isn't worth it and would be harder to verify.
2763 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002764 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002765 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002766
2767 // The only case a 256-bit wide vector could be used is when the array
2768 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2769 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002770 //
2771 if (Size > 128 &&
2772 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002773 return;
2774
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002775 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2776 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002777 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002778 Lo = merge(Lo, FieldLo);
2779 Hi = merge(Hi, FieldHi);
2780 if (Lo == Memory || Hi == Memory)
2781 break;
2782 }
2783
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002784 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002785 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002786 return;
2787 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002788
Chris Lattnerd776fb12010-06-28 21:43:59 +00002789 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002790 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002791
2792 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002793 // than eight eightbytes, ..., it has class MEMORY.
2794 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002795 return;
2796
Anders Carlsson20759ad2009-09-16 15:53:40 +00002797 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2798 // copy constructor or a non-trivial destructor, it is passed by invisible
2799 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002800 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002801 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002802
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002803 const RecordDecl *RD = RT->getDecl();
2804
2805 // Assume variable sized types are passed in memory.
2806 if (RD->hasFlexibleArrayMember())
2807 return;
2808
Chris Lattner2b037972010-07-29 02:01:43 +00002809 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002810
2811 // Reset Lo class, this will be recomputed.
2812 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002813
2814 // If this is a C++ record, classify the bases first.
2815 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002816 for (const auto &I : CXXRD->bases()) {
2817 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002818 "Unexpected base class!");
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002819 const auto *Base =
2820 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002821
2822 // Classify this field.
2823 //
2824 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2825 // single eightbyte, each is classified separately. Each eightbyte gets
2826 // initialized to class NO_CLASS.
2827 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002828 uint64_t Offset =
2829 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002830 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002831 Lo = merge(Lo, FieldLo);
2832 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002833 if (Lo == Memory || Hi == Memory) {
2834 postMerge(Size, Lo, Hi);
2835 return;
2836 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002837 }
2838 }
2839
2840 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002841 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002842 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002843 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002844 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2845 bool BitField = i->isBitField();
2846
David Majnemerb439dfe2016-08-15 07:20:40 +00002847 // Ignore padding bit-fields.
2848 if (BitField && i->isUnnamedBitfield())
2849 continue;
2850
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002851 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2852 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002853 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002854 // The only case a 256-bit wide vector could be used is when the struct
2855 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2856 // to work for sizes wider than 128, early check and fallback to memory.
2857 //
David Majnemerb229cb02016-08-15 06:39:18 +00002858 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2859 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002860 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002861 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002862 return;
2863 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002864 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002865 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002866 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002867 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002868 return;
2869 }
2870
2871 // Classify this field.
2872 //
2873 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2874 // exceeds a single eightbyte, each is classified
2875 // separately. Each eightbyte gets initialized to class
2876 // NO_CLASS.
2877 Class FieldLo, FieldHi;
2878
2879 // Bit-fields require special handling, they do not force the
2880 // structure to be passed in memory even if unaligned, and
2881 // therefore they can straddle an eightbyte.
2882 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002883 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002884 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002885 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002886
2887 uint64_t EB_Lo = Offset / 64;
2888 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002889
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002890 if (EB_Lo) {
2891 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2892 FieldLo = NoClass;
2893 FieldHi = Integer;
2894 } else {
2895 FieldLo = Integer;
2896 FieldHi = EB_Hi ? Integer : NoClass;
2897 }
2898 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002899 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002900 Lo = merge(Lo, FieldLo);
2901 Hi = merge(Hi, FieldHi);
2902 if (Lo == Memory || Hi == Memory)
2903 break;
2904 }
2905
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002906 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002907 }
2908}
2909
Chris Lattner22a931e2010-06-29 06:01:59 +00002910ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002911 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2912 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002913 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002914 // Treat an enum type as its underlying type.
2915 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2916 Ty = EnumTy->getDecl()->getIntegerType();
2917
Alex Bradburye41a5e22018-01-12 20:08:16 +00002918 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2919 : ABIArgInfo::getDirect());
Daniel Dunbar53fac692010-04-21 19:49:55 +00002920 }
2921
John McCall7f416cc2015-09-08 08:05:57 +00002922 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002923}
2924
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002925bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2926 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2927 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002928 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002929 if (Size <= 64 || Size > LargestVector)
2930 return true;
Craig Topper6c8a34e2019-09-06 06:02:13 +00002931 QualType EltTy = VecTy->getElementType();
2932 if (passInt128VectorsInMem() &&
2933 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
2934 EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
2935 return true;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002936 }
2937
2938 return false;
2939}
2940
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002941ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2942 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002943 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2944 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002945 //
2946 // This assumption is optimistic, as there could be free registers available
2947 // when we need to pass this argument in memory, and LLVM could try to pass
2948 // the argument in the free register. This does not seem to happen currently,
2949 // but this code would be much safer if we could mark the argument with
2950 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002951 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002952 // Treat an enum type as its underlying type.
2953 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2954 Ty = EnumTy->getDecl()->getIntegerType();
2955
Alex Bradburye41a5e22018-01-12 20:08:16 +00002956 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2957 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002958 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002959
Mark Lacey3825e832013-10-06 01:33:34 +00002960 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002961 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002962
Chris Lattner44c2b902011-05-22 23:21:23 +00002963 // Compute the byval alignment. We specify the alignment of the byval in all
2964 // cases so that the mid-level optimizer knows the alignment of the byval.
2965 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002966
2967 // Attempt to avoid passing indirect results using byval when possible. This
2968 // is important for good codegen.
2969 //
2970 // We do this by coercing the value into a scalar type which the backend can
2971 // handle naturally (i.e., without using byval).
2972 //
2973 // For simplicity, we currently only do this when we have exhausted all of the
2974 // free integer registers. Doing this when there are free integer registers
2975 // would require more care, as we would have to ensure that the coerced value
2976 // did not claim the unused register. That would require either reording the
2977 // arguments to the function (so that any subsequent inreg values came first),
2978 // or only doing this optimization when there were no following arguments that
2979 // might be inreg.
2980 //
2981 // We currently expect it to be rare (particularly in well written code) for
2982 // arguments to be passed on the stack when there are still free integer
2983 // registers available (this would typically imply large structs being passed
2984 // by value), so this seems like a fair tradeoff for now.
2985 //
2986 // We can revisit this if the backend grows support for 'onstack' parameter
2987 // attributes. See PR12193.
2988 if (freeIntRegs == 0) {
2989 uint64_t Size = getContext().getTypeSize(Ty);
2990
2991 // If this type fits in an eightbyte, coerce it into the matching integral
2992 // type, which will end up on the stack (with alignment 8).
2993 if (Align == 8 && Size <= 64)
2994 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2995 Size));
2996 }
2997
John McCall7f416cc2015-09-08 08:05:57 +00002998 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002999}
3000
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00003001/// The ABI specifies that a value should be passed in a full vector XMM/YMM
3002/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003003llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00003004 // Wrapper structs/arrays that only contain vectors are passed just like
3005 // vectors; strip them off if present.
3006 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3007 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003008
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00003009 llvm::Type *IRType = CGT.ConvertType(Ty);
Craig Topper6c8a34e2019-09-06 06:02:13 +00003010 if (isa<llvm::VectorType>(IRType)) {
3011 // Don't pass vXi128 vectors in their native type, the backend can't
3012 // legalize them.
3013 if (passInt128VectorsInMem() &&
3014 IRType->getVectorElementType()->isIntegerTy(128)) {
3015 // Use a vXi64 vector.
3016 uint64_t Size = getContext().getTypeSize(Ty);
3017 return llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3018 Size / 64);
3019 }
3020
3021 return IRType;
3022 }
3023
3024 if (IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00003025 return IRType;
3026
3027 // We couldn't find the preferred IR vector type for 'Ty'.
3028 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00003029 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00003030
Craig Topper6c8a34e2019-09-06 06:02:13 +00003031
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00003032 // Return a LLVM IR vector type based on the size of 'Ty'.
3033 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3034 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00003035}
3036
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003037/// BitsContainNoUserData - Return true if the specified [start,end) bit range
3038/// is known to either be off the end of the specified type or being in
3039/// alignment padding. The user type specified is known to be at most 128 bits
3040/// in size, and have passed through X86_64ABIInfo::classify with a successful
3041/// classification that put one of the two halves in the INTEGER class.
3042///
3043/// It is conservatively correct to return false.
3044static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3045 unsigned EndBit, ASTContext &Context) {
3046 // If the bytes being queried are off the end of the type, there is no user
3047 // data hiding here. This handles analysis of builtins, vectors and other
3048 // types that don't contain interesting padding.
3049 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3050 if (TySize <= StartBit)
3051 return true;
3052
Chris Lattner98076a22010-07-29 07:43:55 +00003053 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3054 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3055 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3056
3057 // Check each element to see if the element overlaps with the queried range.
3058 for (unsigned i = 0; i != NumElts; ++i) {
3059 // If the element is after the span we care about, then we're done..
3060 unsigned EltOffset = i*EltSize;
3061 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003062
Chris Lattner98076a22010-07-29 07:43:55 +00003063 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3064 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3065 EndBit-EltOffset, Context))
3066 return false;
3067 }
3068 // If it overlaps no elements, then it is safe to process as padding.
3069 return true;
3070 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003071
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003072 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3073 const RecordDecl *RD = RT->getDecl();
3074 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003075
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003076 // If this is a C++ record, check the bases first.
3077 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003078 for (const auto &I : CXXRD->bases()) {
3079 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003080 "Unexpected base class!");
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003081 const auto *Base =
3082 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003083
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003084 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003085 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003086 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003087
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003088 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003089 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003090 EndBit-BaseOffset, Context))
3091 return false;
3092 }
3093 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003094
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003095 // Verify that no field has data that overlaps the region of interest. Yes
3096 // this could be sped up a lot by being smarter about queried fields,
3097 // however we're only looking at structs up to 16 bytes, so we don't care
3098 // much.
3099 unsigned idx = 0;
3100 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3101 i != e; ++i, ++idx) {
3102 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003103
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003104 // If we found a field after the region we care about, then we're done.
3105 if (FieldOffset >= EndBit) break;
3106
3107 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3108 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3109 Context))
3110 return false;
3111 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003112
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003113 // If nothing in this record overlapped the area of interest, then we're
3114 // clean.
3115 return true;
3116 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003117
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003118 return false;
3119}
3120
Chris Lattnere556a712010-07-29 18:39:32 +00003121/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3122/// float member at the specified offset. For example, {int,{float}} has a
3123/// float at offset 4. It is conservatively correct for this routine to return
3124/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003125static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003126 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003127 // Base case if we find a float.
3128 if (IROffset == 0 && IRType->isFloatTy())
3129 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003130
Chris Lattnere556a712010-07-29 18:39:32 +00003131 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003132 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003133 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3134 unsigned Elt = SL->getElementContainingOffset(IROffset);
3135 IROffset -= SL->getElementOffset(Elt);
3136 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3137 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003138
Chris Lattnere556a712010-07-29 18:39:32 +00003139 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003140 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3141 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003142 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3143 IROffset -= IROffset/EltSize*EltSize;
3144 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3145 }
3146
3147 return false;
3148}
3149
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003150
3151/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3152/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003153llvm::Type *X86_64ABIInfo::
3154GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003155 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003156 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003157 // pass as float if the last 4 bytes is just padding. This happens for
3158 // structs that contain 3 floats.
3159 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3160 SourceOffset*8+64, getContext()))
3161 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003162
Chris Lattnere556a712010-07-29 18:39:32 +00003163 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3164 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3165 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003166 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3167 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003168 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003169
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003170 return llvm::Type::getDoubleTy(getVMContext());
3171}
3172
3173
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003174/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3175/// an 8-byte GPR. This means that we either have a scalar or we are talking
3176/// about the high or low part of an up-to-16-byte struct. This routine picks
3177/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003178/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3179/// etc).
3180///
3181/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3182/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3183/// the 8-byte value references. PrefType may be null.
3184///
Alp Toker9907f082014-07-09 14:06:35 +00003185/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003186/// an offset into this that we're processing (which is always either 0 or 8).
3187///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003188llvm::Type *X86_64ABIInfo::
3189GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003190 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003191 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3192 // returning an 8-byte unit starting with it. See if we can safely use it.
3193 if (IROffset == 0) {
3194 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003195 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3196 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003197 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003198
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003199 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3200 // goodness in the source type is just tail padding. This is allowed to
3201 // kick in for struct {double,int} on the int, but not on
3202 // struct{double,int,int} because we wouldn't return the second int. We
3203 // have to do this analysis on the source type because we can't depend on
3204 // unions being lowered a specific way etc.
3205 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003206 IRType->isIntegerTy(32) ||
3207 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3208 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3209 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003210
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003211 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3212 SourceOffset*8+64, getContext()))
3213 return IRType;
3214 }
3215 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003216
Chris Lattner2192fe52011-07-18 04:24:23 +00003217 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003218 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003219 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003220 if (IROffset < SL->getSizeInBytes()) {
3221 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3222 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003223
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003224 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3225 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003226 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003227 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003228
Chris Lattner2192fe52011-07-18 04:24:23 +00003229 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003230 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003231 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003232 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003233 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3234 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003235 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003236
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003237 // Okay, we don't have any better idea of what to pass, so we pass this in an
3238 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003239 unsigned TySizeInBytes =
3240 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003241
Chris Lattner3f763422010-07-29 17:34:39 +00003242 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003243
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003244 // It is always safe to classify this as an integer type up to i64 that
3245 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003246 return llvm::IntegerType::get(getVMContext(),
3247 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003248}
3249
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003250
3251/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3252/// be used as elements of a two register pair to pass or return, return a
3253/// first class aggregate to represent them. For example, if the low part of
3254/// a by-value argument should be passed as i32* and the high part as float,
3255/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003256static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003257GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003258 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003259 // In order to correctly satisfy the ABI, we need to the high part to start
3260 // at offset 8. If the high and low parts we inferred are both 4-byte types
3261 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3262 // the second element at offset 8. Check for this:
3263 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3264 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003265 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003266 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003267
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003268 // To handle this, we have to increase the size of the low part so that the
3269 // second element will start at an 8 byte offset. We can't increase the size
3270 // of the second element because it might make us access off the end of the
3271 // struct.
3272 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003273 // There are usually two sorts of types the ABI generation code can produce
3274 // for the low part of a pair that aren't 8 bytes in size: float or
3275 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3276 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003277 // Promote these to a larger type.
3278 if (Lo->isFloatTy())
3279 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3280 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003281 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3282 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003283 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3284 }
3285 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003286
Serge Guelton1d993272017-05-09 19:31:30 +00003287 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003288
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003289 // Verify that the second element is at an 8-byte offset.
3290 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3291 "Invalid x86-64 argument pair!");
3292 return Result;
3293}
3294
Chris Lattner31faff52010-07-28 23:06:14 +00003295ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003296classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003297 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3298 // classification algorithm.
3299 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003300 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003301
3302 // Check some invariants.
3303 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003304 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3305
Craig Topper8a13c412014-05-21 05:09:00 +00003306 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003307 switch (Lo) {
3308 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003309 if (Hi == NoClass)
3310 return ABIArgInfo::getIgnore();
3311 // If the low part is just padding, it takes no register, leave ResType
3312 // null.
3313 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3314 "Unknown missing lo part");
3315 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003316
3317 case SSEUp:
3318 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003319 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003320
3321 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3322 // hidden argument.
3323 case Memory:
3324 return getIndirectReturnResult(RetTy);
3325
3326 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3327 // available register of the sequence %rax, %rdx is used.
3328 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003329 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003330
Chris Lattner1f3a0632010-07-29 21:42:50 +00003331 // If we have a sign or zero extended integer, make sure to return Extend
3332 // so that the parameter gets the right LLVM IR attributes.
3333 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3334 // Treat an enum type as its underlying type.
3335 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3336 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003337
Chris Lattner1f3a0632010-07-29 21:42:50 +00003338 if (RetTy->isIntegralOrEnumerationType() &&
3339 RetTy->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003340 return ABIArgInfo::getExtend(RetTy);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003341 }
Chris Lattner31faff52010-07-28 23:06:14 +00003342 break;
3343
3344 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3345 // available SSE register of the sequence %xmm0, %xmm1 is used.
3346 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003347 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003348 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003349
3350 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3351 // returned on the X87 stack in %st0 as 80-bit x87 number.
3352 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003353 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003354 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003355
3356 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3357 // part of the value is returned in %st0 and the imaginary part in
3358 // %st1.
3359 case ComplexX87:
3360 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003361 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003362 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003363 break;
3364 }
3365
Craig Topper8a13c412014-05-21 05:09:00 +00003366 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003367 switch (Hi) {
3368 // Memory was handled previously and X87 should
3369 // never occur as a hi class.
3370 case Memory:
3371 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003372 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003373
3374 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003375 case NoClass:
3376 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003377
Chris Lattner52b3c132010-09-01 00:20:33 +00003378 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003379 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003380 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3381 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003382 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003383 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003384 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003385 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3386 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003387 break;
3388
3389 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003390 // is passed in the next available eightbyte chunk if the last used
3391 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003392 //
Chris Lattner57540c52011-04-15 05:22:18 +00003393 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003394 case SSEUp:
3395 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003396 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003397 break;
3398
3399 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3400 // returned together with the previous X87 value in %st0.
3401 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003402 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003403 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003404 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003405 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003406 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003407 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003408 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3409 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003410 }
Chris Lattner31faff52010-07-28 23:06:14 +00003411 break;
3412 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003413
Chris Lattner52b3c132010-09-01 00:20:33 +00003414 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003415 // known to pass in the high eightbyte of the result. We do this by forming a
3416 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003417 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003418 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003419
Chris Lattner1f3a0632010-07-29 21:42:50 +00003420 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003421}
3422
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003423ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003424 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3425 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003426 const
3427{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003428 Ty = useFirstFieldIfTransparentUnion(Ty);
3429
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003430 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003431 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003432
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003433 // Check some invariants.
3434 // FIXME: Enforce these by construction.
3435 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003436 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3437
3438 neededInt = 0;
3439 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003440 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003441 switch (Lo) {
3442 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003443 if (Hi == NoClass)
3444 return ABIArgInfo::getIgnore();
3445 // If the low part is just padding, it takes no register, leave ResType
3446 // null.
3447 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3448 "Unknown missing lo part");
3449 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003450
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003451 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3452 // on the stack.
3453 case Memory:
3454
3455 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3456 // COMPLEX_X87, it is passed in memory.
3457 case X87:
3458 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003459 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003460 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003461 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003462
3463 case SSEUp:
3464 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003465 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003466
3467 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3468 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3469 // and %r9 is used.
3470 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003471 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003472
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003473 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003474 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003475
3476 // If we have a sign or zero extended integer, make sure to return Extend
3477 // so that the parameter gets the right LLVM IR attributes.
3478 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3479 // Treat an enum type as its underlying type.
3480 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3481 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003482
Chris Lattner1f3a0632010-07-29 21:42:50 +00003483 if (Ty->isIntegralOrEnumerationType() &&
3484 Ty->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003485 return ABIArgInfo::getExtend(Ty);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003486 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003487
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003488 break;
3489
3490 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3491 // available SSE register is used, the registers are taken in the
3492 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003493 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003494 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003495 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003496 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003497 break;
3498 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003499 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003500
Craig Topper8a13c412014-05-21 05:09:00 +00003501 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003502 switch (Hi) {
3503 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003504 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003505 // which is passed in memory.
3506 case Memory:
3507 case X87:
3508 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003509 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003510
3511 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003512
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003513 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003514 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003515 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003516 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003517
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003518 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3519 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003520 break;
3521
3522 // X87Up generally doesn't occur here (long double is passed in
3523 // memory), except in situations involving unions.
3524 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003525 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003526 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003527
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003528 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3529 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003530
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003531 ++neededSSE;
3532 break;
3533
3534 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3535 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003536 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003537 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003538 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003539 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003540 break;
3541 }
3542
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003543 // If a high part was specified, merge it together with the low part. It is
3544 // known to pass in the high eightbyte of the result. We do this by forming a
3545 // first class struct aggregate with the high and low part: {low, high}
3546 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003547 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003548
Chris Lattner1f3a0632010-07-29 21:42:50 +00003549 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003550}
3551
Erich Keane757d3172016-11-02 18:29:35 +00003552ABIArgInfo
3553X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3554 unsigned &NeededSSE) const {
3555 auto RT = Ty->getAs<RecordType>();
3556 assert(RT && "classifyRegCallStructType only valid with struct types");
3557
3558 if (RT->getDecl()->hasFlexibleArrayMember())
3559 return getIndirectReturnResult(Ty);
3560
3561 // Sum up bases
3562 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3563 if (CXXRD->isDynamicClass()) {
3564 NeededInt = NeededSSE = 0;
3565 return getIndirectReturnResult(Ty);
3566 }
3567
3568 for (const auto &I : CXXRD->bases())
3569 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3570 .isIndirect()) {
3571 NeededInt = NeededSSE = 0;
3572 return getIndirectReturnResult(Ty);
3573 }
3574 }
3575
3576 // Sum up members
3577 for (const auto *FD : RT->getDecl()->fields()) {
3578 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3579 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3580 .isIndirect()) {
3581 NeededInt = NeededSSE = 0;
3582 return getIndirectReturnResult(Ty);
3583 }
3584 } else {
3585 unsigned LocalNeededInt, LocalNeededSSE;
3586 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3587 LocalNeededSSE, true)
3588 .isIndirect()) {
3589 NeededInt = NeededSSE = 0;
3590 return getIndirectReturnResult(Ty);
3591 }
3592 NeededInt += LocalNeededInt;
3593 NeededSSE += LocalNeededSSE;
3594 }
3595 }
3596
3597 return ABIArgInfo::getDirect();
3598}
3599
3600ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3601 unsigned &NeededInt,
3602 unsigned &NeededSSE) const {
3603
3604 NeededInt = 0;
3605 NeededSSE = 0;
3606
3607 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3608}
3609
Chris Lattner22326a12010-07-29 02:31:05 +00003610void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003611
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003612 const unsigned CallingConv = FI.getCallingConvention();
3613 // It is possible to force Win64 calling convention on any x86_64 target by
3614 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3615 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3616 if (CallingConv == llvm::CallingConv::Win64) {
Reid Kleckner3fd3de12019-06-20 20:07:20 +00003617 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003618 Win64ABIInfo.computeInfo(FI);
3619 return;
3620 }
3621
3622 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003623
3624 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003625 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3626 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3627 unsigned NeededInt, NeededSSE;
3628
Akira Hatanakad791e922018-03-19 17:38:40 +00003629 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Erich Keanede1b2a92017-07-21 18:50:36 +00003630 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3631 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3632 FI.getReturnInfo() =
3633 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3634 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3635 FreeIntRegs -= NeededInt;
3636 FreeSSERegs -= NeededSSE;
3637 } else {
3638 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3639 }
3640 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3641 // Complex Long Double Type is passed in Memory when Regcall
3642 // calling convention is used.
3643 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3644 if (getContext().getCanonicalType(CT->getElementType()) ==
3645 getContext().LongDoubleTy)
3646 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3647 } else
3648 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3649 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003650
3651 // If the return value is indirect, then the hidden argument is consuming one
3652 // integer register.
3653 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003654 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003655
Peter Collingbournef7706832014-12-12 23:41:25 +00003656 // The chain argument effectively gives us another free register.
3657 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003658 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003659
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003660 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003661 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3662 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003663 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003664 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003665 it != ie; ++it, ++ArgNo) {
3666 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003667
Erich Keane757d3172016-11-02 18:29:35 +00003668 if (IsRegCall && it->type->isStructureOrClassType())
3669 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3670 else
3671 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3672 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003673
3674 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3675 // eightbyte of an argument, the whole argument is passed on the
3676 // stack. If registers have already been assigned for some
3677 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003678 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3679 FreeIntRegs -= NeededInt;
3680 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003681 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003682 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003683 }
3684 }
3685}
3686
John McCall7f416cc2015-09-08 08:05:57 +00003687static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3688 Address VAListAddr, QualType Ty) {
James Y Knight751fe282019-02-09 22:22:28 +00003689 Address overflow_arg_area_p =
3690 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003691 llvm::Value *overflow_arg_area =
3692 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3693
3694 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3695 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003696 // It isn't stated explicitly in the standard, but in practice we use
3697 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003698 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3699 if (Align > CharUnits::fromQuantity(8)) {
3700 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3701 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003702 }
3703
3704 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003705 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003706 llvm::Value *Res =
3707 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003708 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003709
3710 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3711 // l->overflow_arg_area + sizeof(type).
3712 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3713 // an 8 byte boundary.
3714
3715 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003716 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003717 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003718 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3719 "overflow_arg_area.next");
3720 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3721
3722 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003723 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003724}
3725
John McCall7f416cc2015-09-08 08:05:57 +00003726Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3727 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003728 // Assume that va_list type is correct; should be pointer to LLVM type:
3729 // struct {
3730 // i32 gp_offset;
3731 // i32 fp_offset;
3732 // i8* overflow_arg_area;
3733 // i8* reg_save_area;
3734 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003735 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003736
John McCall7f416cc2015-09-08 08:05:57 +00003737 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003738 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003739 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003740
3741 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3742 // in the registers. If not go to step 7.
3743 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003744 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003745
3746 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3747 // general purpose registers needed to pass type and num_fp to hold
3748 // the number of floating point registers needed.
3749
3750 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3751 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3752 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3753 //
3754 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3755 // register save space).
3756
Craig Topper8a13c412014-05-21 05:09:00 +00003757 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003758 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3759 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003760 if (neededInt) {
James Y Knight751fe282019-02-09 22:22:28 +00003761 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003762 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003763 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3764 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003765 }
3766
3767 if (neededSSE) {
James Y Knight751fe282019-02-09 22:22:28 +00003768 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003769 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3770 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003771 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3772 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003773 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3774 }
3775
3776 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3777 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3778 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3779 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3780
3781 // Emit code to load the value if it was passed in registers.
3782
3783 CGF.EmitBlock(InRegBlock);
3784
3785 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3786 // an offset of l->gp_offset and/or l->fp_offset. This may require
3787 // copying to a temporary location in case the parameter is passed
3788 // in different register classes or requires an alignment greater
3789 // than 8 for general purpose registers and 16 for XMM registers.
3790 //
3791 // FIXME: This really results in shameful code when we end up needing to
3792 // collect arguments from different places; often what should result in a
3793 // simple assembling of a structure from scattered addresses has many more
3794 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003795 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003796 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
James Y Knight751fe282019-02-09 22:22:28 +00003797 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00003798
3799 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003800 if (neededInt && neededSSE) {
3801 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003802 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003803 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003804 Address Tmp = CGF.CreateMemTemp(Ty);
3805 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003806 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003807 llvm::Type *TyLo = ST->getElementType(0);
3808 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003809 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003810 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003811 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3812 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003813 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3814 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003815 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3816 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003817
John McCall7f416cc2015-09-08 08:05:57 +00003818 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003819 // FIXME: Our choice of alignment here and below is probably pessimistic.
3820 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3821 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3822 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
James Y Knight751fe282019-02-09 22:22:28 +00003823 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
John McCall7f416cc2015-09-08 08:05:57 +00003824
3825 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003826 V = CGF.Builder.CreateAlignedLoad(
3827 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3828 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
James Y Knight751fe282019-02-09 22:22:28 +00003829 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
John McCall7f416cc2015-09-08 08:05:57 +00003830
3831 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003832 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003833 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3834 CharUnits::fromQuantity(8));
3835 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003836
3837 // Copy to a temporary if necessary to ensure the appropriate alignment.
3838 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003839 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003840 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003841 CharUnits TyAlign = SizeAlign.second;
3842
3843 // Copy into a temporary if the type is more aligned than the
3844 // register save area.
3845 if (TyAlign.getQuantity() > 8) {
3846 Address Tmp = CGF.CreateMemTemp(Ty);
3847 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003848 RegAddr = Tmp;
3849 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003850
Chris Lattner0cf24192010-06-28 20:05:43 +00003851 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003852 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3853 CharUnits::fromQuantity(16));
3854 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003855 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003856 assert(neededSSE == 2 && "Invalid number of needed registers!");
3857 // SSE registers are spaced 16 bytes apart in the register save
3858 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003859 // The ABI isn't explicit about this, but it seems reasonable
3860 // to assume that the slots are 16-byte aligned, since the stack is
3861 // naturally 16-byte aligned and the prologue is expected to store
3862 // all the SSE registers to the RSA.
3863 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3864 CharUnits::fromQuantity(16));
3865 Address RegAddrHi =
3866 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3867 CharUnits::fromQuantity(16));
Erich Keane24e68402018-02-02 15:53:35 +00003868 llvm::Type *ST = AI.canHaveCoerceToType()
3869 ? AI.getCoerceToType()
3870 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003871 llvm::Value *V;
3872 Address Tmp = CGF.CreateMemTemp(Ty);
3873 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Erich Keane24e68402018-02-02 15:53:35 +00003874 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3875 RegAddrLo, ST->getStructElementType(0)));
James Y Knight751fe282019-02-09 22:22:28 +00003876 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
Erich Keane24e68402018-02-02 15:53:35 +00003877 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3878 RegAddrHi, ST->getStructElementType(1)));
James Y Knight751fe282019-02-09 22:22:28 +00003879 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
John McCall7f416cc2015-09-08 08:05:57 +00003880
3881 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003882 }
3883
3884 // AMD64-ABI 3.5.7p5: Step 5. Set:
3885 // l->gp_offset = l->gp_offset + num_gp * 8
3886 // l->fp_offset = l->fp_offset + num_fp * 16.
3887 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003888 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003889 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3890 gp_offset_p);
3891 }
3892 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003893 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003894 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3895 fp_offset_p);
3896 }
3897 CGF.EmitBranch(ContBlock);
3898
3899 // Emit code to load the value if it was passed in memory.
3900
3901 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003902 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003903
3904 // Return the appropriate result.
3905
3906 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003907 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3908 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003909 return ResAddr;
3910}
3911
Charles Davisc7d5c942015-09-17 20:55:33 +00003912Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3913 QualType Ty) const {
3914 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3915 CGF.getContext().getTypeInfoInChars(Ty),
3916 CharUnits::fromQuantity(8),
3917 /*allowHigherAlign*/ false);
3918}
3919
Erich Keane521ed962017-01-05 00:20:51 +00003920ABIArgInfo
3921WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3922 const ABIArgInfo &current) const {
3923 // Assumes vectorCall calling convention.
3924 const Type *Base = nullptr;
3925 uint64_t NumElts = 0;
3926
3927 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3928 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3929 FreeSSERegs -= NumElts;
3930 return getDirectX86Hva();
3931 }
3932 return current;
3933}
3934
Reid Kleckner80944df2014-10-31 22:00:51 +00003935ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003936 bool IsReturnType, bool IsVectorCall,
3937 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003938
3939 if (Ty->isVoidType())
3940 return ABIArgInfo::getIgnore();
3941
3942 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3943 Ty = EnumTy->getDecl()->getIntegerType();
3944
Reid Kleckner80944df2014-10-31 22:00:51 +00003945 TypeInfo Info = getContext().getTypeInfo(Ty);
3946 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003947 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003948
Reid Kleckner9005f412014-05-02 00:51:20 +00003949 const RecordType *RT = Ty->getAs<RecordType>();
3950 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003951 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003952 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003953 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003954 }
3955
3956 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003957 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003958
Reid Kleckner9005f412014-05-02 00:51:20 +00003959 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003960
Reid Kleckner80944df2014-10-31 22:00:51 +00003961 const Type *Base = nullptr;
3962 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003963 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3964 // other targets.
3965 if ((IsVectorCall || IsRegCall) &&
3966 isHomogeneousAggregate(Ty, Base, NumElts)) {
3967 if (IsRegCall) {
3968 if (FreeSSERegs >= NumElts) {
3969 FreeSSERegs -= NumElts;
3970 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3971 return ABIArgInfo::getDirect();
3972 return ABIArgInfo::getExpand();
3973 }
3974 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3975 } else if (IsVectorCall) {
3976 if (FreeSSERegs >= NumElts &&
3977 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3978 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003979 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003980 } else if (IsReturnType) {
3981 return ABIArgInfo::getExpand();
3982 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3983 // HVAs are delayed and reclassified in the 2nd step.
3984 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3985 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003986 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003987 }
3988
Reid Klecknerec87fec2014-05-02 01:17:12 +00003989 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003990 // If the member pointer is represented by an LLVM int or ptr, pass it
3991 // directly.
3992 llvm::Type *LLTy = CGT.ConvertType(Ty);
3993 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3994 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003995 }
3996
Michael Kuperstein4f818702015-02-24 09:35:58 +00003997 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003998 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3999 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00004000 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00004001 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004002
Reid Kleckner9005f412014-05-02 00:51:20 +00004003 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00004004 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004005 }
4006
Reid Kleckner08f64e92018-10-31 17:43:55 +00004007 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4008 switch (BT->getKind()) {
4009 case BuiltinType::Bool:
4010 // Bool type is always extended to the ABI, other builtin types are not
4011 // extended.
4012 return ABIArgInfo::getExtend(Ty);
4013
4014 case BuiltinType::LongDouble:
4015 // Mingw64 GCC uses the old 80 bit extended precision floating point
4016 // unit. It passes them indirectly through memory.
4017 if (IsMingw64) {
4018 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4019 if (LDF == &llvm::APFloat::x87DoubleExtended())
4020 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4021 }
4022 break;
4023
4024 case BuiltinType::Int128:
4025 case BuiltinType::UInt128:
4026 // If it's a parameter type, the normal ABI rule is that arguments larger
4027 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4028 // even though it isn't particularly efficient.
4029 if (!IsReturnType)
4030 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4031
4032 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4033 // Clang matches them for compatibility.
4034 return ABIArgInfo::getDirect(
4035 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2));
4036
4037 default:
4038 break;
4039 }
Reid Kleckner11a17192015-10-28 22:29:52 +00004040 }
4041
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004042 return ABIArgInfo::getDirect();
4043}
4044
Erich Keane521ed962017-01-05 00:20:51 +00004045void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4046 unsigned FreeSSERegs,
4047 bool IsVectorCall,
4048 bool IsRegCall) const {
4049 unsigned Count = 0;
4050 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004051 // Vectorcall in x64 only permits the first 6 arguments to be passed
4052 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00004053 if (Count < VectorcallMaxParamNumAsReg)
4054 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4055 else {
4056 // Since these cannot be passed in registers, pretend no registers
4057 // are left.
4058 unsigned ZeroSSERegsAvail = 0;
4059 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4060 IsVectorCall, IsRegCall);
4061 }
4062 ++Count;
4063 }
4064
Erich Keane521ed962017-01-05 00:20:51 +00004065 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004066 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00004067 }
4068}
4069
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004070void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner3fd3de12019-06-20 20:07:20 +00004071 const unsigned CC = FI.getCallingConvention();
4072 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4073 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4074
4075 // If __attribute__((sysv_abi)) is in use, use the SysV argument
4076 // classification rules.
4077 if (CC == llvm::CallingConv::X86_64_SysV) {
4078 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4079 SysVABIInfo.computeInfo(FI);
4080 return;
4081 }
Reid Kleckner37abaca2014-05-09 22:46:15 +00004082
Erich Keane757d3172016-11-02 18:29:35 +00004083 unsigned FreeSSERegs = 0;
4084 if (IsVectorCall) {
4085 // We can use up to 4 SSE return registers with vectorcall.
4086 FreeSSERegs = 4;
4087 } else if (IsRegCall) {
4088 // RegCall gives us 16 SSE registers.
4089 FreeSSERegs = 16;
4090 }
4091
Reid Kleckner80944df2014-10-31 22:00:51 +00004092 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00004093 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4094 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00004095
Erich Keane757d3172016-11-02 18:29:35 +00004096 if (IsVectorCall) {
4097 // We can use up to 6 SSE register parameters with vectorcall.
4098 FreeSSERegs = 6;
4099 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004100 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004101 FreeSSERegs = 16;
4102 }
4103
Erich Keane521ed962017-01-05 00:20:51 +00004104 if (IsVectorCall) {
4105 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4106 } else {
4107 for (auto &I : FI.arguments())
4108 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4109 }
4110
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004111}
4112
John McCall7f416cc2015-09-08 08:05:57 +00004113Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4114 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004115
4116 bool IsIndirect = false;
4117
4118 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4119 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4120 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4121 uint64_t Width = getContext().getTypeSize(Ty);
4122 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4123 }
4124
4125 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004126 CGF.getContext().getTypeInfoInChars(Ty),
4127 CharUnits::fromQuantity(8),
4128 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004129}
Chris Lattner0cf24192010-06-28 20:05:43 +00004130
John McCallea8d8bb2010-03-11 00:10:12 +00004131// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004132namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004133/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4134class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004135 bool IsSoftFloatABI;
4136
4137 CharUnits getParamTypeAlignment(QualType Ty) const;
4138
John McCallea8d8bb2010-03-11 00:10:12 +00004139public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004140 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4141 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004142
John McCall7f416cc2015-09-08 08:05:57 +00004143 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4144 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004145};
4146
4147class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4148public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004149 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4150 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004151
Craig Topper4f12f102014-03-12 06:41:41 +00004152 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004153 // This is recovered from gcc output.
4154 return 1; // r1 is the dedicated stack pointer
4155 }
4156
4157 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004158 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004159};
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004160}
John McCallea8d8bb2010-03-11 00:10:12 +00004161
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004162CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4163 // Complex types are passed just like their elements
4164 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4165 Ty = CTy->getElementType();
4166
4167 if (Ty->isVectorType())
4168 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4169 : 4);
4170
4171 // For single-element float/vector structs, we consider the whole type
4172 // to have the same alignment requirements as its single element.
4173 const Type *AlignTy = nullptr;
4174 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4175 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4176 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4177 (BT && BT->isFloatingPoint()))
4178 AlignTy = EltType;
4179 }
4180
4181 if (AlignTy)
4182 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4183 return CharUnits::fromQuantity(4);
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004184}
John McCallea8d8bb2010-03-11 00:10:12 +00004185
James Y Knight29b5f082016-02-24 02:59:33 +00004186// TODO: this implementation is now likely redundant with
4187// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004188Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4189 QualType Ty) const {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004190 if (getTarget().getTriple().isOSDarwin()) {
4191 auto TI = getContext().getTypeInfoInChars(Ty);
4192 TI.second = getParamTypeAlignment(Ty);
4193
4194 CharUnits SlotSize = CharUnits::fromQuantity(4);
4195 return emitVoidPtrVAArg(CGF, VAList, Ty,
4196 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4197 /*AllowHigherAlign=*/true);
4198 }
4199
Roman Divacky039b9702016-02-20 08:31:24 +00004200 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004201 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4202 // TODO: Implement this. For now ignore.
4203 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004204 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004205 }
4206
John McCall7f416cc2015-09-08 08:05:57 +00004207 // struct __va_list_tag {
4208 // unsigned char gpr;
4209 // unsigned char fpr;
4210 // unsigned short reserved;
4211 // void *overflow_arg_area;
4212 // void *reg_save_area;
4213 // };
4214
Roman Divacky8a12d842014-11-03 18:32:54 +00004215 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004216 bool isInt =
4217 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004218 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004219
4220 // All aggregates are passed indirectly? That doesn't seem consistent
4221 // with the argument-lowering code.
4222 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004223
4224 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004225
4226 // The calling convention either uses 1-2 GPRs or 1 FPR.
4227 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004228 if (isInt || IsSoftFloatABI) {
James Y Knight751fe282019-02-09 22:22:28 +00004229 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
John McCall7f416cc2015-09-08 08:05:57 +00004230 } else {
James Y Knight751fe282019-02-09 22:22:28 +00004231 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004232 }
John McCall7f416cc2015-09-08 08:05:57 +00004233
4234 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4235
4236 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004237 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004238 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4239 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4240 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004241
Eric Christopher7565e0d2015-05-29 23:09:49 +00004242 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004243 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004244
4245 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4246 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4247 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4248
4249 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4250
John McCall7f416cc2015-09-08 08:05:57 +00004251 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4252 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004253
John McCall7f416cc2015-09-08 08:05:57 +00004254 // Case 1: consume registers.
4255 Address RegAddr = Address::invalid();
4256 {
4257 CGF.EmitBlock(UsingRegs);
4258
James Y Knight751fe282019-02-09 22:22:28 +00004259 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
John McCall7f416cc2015-09-08 08:05:57 +00004260 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4261 CharUnits::fromQuantity(8));
4262 assert(RegAddr.getElementType() == CGF.Int8Ty);
4263
4264 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004265 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004266 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4267 CharUnits::fromQuantity(32));
4268 }
4269
4270 // Get the address of the saved value by scaling the number of
Fangrui Song6907ce22018-07-30 19:24:48 +00004271 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004272 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004273 llvm::Value *RegOffset =
4274 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4275 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4276 RegAddr.getPointer(), RegOffset),
4277 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4278 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4279
4280 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004281 NumRegs =
Fangrui Song6907ce22018-07-30 19:24:48 +00004282 Builder.CreateAdd(NumRegs,
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004283 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004284 Builder.CreateStore(NumRegs, NumRegsAddr);
4285
4286 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004287 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004288
John McCall7f416cc2015-09-08 08:05:57 +00004289 // Case 2: consume space in the overflow area.
4290 Address MemAddr = Address::invalid();
4291 {
4292 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004293
Roman Divacky039b9702016-02-20 08:31:24 +00004294 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4295
John McCall7f416cc2015-09-08 08:05:57 +00004296 // Everything in the overflow area is rounded up to a size of at least 4.
4297 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4298
4299 CharUnits Size;
4300 if (!isIndirect) {
4301 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004302 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004303 } else {
4304 Size = CGF.getPointerSize();
4305 }
4306
James Y Knight751fe282019-02-09 22:22:28 +00004307 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004308 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004309 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004310 // Round up address of argument to alignment
4311 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4312 if (Align > OverflowAreaAlign) {
4313 llvm::Value *Ptr = OverflowArea.getPointer();
4314 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4315 Align);
4316 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004317
John McCall7f416cc2015-09-08 08:05:57 +00004318 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4319
4320 // Increase the overflow area.
4321 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4322 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4323 CGF.EmitBranch(Cont);
4324 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004325
4326 CGF.EmitBlock(Cont);
4327
John McCall7f416cc2015-09-08 08:05:57 +00004328 // Merge the cases with a phi.
4329 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4330 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004331
John McCall7f416cc2015-09-08 08:05:57 +00004332 // Load the pointer if the argument was passed indirectly.
4333 if (isIndirect) {
4334 Result = Address(Builder.CreateLoad(Result, "aggr"),
4335 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004336 }
4337
4338 return Result;
4339}
4340
John McCallea8d8bb2010-03-11 00:10:12 +00004341bool
4342PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4343 llvm::Value *Address) const {
4344 // This is calculated from the LLVM and GCC tables and verified
4345 // against gcc output. AFAIK all ABIs use the same encoding.
4346
4347 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004348
Chris Lattnerece04092012-02-07 00:39:47 +00004349 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004350 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4351 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4352 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4353
4354 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004355 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004356
4357 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004358 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004359
4360 // 64-76 are various 4-byte special-purpose registers:
4361 // 64: mq
4362 // 65: lr
4363 // 66: ctr
4364 // 67: ap
4365 // 68-75 cr0-7
4366 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004367 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004368
4369 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004370 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004371
4372 // 109: vrsave
4373 // 110: vscr
4374 // 111: spe_acc
4375 // 112: spefscr
4376 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004377 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004378
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004379 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004380}
4381
Roman Divackyd966e722012-05-09 18:22:46 +00004382// PowerPC-64
4383
4384namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004385/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004386class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004387public:
4388 enum ABIKind {
4389 ELFv1 = 0,
4390 ELFv2
4391 };
4392
4393private:
4394 static const unsigned GPRBits = 64;
4395 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004396 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004397 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004398
4399 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4400 // will be passed in a QPX register.
4401 bool IsQPXVectorTy(const Type *Ty) const {
4402 if (!HasQPX)
4403 return false;
4404
4405 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4406 unsigned NumElements = VT->getNumElements();
4407 if (NumElements == 1)
4408 return false;
4409
4410 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4411 if (getContext().getTypeSize(Ty) <= 256)
4412 return true;
4413 } else if (VT->getElementType()->
4414 isSpecificBuiltinType(BuiltinType::Float)) {
4415 if (getContext().getTypeSize(Ty) <= 128)
4416 return true;
4417 }
4418 }
4419
4420 return false;
4421 }
4422
4423 bool IsQPXVectorTy(QualType Ty) const {
4424 return IsQPXVectorTy(Ty.getTypePtr());
4425 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004426
4427public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004428 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4429 bool SoftFloatABI)
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004430 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
Hal Finkel415c2a32016-10-02 02:10:45 +00004431 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004432
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004433 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004434 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004435
4436 ABIArgInfo classifyReturnType(QualType RetTy) const;
4437 ABIArgInfo classifyArgumentType(QualType Ty) const;
4438
Reid Klecknere9f6a712014-10-31 17:10:41 +00004439 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4440 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4441 uint64_t Members) const override;
4442
Bill Schmidt84d37792012-10-12 19:26:17 +00004443 // TODO: We can add more logic to computeInfo to improve performance.
4444 // Example: For aggregate arguments that fit in a register, we could
4445 // use getDirectInReg (as is done below for structs containing a single
4446 // floating-point value) to avoid pushing them to memory on function
4447 // entry. This would require changing the logic in PPCISelLowering
4448 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004449 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004450 if (!getCXXABI().classifyReturnType(FI))
4451 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004452 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004453 // We rely on the default argument classification for the most part.
4454 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004455 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004456 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004457 if (T) {
4458 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004459 if (IsQPXVectorTy(T) ||
4460 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004461 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004462 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004463 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004464 continue;
4465 }
4466 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004467 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004468 }
4469 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004470
John McCall7f416cc2015-09-08 08:05:57 +00004471 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4472 QualType Ty) const override;
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004473
4474 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4475 bool asReturnValue) const override {
4476 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4477 }
4478
4479 bool isSwiftErrorInRegister() const override {
4480 return false;
4481 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004482};
4483
4484class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004485
Bill Schmidt25cb3492012-10-03 19:18:57 +00004486public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004487 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004488 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4489 bool SoftFloatABI)
4490 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4491 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004492
Craig Topper4f12f102014-03-12 06:41:41 +00004493 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004494 // This is recovered from gcc output.
4495 return 1; // r1 is the dedicated stack pointer
4496 }
4497
4498 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004499 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004500};
4501
Roman Divackyd966e722012-05-09 18:22:46 +00004502class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4503public:
4504 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4505
Craig Topper4f12f102014-03-12 06:41:41 +00004506 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004507 // This is recovered from gcc output.
4508 return 1; // r1 is the dedicated stack pointer
4509 }
4510
4511 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004512 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004513};
4514
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004515}
Roman Divackyd966e722012-05-09 18:22:46 +00004516
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004517// Return true if the ABI requires Ty to be passed sign- or zero-
4518// extended to 64 bits.
4519bool
4520PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4521 // Treat an enum type as its underlying type.
4522 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4523 Ty = EnumTy->getDecl()->getIntegerType();
4524
4525 // Promotable integer types are required to be promoted by the ABI.
4526 if (Ty->isPromotableIntegerType())
4527 return true;
4528
4529 // In addition to the usual promotable integer types, we also need to
4530 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4531 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4532 switch (BT->getKind()) {
4533 case BuiltinType::Int:
4534 case BuiltinType::UInt:
4535 return true;
4536 default:
4537 break;
4538 }
4539
4540 return false;
4541}
4542
John McCall7f416cc2015-09-08 08:05:57 +00004543/// isAlignedParamType - Determine whether a type requires 16-byte or
4544/// higher alignment in the parameter area. Always returns at least 8.
4545CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004546 // Complex types are passed just like their elements.
4547 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4548 Ty = CTy->getElementType();
4549
4550 // Only vector types of size 16 bytes need alignment (larger types are
4551 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004552 if (IsQPXVectorTy(Ty)) {
4553 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004554 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004555
John McCall7f416cc2015-09-08 08:05:57 +00004556 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004557 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004558 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004559 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004560
4561 // For single-element float/vector structs, we consider the whole type
4562 // to have the same alignment requirements as its single element.
4563 const Type *AlignAsType = nullptr;
4564 const Type *EltType = isSingleElementStruct(Ty, getContext());
4565 if (EltType) {
4566 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004567 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004568 getContext().getTypeSize(EltType) == 128) ||
4569 (BT && BT->isFloatingPoint()))
4570 AlignAsType = EltType;
4571 }
4572
Ulrich Weigandb7122372014-07-21 00:48:09 +00004573 // Likewise for ELFv2 homogeneous aggregates.
4574 const Type *Base = nullptr;
4575 uint64_t Members = 0;
4576 if (!AlignAsType && Kind == ELFv2 &&
4577 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4578 AlignAsType = Base;
4579
Ulrich Weigand581badc2014-07-10 17:20:07 +00004580 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004581 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4582 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004583 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004584
John McCall7f416cc2015-09-08 08:05:57 +00004585 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004586 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004587 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004588 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004589
4590 // Otherwise, we only need alignment for any aggregate type that
4591 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004592 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4593 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004594 return CharUnits::fromQuantity(32);
4595 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004596 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004597
John McCall7f416cc2015-09-08 08:05:57 +00004598 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004599}
4600
Ulrich Weigandb7122372014-07-21 00:48:09 +00004601/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4602/// aggregate. Base is set to the base element type, and Members is set
4603/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004604bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4605 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004606 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4607 uint64_t NElements = AT->getSize().getZExtValue();
4608 if (NElements == 0)
4609 return false;
4610 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4611 return false;
4612 Members *= NElements;
4613 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4614 const RecordDecl *RD = RT->getDecl();
4615 if (RD->hasFlexibleArrayMember())
4616 return false;
4617
4618 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004619
4620 // If this is a C++ record, check the bases first.
4621 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4622 for (const auto &I : CXXRD->bases()) {
4623 // Ignore empty records.
4624 if (isEmptyRecord(getContext(), I.getType(), true))
4625 continue;
4626
4627 uint64_t FldMembers;
4628 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4629 return false;
4630
4631 Members += FldMembers;
4632 }
4633 }
4634
Ulrich Weigandb7122372014-07-21 00:48:09 +00004635 for (const auto *FD : RD->fields()) {
4636 // Ignore (non-zero arrays of) empty records.
4637 QualType FT = FD->getType();
4638 while (const ConstantArrayType *AT =
4639 getContext().getAsConstantArrayType(FT)) {
4640 if (AT->getSize().getZExtValue() == 0)
4641 return false;
4642 FT = AT->getElementType();
4643 }
4644 if (isEmptyRecord(getContext(), FT, true))
4645 continue;
4646
4647 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4648 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00004649 FD->isZeroLengthBitField(getContext()))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004650 continue;
4651
4652 uint64_t FldMembers;
4653 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4654 return false;
4655
4656 Members = (RD->isUnion() ?
4657 std::max(Members, FldMembers) : Members + FldMembers);
4658 }
4659
4660 if (!Base)
4661 return false;
4662
4663 // Ensure there is no padding.
4664 if (getContext().getTypeSize(Base) * Members !=
4665 getContext().getTypeSize(Ty))
4666 return false;
4667 } else {
4668 Members = 1;
4669 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4670 Members = 2;
4671 Ty = CT->getElementType();
4672 }
4673
Reid Klecknere9f6a712014-10-31 17:10:41 +00004674 // Most ABIs only support float, double, and some vector type widths.
4675 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004676 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004677
4678 // The base type must be the same for all members. Types that
4679 // agree in both total size and mode (float vs. vector) are
4680 // treated as being equivalent here.
4681 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004682 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004683 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004684 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4685 // so make sure to widen it explicitly.
4686 if (const VectorType *VT = Base->getAs<VectorType>()) {
4687 QualType EltTy = VT->getElementType();
4688 unsigned NumElements =
4689 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4690 Base = getContext()
4691 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4692 .getTypePtr();
4693 }
4694 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004695
4696 if (Base->isVectorType() != TyPtr->isVectorType() ||
4697 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4698 return false;
4699 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004700 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4701}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004702
Reid Klecknere9f6a712014-10-31 17:10:41 +00004703bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4704 // Homogeneous aggregates for ELFv2 must have base types of float,
4705 // double, long double, or 128-bit vectors.
4706 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4707 if (BT->getKind() == BuiltinType::Float ||
4708 BT->getKind() == BuiltinType::Double ||
Lei Huang449252d2018-07-05 04:32:01 +00004709 BT->getKind() == BuiltinType::LongDouble ||
4710 (getContext().getTargetInfo().hasFloat128Type() &&
4711 (BT->getKind() == BuiltinType::Float128))) {
Hal Finkel415c2a32016-10-02 02:10:45 +00004712 if (IsSoftFloatABI)
4713 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004714 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004715 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004716 }
4717 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004718 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004719 return true;
4720 }
4721 return false;
4722}
4723
4724bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4725 const Type *Base, uint64_t Members) const {
Lei Huang449252d2018-07-05 04:32:01 +00004726 // Vector and fp128 types require one register, other floating point types
4727 // require one or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004728 uint32_t NumRegs =
Lei Huang449252d2018-07-05 04:32:01 +00004729 ((getContext().getTargetInfo().hasFloat128Type() &&
4730 Base->isFloat128Type()) ||
4731 Base->isVectorType()) ? 1
4732 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004733
4734 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004735 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004736}
4737
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004738ABIArgInfo
4739PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004740 Ty = useFirstFieldIfTransparentUnion(Ty);
4741
Bill Schmidt90b22c92012-11-27 02:46:43 +00004742 if (Ty->isAnyComplexType())
4743 return ABIArgInfo::getDirect();
4744
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004745 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4746 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004747 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004748 uint64_t Size = getContext().getTypeSize(Ty);
4749 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004750 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004751 else if (Size < 128) {
4752 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4753 return ABIArgInfo::getDirect(CoerceTy);
4754 }
4755 }
4756
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004757 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004758 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004759 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004760
John McCall7f416cc2015-09-08 08:05:57 +00004761 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4762 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004763
4764 // ELFv2 homogeneous aggregates are passed as array types.
4765 const Type *Base = nullptr;
4766 uint64_t Members = 0;
4767 if (Kind == ELFv2 &&
4768 isHomogeneousAggregate(Ty, Base, Members)) {
4769 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4770 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4771 return ABIArgInfo::getDirect(CoerceTy);
4772 }
4773
Ulrich Weigand601957f2014-07-21 00:56:36 +00004774 // If an aggregate may end up fully in registers, we do not
4775 // use the ByVal method, but pass the aggregate as array.
4776 // This is usually beneficial since we avoid forcing the
4777 // back-end to store the argument to memory.
4778 uint64_t Bits = getContext().getTypeSize(Ty);
4779 if (Bits > 0 && Bits <= 8 * GPRBits) {
4780 llvm::Type *CoerceTy;
4781
4782 // Types up to 8 bytes are passed as integer type (which will be
4783 // properly aligned in the argument save area doubleword).
4784 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004785 CoerceTy =
4786 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004787 // Larger types are passed as arrays, with the base type selected
4788 // according to the required alignment in the save area.
4789 else {
4790 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004791 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004792 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4793 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4794 }
4795
4796 return ABIArgInfo::getDirect(CoerceTy);
4797 }
4798
Ulrich Weigandb7122372014-07-21 00:48:09 +00004799 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004800 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4801 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004802 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004803 }
4804
Alex Bradburye41a5e22018-01-12 20:08:16 +00004805 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4806 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004807}
4808
4809ABIArgInfo
4810PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4811 if (RetTy->isVoidType())
4812 return ABIArgInfo::getIgnore();
4813
Bill Schmidta3d121c2012-12-17 04:20:17 +00004814 if (RetTy->isAnyComplexType())
4815 return ABIArgInfo::getDirect();
4816
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004817 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4818 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004819 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004820 uint64_t Size = getContext().getTypeSize(RetTy);
4821 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004822 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004823 else if (Size < 128) {
4824 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4825 return ABIArgInfo::getDirect(CoerceTy);
4826 }
4827 }
4828
Ulrich Weigandb7122372014-07-21 00:48:09 +00004829 if (isAggregateTypeForABI(RetTy)) {
4830 // ELFv2 homogeneous aggregates are returned as array types.
4831 const Type *Base = nullptr;
4832 uint64_t Members = 0;
4833 if (Kind == ELFv2 &&
4834 isHomogeneousAggregate(RetTy, Base, Members)) {
4835 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4836 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4837 return ABIArgInfo::getDirect(CoerceTy);
4838 }
4839
4840 // ELFv2 small aggregates are returned in up to two registers.
4841 uint64_t Bits = getContext().getTypeSize(RetTy);
4842 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4843 if (Bits == 0)
4844 return ABIArgInfo::getIgnore();
4845
4846 llvm::Type *CoerceTy;
4847 if (Bits > GPRBits) {
4848 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004849 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004850 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004851 CoerceTy =
4852 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004853 return ABIArgInfo::getDirect(CoerceTy);
4854 }
4855
4856 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004857 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004858 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004859
Alex Bradburye41a5e22018-01-12 20:08:16 +00004860 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4861 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004862}
4863
Bill Schmidt25cb3492012-10-03 19:18:57 +00004864// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004865Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4866 QualType Ty) const {
4867 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4868 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004869
John McCall7f416cc2015-09-08 08:05:57 +00004870 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004871
Bill Schmidt924c4782013-01-14 17:45:36 +00004872 // If we have a complex type and the base type is smaller than 8 bytes,
4873 // the ABI calls for the real and imaginary parts to be right-adjusted
4874 // in separate doublewords. However, Clang expects us to produce a
4875 // pointer to a structure with the two parts packed tightly. So generate
4876 // loads of the real and imaginary parts relative to the va_list pointer,
4877 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004878 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4879 CharUnits EltSize = TypeInfo.first / 2;
4880 if (EltSize < SlotSize) {
4881 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4882 SlotSize * 2, SlotSize,
4883 SlotSize, /*AllowHigher*/ true);
4884
4885 Address RealAddr = Addr;
4886 Address ImagAddr = RealAddr;
4887 if (CGF.CGM.getDataLayout().isBigEndian()) {
4888 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4889 SlotSize - EltSize);
4890 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4891 2 * SlotSize - EltSize);
4892 } else {
4893 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4894 }
4895
4896 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4897 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4898 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4899 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4900 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4901
4902 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4903 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4904 /*init*/ true);
4905 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004906 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004907 }
4908
John McCall7f416cc2015-09-08 08:05:57 +00004909 // Otherwise, just use the general rule.
4910 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4911 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004912}
4913
4914static bool
4915PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4916 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004917 // This is calculated from the LLVM and GCC tables and verified
4918 // against gcc output. AFAIK all ABIs use the same encoding.
4919
4920 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4921
4922 llvm::IntegerType *i8 = CGF.Int8Ty;
4923 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4924 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4925 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4926
4927 // 0-31: r0-31, the 8-byte general-purpose registers
4928 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4929
4930 // 32-63: fp0-31, the 8-byte floating-point registers
4931 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4932
Hal Finkel84832a72016-08-30 02:38:34 +00004933 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004934 // 64: mq
4935 // 65: lr
4936 // 66: ctr
4937 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004938 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4939
4940 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004941 // 68-75 cr0-7
4942 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004943 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004944
4945 // 77-108: v0-31, the 16-byte vector registers
4946 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4947
4948 // 109: vrsave
4949 // 110: vscr
4950 // 111: spe_acc
4951 // 112: spefscr
4952 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004953 // 114: tfhar
4954 // 115: tfiar
4955 // 116: texasr
4956 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004957
4958 return false;
4959}
John McCallea8d8bb2010-03-11 00:10:12 +00004960
Bill Schmidt25cb3492012-10-03 19:18:57 +00004961bool
4962PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4963 CodeGen::CodeGenFunction &CGF,
4964 llvm::Value *Address) const {
4965
4966 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4967}
4968
4969bool
4970PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4971 llvm::Value *Address) const {
4972
4973 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4974}
4975
Chris Lattner0cf24192010-06-28 20:05:43 +00004976//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004977// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004978//===----------------------------------------------------------------------===//
4979
4980namespace {
4981
John McCall12f23522016-04-04 18:33:08 +00004982class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004983public:
4984 enum ABIKind {
4985 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004986 DarwinPCS,
4987 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004988 };
4989
4990private:
4991 ABIKind Kind;
4992
4993public:
John McCall12f23522016-04-04 18:33:08 +00004994 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4995 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004996
4997private:
4998 ABIKind getABIKind() const { return Kind; }
4999 bool isDarwinPCS() const { return Kind == DarwinPCS; }
5000
Tim Northover44e58792018-09-18 10:34:39 +01005001 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00005002 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005003 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5004 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5005 uint64_t Members) const override;
5006
Tim Northovera2ee4332014-03-29 15:09:45 +00005007 bool isIllegalVectorType(QualType Ty) const;
5008
David Blaikie1cbb9712014-11-14 19:09:44 +00005009 void computeInfo(CGFunctionInfo &FI) const override {
Akira Hatanakad791e922018-03-19 17:38:40 +00005010 if (!::classifyReturnType(getCXXABI(), FI, *this))
Tim Northover44e58792018-09-18 10:34:39 +01005011 FI.getReturnInfo() =
5012 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Tim Northover5ffc0922014-04-17 10:20:38 +00005013
Tim Northoverb047bfa2014-11-27 21:02:49 +00005014 for (auto &it : FI.arguments())
5015 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00005016 }
5017
John McCall7f416cc2015-09-08 08:05:57 +00005018 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5019 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00005020
John McCall7f416cc2015-09-08 08:05:57 +00005021 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5022 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00005023
John McCall7f416cc2015-09-08 08:05:57 +00005024 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5025 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00005026 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5027 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5028 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00005029 }
John McCall12f23522016-04-04 18:33:08 +00005030
Martin Storsjo502de222017-07-13 17:59:14 +00005031 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5032 QualType Ty) const override;
5033
John McCall56331e22018-01-07 06:28:49 +00005034 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005035 bool asReturnValue) const override {
5036 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5037 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005038 bool isSwiftErrorInRegister() const override {
5039 return true;
5040 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005041
5042 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5043 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00005044};
5045
Tim Northover573cbee2014-05-24 12:52:07 +00005046class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00005047public:
Tim Northover573cbee2014-05-24 12:52:07 +00005048 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5049 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00005050
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005051 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005052 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00005053 }
5054
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005055 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5056 return 31;
5057 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005058
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005059 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005060
5061 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5062 CodeGen::CodeGenModule &CGM) const override {
5063 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5064 if (!FD)
5065 return;
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005066
Momchil Velikovaa6d48f2019-11-15 11:34:47 +00005067 CodeGenOptions::SignReturnAddressScope Scope = CGM.getCodeGenOpts().getSignReturnAddress();
5068 CodeGenOptions::SignReturnAddressKeyValue Key = CGM.getCodeGenOpts().getSignReturnAddressKey();
5069 bool BranchTargetEnforcement = CGM.getCodeGenOpts().BranchTargetEnforcement;
5070 if (const auto *TA = FD->getAttr<TargetAttr>()) {
Craig Topper505aa242019-12-09 10:34:24 -08005071 ParsedTargetAttr Attr = TA->parse();
Momchil Velikovaa6d48f2019-11-15 11:34:47 +00005072 if (!Attr.BranchProtection.empty()) {
5073 TargetInfo::BranchProtectionInfo BPI;
5074 StringRef Error;
5075 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5076 BPI, Error);
5077 assert(Error.empty());
5078 Scope = BPI.SignReturnAddr;
5079 Key = BPI.SignKey;
5080 BranchTargetEnforcement = BPI.BranchTargetEnforcement;
5081 }
5082 }
5083
5084 auto *Fn = cast<llvm::Function>(GV);
5085 if (Scope != CodeGenOptions::SignReturnAddressScope::None) {
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005086 Fn->addFnAttr("sign-return-address",
Momchil Velikovaa6d48f2019-11-15 11:34:47 +00005087 Scope == CodeGenOptions::SignReturnAddressScope::All
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005088 ? "all"
5089 : "non-leaf");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005090
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005091 Fn->addFnAttr("sign-return-address-key",
5092 Key == CodeGenOptions::SignReturnAddressKeyValue::AKey
5093 ? "a_key"
5094 : "b_key");
5095 }
5096
Momchil Velikovaa6d48f2019-11-15 11:34:47 +00005097 if (BranchTargetEnforcement)
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005098 Fn->addFnAttr("branch-target-enforcement");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005099 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005100};
Martin Storsjo1c8af272017-07-20 05:47:06 +00005101
5102class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5103public:
5104 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5105 : AArch64TargetCodeGenInfo(CGT, K) {}
5106
Eli Friedman540be6d2018-10-26 01:31:57 +00005107 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5108 CodeGen::CodeGenModule &CGM) const override;
5109
Martin Storsjo1c8af272017-07-20 05:47:06 +00005110 void getDependentLibraryOption(llvm::StringRef Lib,
5111 llvm::SmallString<24> &Opt) const override {
5112 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5113 }
5114
5115 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5116 llvm::SmallString<32> &Opt) const override {
5117 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5118 }
5119};
Eli Friedman540be6d2018-10-26 01:31:57 +00005120
5121void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5122 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5123 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5124 if (GV->isDeclaration())
5125 return;
5126 addStackProbeTargetAttributes(D, GV, CGM);
5127}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005128}
Tim Northovera2ee4332014-03-29 15:09:45 +00005129
Tim Northoverb047bfa2014-11-27 21:02:49 +00005130ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00005131 Ty = useFirstFieldIfTransparentUnion(Ty);
5132
Tim Northovera2ee4332014-03-29 15:09:45 +00005133 // Handle illegal vector types here.
5134 if (isIllegalVectorType(Ty)) {
5135 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005136 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00005137 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005138 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5139 return ABIArgInfo::getDirect(ResType);
5140 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005141 if (Size <= 32) {
5142 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00005143 return ABIArgInfo::getDirect(ResType);
5144 }
5145 if (Size == 64) {
5146 llvm::Type *ResType =
5147 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00005148 return ABIArgInfo::getDirect(ResType);
5149 }
5150 if (Size == 128) {
5151 llvm::Type *ResType =
5152 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00005153 return ABIArgInfo::getDirect(ResType);
5154 }
John McCall7f416cc2015-09-08 08:05:57 +00005155 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005156 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005157
5158 if (!isAggregateTypeForABI(Ty)) {
5159 // Treat an enum type as its underlying type.
5160 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5161 Ty = EnumTy->getDecl()->getIntegerType();
5162
Tim Northovera2ee4332014-03-29 15:09:45 +00005163 return (Ty->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005164 ? ABIArgInfo::getExtend(Ty)
Tim Northovera2ee4332014-03-29 15:09:45 +00005165 : ABIArgInfo::getDirect());
5166 }
5167
5168 // Structures with either a non-trivial destructor or a non-trivial
5169 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00005170 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005171 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5172 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00005173 }
5174
5175 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5176 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00005177 uint64_t Size = getContext().getTypeSize(Ty);
5178 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5179 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005180 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5181 return ABIArgInfo::getIgnore();
5182
Tim Northover23bcad22017-05-05 22:36:06 +00005183 // GNU C mode. The only argument that gets ignored is an empty one with size
5184 // 0.
5185 if (IsEmpty && Size == 0)
5186 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00005187 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5188 }
5189
5190 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005191 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005192 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005193 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005194 return ABIArgInfo::getDirect(
5195 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005196 }
5197
5198 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005199 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005200 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5201 // same size and alignment.
5202 if (getTarget().isRenderScriptTarget()) {
5203 return coerceToIntArray(Ty, getContext(), getVMContext());
5204 }
Momchil Velikov20208cc2018-07-30 17:48:23 +00005205 unsigned Alignment;
5206 if (Kind == AArch64ABIInfo::AAPCS) {
5207 Alignment = getContext().getTypeUnadjustedAlign(Ty);
5208 Alignment = Alignment < 128 ? 64 : 128;
5209 } else {
Tim Northover44e58792018-09-18 10:34:39 +01005210 Alignment = std::max(getContext().getTypeAlign(Ty),
5211 (unsigned)getTarget().getPointerWidth(0));
Momchil Velikov20208cc2018-07-30 17:48:23 +00005212 }
Tim Northover44e58792018-09-18 10:34:39 +01005213 Size = llvm::alignTo(Size, Alignment);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005214
Tim Northovera2ee4332014-03-29 15:09:45 +00005215 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5216 // For aggregates with 16-byte alignment, we use i128.
Tim Northover44e58792018-09-18 10:34:39 +01005217 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5218 return ABIArgInfo::getDirect(
5219 Size == Alignment ? BaseTy
5220 : llvm::ArrayType::get(BaseTy, Size / Alignment));
Tim Northovera2ee4332014-03-29 15:09:45 +00005221 }
5222
John McCall7f416cc2015-09-08 08:05:57 +00005223 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005224}
5225
Tim Northover44e58792018-09-18 10:34:39 +01005226ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5227 bool IsVariadic) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005228 if (RetTy->isVoidType())
5229 return ABIArgInfo::getIgnore();
5230
5231 // Large vector types should be returned via memory.
5232 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005233 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005234
5235 if (!isAggregateTypeForABI(RetTy)) {
5236 // Treat an enum type as its underlying type.
5237 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5238 RetTy = EnumTy->getDecl()->getIntegerType();
5239
Tim Northover4dab6982014-04-18 13:46:08 +00005240 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005241 ? ABIArgInfo::getExtend(RetTy)
Tim Northover4dab6982014-04-18 13:46:08 +00005242 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005243 }
5244
Tim Northover23bcad22017-05-05 22:36:06 +00005245 uint64_t Size = getContext().getTypeSize(RetTy);
5246 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005247 return ABIArgInfo::getIgnore();
5248
Craig Topper8a13c412014-05-21 05:09:00 +00005249 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005250 uint64_t Members = 0;
Tim Northover44e58792018-09-18 10:34:39 +01005251 if (isHomogeneousAggregate(RetTy, Base, Members) &&
5252 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5253 IsVariadic))
Tim Northovera2ee4332014-03-29 15:09:45 +00005254 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5255 return ABIArgInfo::getDirect();
5256
5257 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005258 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005259 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5260 // same size and alignment.
5261 if (getTarget().isRenderScriptTarget()) {
5262 return coerceToIntArray(RetTy, getContext(), getVMContext());
5263 }
Pete Cooper635b5092015-04-17 22:16:24 +00005264 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005265 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005266
5267 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5268 // For aggregates with 16-byte alignment, we use i128.
5269 if (Alignment < 128 && Size == 128) {
5270 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5271 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5272 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005273 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5274 }
5275
John McCall7f416cc2015-09-08 08:05:57 +00005276 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005277}
5278
Tim Northover573cbee2014-05-24 12:52:07 +00005279/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5280bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005281 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5282 // Check whether VT is legal.
5283 unsigned NumElements = VT->getNumElements();
5284 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005285 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005286 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005287 return true;
Tim Northover44e58792018-09-18 10:34:39 +01005288
5289 // arm64_32 has to be compatible with the ARM logic here, which allows huge
5290 // vectors for some reason.
5291 llvm::Triple Triple = getTarget().getTriple();
5292 if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5293 Triple.isOSBinFormatMachO())
5294 return Size <= 32;
5295
Tim Northovera2ee4332014-03-29 15:09:45 +00005296 return Size != 64 && (Size != 128 || NumElements == 1);
5297 }
5298 return false;
5299}
5300
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005301bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5302 llvm::Type *eltTy,
5303 unsigned elts) const {
5304 if (!llvm::isPowerOf2_32(elts))
5305 return false;
5306 if (totalSize.getQuantity() != 8 &&
5307 (totalSize.getQuantity() != 16 || elts == 1))
5308 return false;
5309 return true;
5310}
5311
Reid Klecknere9f6a712014-10-31 17:10:41 +00005312bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5313 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5314 // point type or a short-vector type. This is the same as the 32-bit ABI,
5315 // but with the difference that any floating-point type is allowed,
5316 // including __fp16.
5317 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5318 if (BT->isFloatingPoint())
5319 return true;
5320 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5321 unsigned VecSize = getContext().getTypeSize(VT);
5322 if (VecSize == 64 || VecSize == 128)
5323 return true;
5324 }
5325 return false;
5326}
5327
5328bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5329 uint64_t Members) const {
5330 return Members <= 4;
5331}
5332
John McCall7f416cc2015-09-08 08:05:57 +00005333Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005334 QualType Ty,
5335 CodeGenFunction &CGF) const {
5336 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005337 bool IsIndirect = AI.isIndirect();
5338
Tim Northoverb047bfa2014-11-27 21:02:49 +00005339 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5340 if (IsIndirect)
5341 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5342 else if (AI.getCoerceToType())
5343 BaseTy = AI.getCoerceToType();
5344
5345 unsigned NumRegs = 1;
5346 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5347 BaseTy = ArrTy->getElementType();
5348 NumRegs = ArrTy->getNumElements();
5349 }
5350 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5351
Tim Northovera2ee4332014-03-29 15:09:45 +00005352 // The AArch64 va_list type and handling is specified in the Procedure Call
5353 // Standard, section B.4:
5354 //
5355 // struct {
5356 // void *__stack;
5357 // void *__gr_top;
5358 // void *__vr_top;
5359 // int __gr_offs;
5360 // int __vr_offs;
5361 // };
5362
5363 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5364 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5365 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5366 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005367
John Brawn6c49f582019-05-22 11:42:54 +00005368 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5369 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005370
5371 Address reg_offs_p = Address::invalid();
5372 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005373 int reg_top_index;
John Brawn6c49f582019-05-22 11:42:54 +00005374 int RegSize = IsIndirect ? 8 : TySize.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005375 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005376 // 3 is the field number of __gr_offs
James Y Knight751fe282019-02-09 22:22:28 +00005377 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005378 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5379 reg_top_index = 1; // field number for __gr_top
Rui Ueyama83aa9792016-01-14 21:00:27 +00005380 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005381 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005382 // 4 is the field number of __vr_offs.
James Y Knight751fe282019-02-09 22:22:28 +00005383 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005384 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5385 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00005386 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005387 }
5388
5389 //=======================================
5390 // Find out where argument was passed
5391 //=======================================
5392
5393 // If reg_offs >= 0 we're already using the stack for this type of
5394 // argument. We don't want to keep updating reg_offs (in case it overflows,
5395 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5396 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005397 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005398 UsingStack = CGF.Builder.CreateICmpSGE(
5399 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5400
5401 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5402
5403 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005404 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005405 CGF.EmitBlock(MaybeRegBlock);
5406
5407 // Integer arguments may need to correct register alignment (for example a
5408 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5409 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005410 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5411 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005412
5413 reg_offs = CGF.Builder.CreateAdd(
5414 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5415 "align_regoffs");
5416 reg_offs = CGF.Builder.CreateAnd(
5417 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5418 "aligned_regoffs");
5419 }
5420
5421 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005422 // The fact that this is done unconditionally reflects the fact that
5423 // allocating an argument to the stack also uses up all the remaining
5424 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005425 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005426 NewOffset = CGF.Builder.CreateAdd(
5427 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5428 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5429
5430 // Now we're in a position to decide whether this argument really was in
5431 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005432 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005433 InRegs = CGF.Builder.CreateICmpSLE(
5434 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5435
5436 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5437
5438 //=======================================
5439 // Argument was in registers
5440 //=======================================
5441
5442 // Now we emit the code for if the argument was originally passed in
5443 // registers. First start the appropriate block:
5444 CGF.EmitBlock(InRegBlock);
5445
John McCall7f416cc2015-09-08 08:05:57 +00005446 llvm::Value *reg_top = nullptr;
James Y Knight751fe282019-02-09 22:22:28 +00005447 Address reg_top_p =
5448 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005449 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005450 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5451 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5452 Address RegAddr = Address::invalid();
5453 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005454
5455 if (IsIndirect) {
5456 // If it's been passed indirectly (actually a struct), whatever we find from
5457 // stored registers or on the stack will actually be a struct **.
5458 MemTy = llvm::PointerType::getUnqual(MemTy);
5459 }
5460
Craig Topper8a13c412014-05-21 05:09:00 +00005461 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005462 uint64_t NumMembers = 0;
5463 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005464 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005465 // Homogeneous aggregates passed in registers will have their elements split
5466 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5467 // qN+1, ...). We reload and store into a temporary local variable
5468 // contiguously.
5469 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005470 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005471 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5472 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005473 Address Tmp = CGF.CreateTempAlloca(HFATy,
5474 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005475
John McCall7f416cc2015-09-08 08:05:57 +00005476 // On big-endian platforms, the value will be right-aligned in its slot.
5477 int Offset = 0;
5478 if (CGF.CGM.getDataLayout().isBigEndian() &&
5479 BaseTyInfo.first.getQuantity() < 16)
5480 Offset = 16 - BaseTyInfo.first.getQuantity();
5481
Tim Northovera2ee4332014-03-29 15:09:45 +00005482 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005483 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5484 Address LoadAddr =
5485 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5486 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5487
James Y Knight751fe282019-02-09 22:22:28 +00005488 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00005489
5490 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5491 CGF.Builder.CreateStore(Elem, StoreAddr);
5492 }
5493
John McCall7f416cc2015-09-08 08:05:57 +00005494 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005495 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005496 // Otherwise the object is contiguous in memory.
5497
5498 // It might be right-aligned in its slot.
5499 CharUnits SlotSize = BaseAddr.getAlignment();
5500 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005501 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John Brawn6c49f582019-05-22 11:42:54 +00005502 TySize < SlotSize) {
5503 CharUnits Offset = SlotSize - TySize;
John McCall7f416cc2015-09-08 08:05:57 +00005504 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005505 }
5506
John McCall7f416cc2015-09-08 08:05:57 +00005507 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005508 }
5509
5510 CGF.EmitBranch(ContBlock);
5511
5512 //=======================================
5513 // Argument was on the stack
5514 //=======================================
5515 CGF.EmitBlock(OnStackBlock);
5516
James Y Knight751fe282019-02-09 22:22:28 +00005517 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
John McCall7f416cc2015-09-08 08:05:57 +00005518 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005519
John McCall7f416cc2015-09-08 08:05:57 +00005520 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005521 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005522 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5523 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005524
John McCall7f416cc2015-09-08 08:05:57 +00005525 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005526
John McCall7f416cc2015-09-08 08:05:57 +00005527 OnStackPtr = CGF.Builder.CreateAdd(
5528 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005529 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005530 OnStackPtr = CGF.Builder.CreateAnd(
5531 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005532 "align_stack");
5533
John McCall7f416cc2015-09-08 08:05:57 +00005534 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005535 }
John McCall7f416cc2015-09-08 08:05:57 +00005536 Address OnStackAddr(OnStackPtr,
5537 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005538
John McCall7f416cc2015-09-08 08:05:57 +00005539 // All stack slots are multiples of 8 bytes.
5540 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5541 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005542 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005543 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005544 else
John Brawn6c49f582019-05-22 11:42:54 +00005545 StackSize = TySize.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005546
John McCall7f416cc2015-09-08 08:05:57 +00005547 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005548 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005549 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005550
5551 // Write the new value of __stack for the next call to va_arg
5552 CGF.Builder.CreateStore(NewStack, stack_p);
5553
5554 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John Brawn6c49f582019-05-22 11:42:54 +00005555 TySize < StackSlotSize) {
5556 CharUnits Offset = StackSlotSize - TySize;
John McCall7f416cc2015-09-08 08:05:57 +00005557 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005558 }
5559
John McCall7f416cc2015-09-08 08:05:57 +00005560 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005561
5562 CGF.EmitBranch(ContBlock);
5563
5564 //=======================================
5565 // Tidy up
5566 //=======================================
5567 CGF.EmitBlock(ContBlock);
5568
John McCall7f416cc2015-09-08 08:05:57 +00005569 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5570 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005571
5572 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005573 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
John Brawn6c49f582019-05-22 11:42:54 +00005574 TyAlign);
Tim Northovera2ee4332014-03-29 15:09:45 +00005575
5576 return ResAddr;
5577}
5578
John McCall7f416cc2015-09-08 08:05:57 +00005579Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5580 CodeGenFunction &CGF) const {
5581 // The backend's lowering doesn't support va_arg for aggregates or
5582 // illegal vector types. Lower VAArg here for these cases and use
5583 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005584 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005585 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005586
Tim Northover44e58792018-09-18 10:34:39 +01005587 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
5588 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005589
John McCall7f416cc2015-09-08 08:05:57 +00005590 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005591 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005592 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5593 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5594 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005595 }
5596
John McCall7f416cc2015-09-08 08:05:57 +00005597 // The size of the actual thing passed, which might end up just
5598 // being a pointer for indirect types.
5599 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5600
5601 // Arguments bigger than 16 bytes which aren't homogeneous
5602 // aggregates should be passed indirectly.
5603 bool IsIndirect = false;
5604 if (TyInfo.first.getQuantity() > 16) {
5605 const Type *Base = nullptr;
5606 uint64_t Members = 0;
5607 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005608 }
5609
John McCall7f416cc2015-09-08 08:05:57 +00005610 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5611 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005612}
5613
Martin Storsjo502de222017-07-13 17:59:14 +00005614Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5615 QualType Ty) const {
5616 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5617 CGF.getContext().getTypeInfoInChars(Ty),
5618 CharUnits::fromQuantity(8),
5619 /*allowHigherAlign*/ false);
5620}
5621
Tim Northovera2ee4332014-03-29 15:09:45 +00005622//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005623// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005624//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005625
5626namespace {
5627
John McCall12f23522016-04-04 18:33:08 +00005628class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005629public:
5630 enum ABIKind {
5631 APCS = 0,
5632 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005633 AAPCS_VFP = 2,
5634 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005635 };
5636
5637private:
5638 ABIKind Kind;
5639
5640public:
John McCall12f23522016-04-04 18:33:08 +00005641 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5642 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005643 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005644 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005645
John McCall3480ef22011-08-30 01:42:09 +00005646 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005647 switch (getTarget().getTriple().getEnvironment()) {
5648 case llvm::Triple::Android:
5649 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005650 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005651 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005652 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005653 case llvm::Triple::MuslEABI:
5654 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005655 return true;
5656 default:
5657 return false;
5658 }
John McCall3480ef22011-08-30 01:42:09 +00005659 }
5660
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005661 bool isEABIHF() const {
5662 switch (getTarget().getTriple().getEnvironment()) {
5663 case llvm::Triple::EABIHF:
5664 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005665 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005666 return true;
5667 default:
5668 return false;
5669 }
5670 }
5671
Daniel Dunbar020daa92009-09-12 01:00:39 +00005672 ABIKind getABIKind() const { return Kind; }
5673
Tim Northovera484bc02013-10-01 14:34:25 +00005674private:
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005675 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
5676 unsigned functionCallConv) const;
5677 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
5678 unsigned functionCallConv) const;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005679 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
5680 uint64_t Members) const;
5681 ABIArgInfo coerceIllegalVector(QualType Ty) const;
Manman Renfef9e312012-10-16 19:18:39 +00005682 bool isIllegalVectorType(QualType Ty) const;
Mikhail Maltseva45292c2019-06-18 14:34:27 +00005683 bool containsAnyFP16Vectors(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005684
Reid Klecknere9f6a712014-10-31 17:10:41 +00005685 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5686 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5687 uint64_t Members) const override;
5688
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005689 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
5690
Craig Topper4f12f102014-03-12 06:41:41 +00005691 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005692
John McCall7f416cc2015-09-08 08:05:57 +00005693 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5694 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005695
5696 llvm::CallingConv::ID getLLVMDefaultCC() const;
5697 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005698 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005699
John McCall56331e22018-01-07 06:28:49 +00005700 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005701 bool asReturnValue) const override {
5702 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5703 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005704 bool isSwiftErrorInRegister() const override {
5705 return true;
5706 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005707 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5708 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005709};
5710
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005711class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5712public:
Chris Lattner2b037972010-07-29 02:01:43 +00005713 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5714 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005715
John McCall3480ef22011-08-30 01:42:09 +00005716 const ARMABIInfo &getABIInfo() const {
5717 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5718 }
5719
Craig Topper4f12f102014-03-12 06:41:41 +00005720 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005721 return 13;
5722 }
Roman Divackyc1617352011-05-18 19:36:54 +00005723
Craig Topper4f12f102014-03-12 06:41:41 +00005724 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005725 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005726 }
5727
Roman Divackyc1617352011-05-18 19:36:54 +00005728 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005729 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005730 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005731
5732 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005733 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005734 return false;
5735 }
John McCall3480ef22011-08-30 01:42:09 +00005736
Craig Topper4f12f102014-03-12 06:41:41 +00005737 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005738 if (getABIInfo().isEABI()) return 88;
5739 return TargetCodeGenInfo::getSizeOfUnwindException();
5740 }
Tim Northovera484bc02013-10-01 14:34:25 +00005741
Eric Christopher162c91c2015-06-05 22:03:00 +00005742 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005743 CodeGen::CodeGenModule &CGM) const override {
5744 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005745 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005746 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005747 if (!FD)
5748 return;
5749
5750 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5751 if (!Attr)
5752 return;
5753
5754 const char *Kind;
5755 switch (Attr->getInterrupt()) {
5756 case ARMInterruptAttr::Generic: Kind = ""; break;
5757 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5758 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5759 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5760 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5761 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5762 }
5763
5764 llvm::Function *Fn = cast<llvm::Function>(GV);
5765
5766 Fn->addFnAttr("interrupt", Kind);
5767
Tim Northover5627d392015-10-30 16:30:45 +00005768 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5769 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005770 return;
5771
5772 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5773 // however this is not necessarily true on taking any interrupt. Instruct
5774 // the backend to perform a realignment as part of the function prologue.
5775 llvm::AttrBuilder B;
5776 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005777 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005778 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005779};
5780
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005781class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005782public:
5783 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5784 : ARMTargetCodeGenInfo(CGT, K) {}
5785
Eric Christopher162c91c2015-06-05 22:03:00 +00005786 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005787 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005788
5789 void getDependentLibraryOption(llvm::StringRef Lib,
5790 llvm::SmallString<24> &Opt) const override {
5791 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5792 }
5793
5794 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5795 llvm::SmallString<32> &Opt) const override {
5796 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5797 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005798};
5799
Eric Christopher162c91c2015-06-05 22:03:00 +00005800void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005801 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5802 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5803 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005804 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00005805 addStackProbeTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005806}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005807}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005808
Chris Lattner22326a12010-07-29 02:31:05 +00005809void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakad791e922018-03-19 17:38:40 +00005810 if (!::classifyReturnType(getCXXABI(), FI, *this))
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005811 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
5812 FI.getCallingConvention());
Oliver Stannard405bded2014-02-11 09:25:50 +00005813
Tim Northoverbc784d12015-02-24 17:22:40 +00005814 for (auto &I : FI.arguments())
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005815 I.info = classifyArgumentType(I.type, FI.isVariadic(),
5816 FI.getCallingConvention());
5817
Daniel Dunbar020daa92009-09-12 01:00:39 +00005818
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005819 // Always honor user-specified calling convention.
5820 if (FI.getCallingConvention() != llvm::CallingConv::C)
5821 return;
5822
John McCall882987f2013-02-28 19:01:20 +00005823 llvm::CallingConv::ID cc = getRuntimeCC();
5824 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005825 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005826}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005827
John McCall882987f2013-02-28 19:01:20 +00005828/// Return the default calling convention that LLVM will use.
5829llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5830 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005831 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005832 return llvm::CallingConv::ARM_AAPCS_VFP;
5833 else if (isEABI())
5834 return llvm::CallingConv::ARM_AAPCS;
5835 else
5836 return llvm::CallingConv::ARM_APCS;
5837}
5838
5839/// Return the calling convention that our ABI would like us to use
5840/// as the C calling convention.
5841llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005842 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005843 case APCS: return llvm::CallingConv::ARM_APCS;
5844 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5845 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005846 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005847 }
John McCall882987f2013-02-28 19:01:20 +00005848 llvm_unreachable("bad ABI kind");
5849}
5850
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005851void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005852 assert(getRuntimeCC() == llvm::CallingConv::C);
5853
5854 // Don't muddy up the IR with a ton of explicit annotations if
5855 // they'd just match what LLVM will infer from the triple.
5856 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5857 if (abiCC != getLLVMDefaultCC())
5858 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005859}
5860
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005861ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
5862 uint64_t Size = getContext().getTypeSize(Ty);
5863 if (Size <= 32) {
5864 llvm::Type *ResType =
5865 llvm::Type::getInt32Ty(getVMContext());
5866 return ABIArgInfo::getDirect(ResType);
5867 }
5868 if (Size == 64 || Size == 128) {
5869 llvm::Type *ResType = llvm::VectorType::get(
5870 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5871 return ABIArgInfo::getDirect(ResType);
5872 }
5873 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5874}
5875
5876ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
5877 const Type *Base,
5878 uint64_t Members) const {
5879 assert(Base && "Base class should be set for homogeneous aggregate");
5880 // Base can be a floating-point or a vector.
5881 if (const VectorType *VT = Base->getAs<VectorType>()) {
5882 // FP16 vectors should be converted to integer vectors
Mikhail Maltseva45292c2019-06-18 14:34:27 +00005883 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005884 uint64_t Size = getContext().getTypeSize(VT);
5885 llvm::Type *NewVecTy = llvm::VectorType::get(
5886 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5887 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
5888 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5889 }
5890 }
5891 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5892}
5893
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005894ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
5895 unsigned functionCallConv) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005896 // 6.1.2.1 The following argument types are VFP CPRCs:
5897 // A single-precision floating-point type (including promoted
5898 // half-precision types); A double-precision floating-point type;
5899 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5900 // with a Base Type of a single- or double-precision floating-point type,
5901 // 64-bit containerized vectors or 128-bit containerized vectors with one
5902 // to four Elements.
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005903 // Variadic functions should always marshal to the base standard.
5904 bool IsAAPCS_VFP =
5905 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005906
Reid Klecknerb1be6832014-11-15 01:41:41 +00005907 Ty = useFirstFieldIfTransparentUnion(Ty);
5908
Manman Renfef9e312012-10-16 19:18:39 +00005909 // Handle illegal vector types here.
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005910 if (isIllegalVectorType(Ty))
5911 return coerceIllegalVector(Ty);
Manman Renfef9e312012-10-16 19:18:39 +00005912
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005913 // _Float16 and __fp16 get passed as if it were an int or float, but with
5914 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5915 // half type natively, and does not need to interwork with AAPCS code.
5916 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5917 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005918 llvm::Type *ResType = IsAAPCS_VFP ?
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005919 llvm::Type::getFloatTy(getVMContext()) :
5920 llvm::Type::getInt32Ty(getVMContext());
5921 return ABIArgInfo::getDirect(ResType);
5922 }
5923
John McCalla1dee5302010-08-22 10:59:02 +00005924 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005925 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005926 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005927 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005928 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005929
Alex Bradburye41a5e22018-01-12 20:08:16 +00005930 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
Tim Northover5a1558e2014-11-07 22:30:50 +00005931 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005932 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005933
Oliver Stannard405bded2014-02-11 09:25:50 +00005934 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005935 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005936 }
Tim Northover1060eae2013-06-21 22:49:34 +00005937
Daniel Dunbar09d33622009-09-14 21:54:03 +00005938 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005939 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005940 return ABIArgInfo::getIgnore();
5941
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005942 if (IsAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005943 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5944 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005945 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005946 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005947 if (isHomogeneousAggregate(Ty, Base, Members))
5948 return classifyHomogeneousAggregate(Ty, Base, Members);
Tim Northover5627d392015-10-30 16:30:45 +00005949 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5950 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5951 // this convention even for a variadic function: the backend will use GPRs
5952 // if needed.
5953 const Type *Base = nullptr;
5954 uint64_t Members = 0;
5955 if (isHomogeneousAggregate(Ty, Base, Members)) {
5956 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5957 llvm::Type *Ty =
5958 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5959 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5960 }
5961 }
5962
5963 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5964 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5965 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5966 // bigger than 128-bits, they get placed in space allocated by the caller,
5967 // and a pointer is passed.
5968 return ABIArgInfo::getIndirect(
5969 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005970 }
5971
Manman Ren6c30e132012-08-13 21:23:55 +00005972 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005973 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5974 // most 8-byte. We realign the indirect argument if type alignment is bigger
5975 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005976 uint64_t ABIAlign = 4;
Momchil Velikov20208cc2018-07-30 17:48:23 +00005977 uint64_t TyAlign;
Manman Ren505d68f2012-11-05 22:42:46 +00005978 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Momchil Velikov20208cc2018-07-30 17:48:23 +00005979 getABIKind() == ARMABIInfo::AAPCS) {
5980 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
Manman Ren505d68f2012-11-05 22:42:46 +00005981 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Momchil Velikov20208cc2018-07-30 17:48:23 +00005982 } else {
5983 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5984 }
Manman Ren8cd99812012-11-06 04:58:01 +00005985 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005986 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005987 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5988 /*ByVal=*/true,
5989 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005990 }
5991
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005992 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5993 // same size and alignment.
5994 if (getTarget().isRenderScriptTarget()) {
5995 return coerceToIntArray(Ty, getContext(), getVMContext());
5996 }
5997
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005998 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005999 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006000 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00006001 // FIXME: Try to match the types of the arguments more accurately where
6002 // we can.
Momchil Velikov20208cc2018-07-30 17:48:23 +00006003 if (TyAlign <= 4) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00006004 ElemTy = llvm::Type::getInt32Ty(getVMContext());
6005 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00006006 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00006007 ElemTy = llvm::Type::getInt64Ty(getVMContext());
6008 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00006009 }
Stuart Hastings4b214952011-04-28 18:16:06 +00006010
Tim Northover5a1558e2014-11-07 22:30:50 +00006011 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006012}
6013
Chris Lattner458b2aa2010-07-29 02:16:43 +00006014static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006015 llvm::LLVMContext &VMContext) {
6016 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6017 // is called integer-like if its size is less than or equal to one word, and
6018 // the offset of each of its addressable sub-fields is zero.
6019
6020 uint64_t Size = Context.getTypeSize(Ty);
6021
6022 // Check that the type fits in a word.
6023 if (Size > 32)
6024 return false;
6025
6026 // FIXME: Handle vector types!
6027 if (Ty->isVectorType())
6028 return false;
6029
Daniel Dunbard53bac72009-09-14 02:20:34 +00006030 // Float types are never treated as "integer like".
6031 if (Ty->isRealFloatingType())
6032 return false;
6033
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006034 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00006035 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006036 return true;
6037
Daniel Dunbar96ebba52010-02-01 23:31:26 +00006038 // Small complex integer types are "integer like".
6039 if (const ComplexType *CT = Ty->getAs<ComplexType>())
6040 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006041
6042 // Single element and zero sized arrays should be allowed, by the definition
6043 // above, but they are not.
6044
6045 // Otherwise, it must be a record type.
6046 const RecordType *RT = Ty->getAs<RecordType>();
6047 if (!RT) return false;
6048
6049 // Ignore records with flexible arrays.
6050 const RecordDecl *RD = RT->getDecl();
6051 if (RD->hasFlexibleArrayMember())
6052 return false;
6053
6054 // Check that all sub-fields are at offset 0, and are themselves "integer
6055 // like".
6056 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6057
6058 bool HadField = false;
6059 unsigned idx = 0;
6060 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6061 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00006062 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006063
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006064 // Bit-fields are not addressable, we only need to verify they are "integer
6065 // like". We still have to disallow a subsequent non-bitfield, for example:
6066 // struct { int : 0; int x }
6067 // is non-integer like according to gcc.
6068 if (FD->isBitField()) {
6069 if (!RD->isUnion())
6070 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006071
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006072 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6073 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006074
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006075 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006076 }
6077
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006078 // Check if this field is at offset 0.
6079 if (Layout.getFieldOffset(idx) != 0)
6080 return false;
6081
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006082 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6083 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00006084
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006085 // Only allow at most one field in a structure. This doesn't match the
6086 // wording above, but follows gcc in situations with a field following an
6087 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006088 if (!RD->isUnion()) {
6089 if (HadField)
6090 return false;
6091
6092 HadField = true;
6093 }
6094 }
6095
6096 return true;
6097}
6098
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006099ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6100 unsigned functionCallConv) const {
6101
6102 // Variadic functions should always marshal to the base standard.
6103 bool IsAAPCS_VFP =
6104 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006105
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006106 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006107 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006108
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006109 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6110 // Large vector types should be returned via memory.
6111 if (getContext().getTypeSize(RetTy) > 128)
6112 return getNaturalAlignIndirect(RetTy);
6113 // FP16 vectors should be converted to integer vectors
6114 if (!getTarget().hasLegalHalfType() &&
6115 (VT->getElementType()->isFloat16Type() ||
6116 VT->getElementType()->isHalfType()))
6117 return coerceIllegalVector(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00006118 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00006119
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00006120 // _Float16 and __fp16 get returned as if it were an int or float, but with
6121 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6122 // half type natively, and does not need to interwork with AAPCS code.
6123 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6124 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006125 llvm::Type *ResType = IsAAPCS_VFP ?
Oliver Stannarddc2854c2015-09-03 12:40:58 +00006126 llvm::Type::getFloatTy(getVMContext()) :
6127 llvm::Type::getInt32Ty(getVMContext());
6128 return ABIArgInfo::getDirect(ResType);
6129 }
6130
John McCalla1dee5302010-08-22 10:59:02 +00006131 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00006132 // Treat an enum type as its underlying type.
6133 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6134 RetTy = EnumTy->getDecl()->getIntegerType();
6135
Alex Bradburye41a5e22018-01-12 20:08:16 +00006136 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
Tim Northover5a1558e2014-11-07 22:30:50 +00006137 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00006138 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006139
6140 // Are we following APCS?
6141 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00006142 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006143 return ABIArgInfo::getIgnore();
6144
Daniel Dunbareedf1512010-02-01 23:31:19 +00006145 // Complex types are all returned as packed integers.
6146 //
6147 // FIXME: Consider using 2 x vector types if the back end handles them
6148 // correctly.
6149 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006150 return ABIArgInfo::getDirect(llvm::IntegerType::get(
6151 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00006152
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006153 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006154 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006155 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006156 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006157 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006158 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006159 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006160 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6161 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006162 }
6163
6164 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00006165 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006166 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006167
6168 // Otherwise this is an AAPCS variant.
6169
Chris Lattner458b2aa2010-07-29 02:16:43 +00006170 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006171 return ABIArgInfo::getIgnore();
6172
Bob Wilson1d9269a2011-11-02 04:51:36 +00006173 // Check for homogeneous aggregates with AAPCS-VFP.
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006174 if (IsAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00006175 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00006176 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006177 if (isHomogeneousAggregate(RetTy, Base, Members))
6178 return classifyHomogeneousAggregate(RetTy, Base, Members);
Bob Wilson1d9269a2011-11-02 04:51:36 +00006179 }
6180
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006181 // Aggregates <= 4 bytes are returned in r0; other aggregates
6182 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006183 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006184 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00006185 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6186 // same size and alignment.
6187 if (getTarget().isRenderScriptTarget()) {
6188 return coerceToIntArray(RetTy, getContext(), getVMContext());
6189 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00006190 if (getDataLayout().isBigEndian())
6191 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00006192 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00006193
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006194 // Return in the smallest viable integer type.
6195 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00006196 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006197 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00006198 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6199 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00006200 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6201 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6202 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00006203 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00006204 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006205 }
6206
John McCall7f416cc2015-09-08 08:05:57 +00006207 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006208}
6209
Manman Renfef9e312012-10-16 19:18:39 +00006210/// isIllegalVector - check whether Ty is an illegal vector type.
6211bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00006212 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006213 // On targets that don't support FP16, FP16 is expanded into float, and we
6214 // don't want the ABI to depend on whether or not FP16 is supported in
6215 // hardware. Thus return false to coerce FP16 vectors into integer vectors.
6216 if (!getTarget().hasLegalHalfType() &&
6217 (VT->getElementType()->isFloat16Type() ||
6218 VT->getElementType()->isHalfType()))
6219 return true;
Stephen Hines8267e7d2015-12-04 01:39:30 +00006220 if (isAndroid()) {
6221 // Android shipped using Clang 3.1, which supported a slightly different
6222 // vector ABI. The primary differences were that 3-element vector types
6223 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6224 // accepts that legacy behavior for Android only.
6225 // Check whether VT is legal.
6226 unsigned NumElements = VT->getNumElements();
6227 // NumElements should be power of 2 or equal to 3.
6228 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6229 return true;
6230 } else {
6231 // Check whether VT is legal.
6232 unsigned NumElements = VT->getNumElements();
6233 uint64_t Size = getContext().getTypeSize(VT);
6234 // NumElements should be power of 2.
6235 if (!llvm::isPowerOf2_32(NumElements))
6236 return true;
6237 // Size should be greater than 32 bits.
6238 return Size <= 32;
6239 }
Manman Renfef9e312012-10-16 19:18:39 +00006240 }
6241 return false;
6242}
6243
Mikhail Maltseva45292c2019-06-18 14:34:27 +00006244/// Return true if a type contains any 16-bit floating point vectors
6245bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6246 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6247 uint64_t NElements = AT->getSize().getZExtValue();
6248 if (NElements == 0)
6249 return false;
6250 return containsAnyFP16Vectors(AT->getElementType());
6251 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6252 const RecordDecl *RD = RT->getDecl();
6253
6254 // If this is a C++ record, check the bases first.
6255 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6256 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6257 return containsAnyFP16Vectors(B.getType());
6258 }))
6259 return true;
6260
6261 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6262 return FD && containsAnyFP16Vectors(FD->getType());
6263 }))
6264 return true;
6265
6266 return false;
6267 } else {
6268 if (const VectorType *VT = Ty->getAs<VectorType>())
6269 return (VT->getElementType()->isFloat16Type() ||
6270 VT->getElementType()->isHalfType());
6271 return false;
6272 }
6273}
6274
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006275bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6276 llvm::Type *eltTy,
6277 unsigned numElts) const {
6278 if (!llvm::isPowerOf2_32(numElts))
6279 return false;
6280 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6281 if (size > 64)
6282 return false;
6283 if (vectorSize.getQuantity() != 8 &&
6284 (vectorSize.getQuantity() != 16 || numElts == 1))
6285 return false;
6286 return true;
6287}
6288
Reid Klecknere9f6a712014-10-31 17:10:41 +00006289bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6290 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6291 // double, or 64-bit or 128-bit vectors.
6292 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6293 if (BT->getKind() == BuiltinType::Float ||
6294 BT->getKind() == BuiltinType::Double ||
6295 BT->getKind() == BuiltinType::LongDouble)
6296 return true;
6297 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6298 unsigned VecSize = getContext().getTypeSize(VT);
6299 if (VecSize == 64 || VecSize == 128)
6300 return true;
6301 }
6302 return false;
6303}
6304
6305bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6306 uint64_t Members) const {
6307 return Members <= 4;
6308}
6309
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006310bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6311 bool acceptHalf) const {
6312 // Give precedence to user-specified calling conventions.
6313 if (callConvention != llvm::CallingConv::C)
6314 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6315 else
6316 return (getABIKind() == AAPCS_VFP) ||
6317 (acceptHalf && (getABIKind() == AAPCS16_VFP));
6318}
6319
John McCall7f416cc2015-09-08 08:05:57 +00006320Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6321 QualType Ty) const {
6322 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006323
John McCall7f416cc2015-09-08 08:05:57 +00006324 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006325 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006326 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6327 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6328 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006329 }
6330
John Brawn6c49f582019-05-22 11:42:54 +00006331 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6332 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
Manman Rencca54d02012-10-16 19:01:37 +00006333
John McCall7f416cc2015-09-08 08:05:57 +00006334 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6335 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006336 const Type *Base = nullptr;
6337 uint64_t Members = 0;
John Brawn6c49f582019-05-22 11:42:54 +00006338 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00006339 IsIndirect = true;
6340
Tim Northover5627d392015-10-30 16:30:45 +00006341 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6342 // allocated by the caller.
John Brawn6c49f582019-05-22 11:42:54 +00006343 } else if (TySize > CharUnits::fromQuantity(16) &&
Tim Northover5627d392015-10-30 16:30:45 +00006344 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6345 !isHomogeneousAggregate(Ty, Base, Members)) {
6346 IsIndirect = true;
6347
John McCall7f416cc2015-09-08 08:05:57 +00006348 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006349 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6350 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006351 // Our callers should be prepared to handle an under-aligned address.
6352 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6353 getABIKind() == ARMABIInfo::AAPCS) {
6354 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6355 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006356 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6357 // ARMv7k allows type alignment up to 16 bytes.
6358 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6359 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006360 } else {
6361 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006362 }
Manman Rencca54d02012-10-16 19:01:37 +00006363
John Brawn6c49f582019-05-22 11:42:54 +00006364 std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI };
John McCall7f416cc2015-09-08 08:05:57 +00006365 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6366 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006367}
6368
Chris Lattner0cf24192010-06-28 20:05:43 +00006369//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006370// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006371//===----------------------------------------------------------------------===//
6372
6373namespace {
6374
Justin Holewinski83e96682012-05-24 17:43:12 +00006375class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006376public:
Justin Holewinski36837432013-03-30 14:38:24 +00006377 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006378
6379 ABIArgInfo classifyReturnType(QualType RetTy) const;
6380 ABIArgInfo classifyArgumentType(QualType Ty) const;
6381
Craig Topper4f12f102014-03-12 06:41:41 +00006382 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006383 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6384 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006385};
6386
Justin Holewinski83e96682012-05-24 17:43:12 +00006387class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006388public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006389 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6390 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006391
Eric Christopher162c91c2015-06-05 22:03:00 +00006392 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006393 CodeGen::CodeGenModule &M) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00006394 bool shouldEmitStaticExternCAliases() const override;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006395
Justin Holewinski36837432013-03-30 14:38:24 +00006396private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006397 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6398 // resulting MDNode to the nvvm.annotations MDNode.
6399 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006400};
6401
Alexey Bataev123ad192019-02-27 20:29:45 +00006402/// Checks if the type is unsupported directly by the current target.
6403static bool isUnsupportedType(ASTContext &Context, QualType T) {
6404 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6405 return true;
Alexey Bataev7ae267d2019-06-18 19:04:27 +00006406 if (!Context.getTargetInfo().hasFloat128Type() &&
6407 (T->isFloat128Type() ||
6408 (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
Alexey Bataev123ad192019-02-27 20:29:45 +00006409 return true;
6410 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6411 Context.getTypeSize(T) > 64)
6412 return true;
6413 if (const auto *AT = T->getAsArrayTypeUnsafe())
6414 return isUnsupportedType(Context, AT->getElementType());
6415 const auto *RT = T->getAs<RecordType>();
6416 if (!RT)
6417 return false;
6418 const RecordDecl *RD = RT->getDecl();
6419
6420 // If this is a C++ record, check the bases first.
6421 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6422 for (const CXXBaseSpecifier &I : CXXRD->bases())
6423 if (isUnsupportedType(Context, I.getType()))
6424 return true;
6425
6426 for (const FieldDecl *I : RD->fields())
6427 if (isUnsupportedType(Context, I->getType()))
6428 return true;
6429 return false;
6430}
6431
6432/// Coerce the given type into an array with maximum allowed size of elements.
6433static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context,
6434 llvm::LLVMContext &LLVMContext,
6435 unsigned MaxSize) {
6436 // Alignment and Size are measured in bits.
6437 const uint64_t Size = Context.getTypeSize(Ty);
6438 const uint64_t Alignment = Context.getTypeAlign(Ty);
6439 const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6440 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div);
6441 const uint64_t NumElements = (Size + Div - 1) / Div;
6442 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6443}
6444
Justin Holewinski83e96682012-05-24 17:43:12 +00006445ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006446 if (RetTy->isVoidType())
6447 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006448
Alexey Bataev123ad192019-02-27 20:29:45 +00006449 if (getContext().getLangOpts().OpenMP &&
6450 getContext().getLangOpts().OpenMPIsDevice &&
6451 isUnsupportedType(getContext(), RetTy))
6452 return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64);
6453
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006454 // note: this is different from default ABI
6455 if (!RetTy->isScalarType())
6456 return ABIArgInfo::getDirect();
6457
6458 // Treat an enum type as its underlying type.
6459 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6460 RetTy = EnumTy->getDecl()->getIntegerType();
6461
Alex Bradburye41a5e22018-01-12 20:08:16 +00006462 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6463 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006464}
6465
Justin Holewinski83e96682012-05-24 17:43:12 +00006466ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006467 // Treat an enum type as its underlying type.
6468 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6469 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006470
Eli Bendersky95338a02014-10-29 13:43:21 +00006471 // Return aggregates type as indirect by value
6472 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006473 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006474
Alex Bradburye41a5e22018-01-12 20:08:16 +00006475 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6476 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006477}
6478
Justin Holewinski83e96682012-05-24 17:43:12 +00006479void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006480 if (!getCXXABI().classifyReturnType(FI))
6481 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006482 for (auto &I : FI.arguments())
6483 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006484
6485 // Always honor user-specified calling convention.
6486 if (FI.getCallingConvention() != llvm::CallingConv::C)
6487 return;
6488
John McCall882987f2013-02-28 19:01:20 +00006489 FI.setEffectiveCallingConvention(getRuntimeCC());
6490}
6491
John McCall7f416cc2015-09-08 08:05:57 +00006492Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6493 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006494 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006495}
6496
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006497void NVPTXTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006498 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6499 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006500 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006501 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006502 if (!FD) return;
6503
6504 llvm::Function *F = cast<llvm::Function>(GV);
6505
6506 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006507 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006508 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006509 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006510 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006511 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006512 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6513 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006514 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006515 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006516 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006517 }
Justin Holewinski38031972011-10-05 17:58:44 +00006518
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006519 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006520 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006521 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006522 // __global__ functions cannot be called from the device, we do not
6523 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006524 if (FD->hasAttr<CUDAGlobalAttr>()) {
6525 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6526 addNVVMMetadata(F, "kernel", 1);
6527 }
Artem Belevich7093e402015-04-21 22:55:54 +00006528 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006529 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006530 llvm::APSInt MaxThreads(32);
6531 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6532 if (MaxThreads > 0)
6533 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6534
6535 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6536 // not specified in __launch_bounds__ or if the user specified a 0 value,
6537 // we don't have to add a PTX directive.
6538 if (Attr->getMinBlocks()) {
6539 llvm::APSInt MinBlocks(32);
6540 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6541 if (MinBlocks > 0)
6542 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6543 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006544 }
6545 }
Justin Holewinski38031972011-10-05 17:58:44 +00006546 }
6547}
6548
Eli Benderskye06a2c42014-04-15 16:57:05 +00006549void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6550 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006551 llvm::Module *M = F->getParent();
6552 llvm::LLVMContext &Ctx = M->getContext();
6553
6554 // Get "nvvm.annotations" metadata node
6555 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6556
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006557 llvm::Metadata *MDVals[] = {
6558 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6559 llvm::ConstantAsMetadata::get(
6560 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006561 // Append metadata to nvvm.annotations
6562 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6563}
Yaxun Liub0eee292018-03-29 14:50:00 +00006564
6565bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6566 return false;
6567}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006568}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006569
6570//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006571// SystemZ ABI Implementation
6572//===----------------------------------------------------------------------===//
6573
6574namespace {
6575
Bryan Chane3f1ed52016-04-28 13:56:43 +00006576class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006577 bool HasVector;
6578
Ulrich Weigand47445072013-05-06 16:26:41 +00006579public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006580 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006581 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006582
6583 bool isPromotableIntegerType(QualType Ty) const;
6584 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006585 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006586 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006587 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006588
6589 ABIArgInfo classifyReturnType(QualType RetTy) const;
6590 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6591
Craig Topper4f12f102014-03-12 06:41:41 +00006592 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006593 if (!getCXXABI().classifyReturnType(FI))
6594 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006595 for (auto &I : FI.arguments())
6596 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006597 }
6598
John McCall7f416cc2015-09-08 08:05:57 +00006599 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6600 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006601
John McCall56331e22018-01-07 06:28:49 +00006602 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
Bryan Chane3f1ed52016-04-28 13:56:43 +00006603 bool asReturnValue) const override {
6604 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6605 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006606 bool isSwiftErrorInRegister() const override {
Arnold Schwaighofer612d6932017-11-07 16:40:51 +00006607 return false;
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006608 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006609};
6610
6611class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6612public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006613 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6614 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006615};
6616
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006617}
Ulrich Weigand47445072013-05-06 16:26:41 +00006618
6619bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6620 // Treat an enum type as its underlying type.
6621 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6622 Ty = EnumTy->getDecl()->getIntegerType();
6623
6624 // Promotable integer types are required to be promoted by the ABI.
6625 if (Ty->isPromotableIntegerType())
6626 return true;
6627
6628 // 32-bit values must also be promoted.
6629 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6630 switch (BT->getKind()) {
6631 case BuiltinType::Int:
6632 case BuiltinType::UInt:
6633 return true;
6634 default:
6635 return false;
6636 }
6637 return false;
6638}
6639
6640bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006641 return (Ty->isAnyComplexType() ||
6642 Ty->isVectorType() ||
6643 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006644}
6645
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006646bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6647 return (HasVector &&
6648 Ty->isVectorType() &&
6649 getContext().getTypeSize(Ty) <= 128);
6650}
6651
Ulrich Weigand47445072013-05-06 16:26:41 +00006652bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6653 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6654 switch (BT->getKind()) {
6655 case BuiltinType::Float:
6656 case BuiltinType::Double:
6657 return true;
6658 default:
6659 return false;
6660 }
6661
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006662 return false;
6663}
6664
6665QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006666 if (const RecordType *RT = Ty->getAsStructureType()) {
6667 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006668 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006669
6670 // If this is a C++ record, check the bases first.
6671 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006672 for (const auto &I : CXXRD->bases()) {
6673 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006674
6675 // Empty bases don't affect things either way.
6676 if (isEmptyRecord(getContext(), Base, true))
6677 continue;
6678
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006679 if (!Found.isNull())
6680 return Ty;
6681 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006682 }
6683
6684 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006685 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006686 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006687 // Unlike isSingleElementStruct(), empty structure and array fields
6688 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006689 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00006690 FD->isZeroLengthBitField(getContext()))
Ulrich Weigand759449c2015-03-30 13:49:01 +00006691 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006692
6693 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006694 // Nested structures still do though.
6695 if (!Found.isNull())
6696 return Ty;
6697 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006698 }
6699
6700 // Unlike isSingleElementStruct(), trailing padding is allowed.
6701 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006702 if (!Found.isNull())
6703 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006704 }
6705
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006706 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006707}
6708
John McCall7f416cc2015-09-08 08:05:57 +00006709Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6710 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006711 // Assume that va_list type is correct; should be pointer to LLVM type:
6712 // struct {
6713 // i64 __gpr;
6714 // i64 __fpr;
6715 // i8 *__overflow_arg_area;
6716 // i8 *__reg_save_area;
6717 // };
6718
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006719 // Every non-vector argument occupies 8 bytes and is passed by preference
6720 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6721 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006722 Ty = getContext().getCanonicalType(Ty);
6723 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006724 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006725 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006726 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006727 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006728 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006729 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006730 CharUnits UnpaddedSize;
6731 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006732 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006733 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6734 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006735 } else {
6736 if (AI.getCoerceToType())
6737 ArgTy = AI.getCoerceToType();
6738 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006739 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006740 UnpaddedSize = TyInfo.first;
6741 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006742 }
John McCall7f416cc2015-09-08 08:05:57 +00006743 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6744 if (IsVector && UnpaddedSize > PaddedSize)
6745 PaddedSize = CharUnits::fromQuantity(16);
6746 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006747
John McCall7f416cc2015-09-08 08:05:57 +00006748 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006749
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006750 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006751 llvm::Value *PaddedSizeV =
6752 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006753
6754 if (IsVector) {
6755 // Work out the address of a vector argument on the stack.
6756 // Vector arguments are always passed in the high bits of a
6757 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006758 Address OverflowArgAreaPtr =
James Y Knight751fe282019-02-09 22:22:28 +00006759 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006760 Address OverflowArgArea =
6761 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6762 TyInfo.second);
6763 Address MemAddr =
6764 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006765
6766 // Update overflow_arg_area_ptr pointer
6767 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006768 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6769 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006770 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6771
6772 return MemAddr;
6773 }
6774
John McCall7f416cc2015-09-08 08:05:57 +00006775 assert(PaddedSize.getQuantity() == 8);
6776
6777 unsigned MaxRegs, RegCountField, RegSaveIndex;
6778 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006779 if (InFPRs) {
6780 MaxRegs = 4; // Maximum of 4 FPR arguments
6781 RegCountField = 1; // __fpr
6782 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006783 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006784 } else {
6785 MaxRegs = 5; // Maximum of 5 GPR arguments
6786 RegCountField = 0; // __gpr
6787 RegSaveIndex = 2; // save offset for r2
6788 RegPadding = Padding; // values are passed in the low bits of a GPR
6789 }
6790
James Y Knight751fe282019-02-09 22:22:28 +00006791 Address RegCountPtr =
6792 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006793 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006794 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6795 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006796 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006797
6798 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6799 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6800 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6801 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6802
6803 // Emit code to load the value if it was passed in registers.
6804 CGF.EmitBlock(InRegBlock);
6805
6806 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006807 llvm::Value *ScaledRegCount =
6808 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6809 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006810 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6811 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006812 llvm::Value *RegOffset =
6813 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006814 Address RegSaveAreaPtr =
James Y Knight751fe282019-02-09 22:22:28 +00006815 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006816 llvm::Value *RegSaveArea =
6817 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006818 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6819 "raw_reg_addr"),
6820 PaddedSize);
6821 Address RegAddr =
6822 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006823
6824 // Update the register count
6825 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6826 llvm::Value *NewRegCount =
6827 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6828 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6829 CGF.EmitBranch(ContBlock);
6830
6831 // Emit code to load the value if it was passed in memory.
6832 CGF.EmitBlock(InMemBlock);
6833
6834 // Work out the address of a stack argument.
James Y Knight751fe282019-02-09 22:22:28 +00006835 Address OverflowArgAreaPtr =
6836 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006837 Address OverflowArgArea =
6838 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6839 PaddedSize);
6840 Address RawMemAddr =
6841 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6842 Address MemAddr =
6843 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006844
6845 // Update overflow_arg_area_ptr pointer
6846 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006847 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6848 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006849 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6850 CGF.EmitBranch(ContBlock);
6851
6852 // Return the appropriate result.
6853 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006854 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6855 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006856
6857 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006858 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6859 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006860
6861 return ResAddr;
6862}
6863
Ulrich Weigand47445072013-05-06 16:26:41 +00006864ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6865 if (RetTy->isVoidType())
6866 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006867 if (isVectorArgumentType(RetTy))
6868 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006869 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006870 return getNaturalAlignIndirect(RetTy);
Alex Bradburye41a5e22018-01-12 20:08:16 +00006871 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6872 : ABIArgInfo::getDirect());
Ulrich Weigand47445072013-05-06 16:26:41 +00006873}
6874
6875ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6876 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006877 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006878 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006879
6880 // Integers and enums are extended to full register width.
6881 if (isPromotableIntegerType(Ty))
Alex Bradburye41a5e22018-01-12 20:08:16 +00006882 return ABIArgInfo::getExtend(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006883
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006884 // Handle vector types and vector-like structure types. Note that
6885 // as opposed to float-like structure types, we do not allow any
6886 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006887 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006888 QualType SingleElementTy = GetSingleElementType(Ty);
6889 if (isVectorArgumentType(SingleElementTy) &&
6890 getContext().getTypeSize(SingleElementTy) == Size)
6891 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6892
6893 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006894 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006895 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006896
6897 // Handle small structures.
6898 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6899 // Structures with flexible arrays have variable length, so really
6900 // fail the size test above.
6901 const RecordDecl *RD = RT->getDecl();
6902 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006903 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006904
6905 // The structure is passed as an unextended integer, a float, or a double.
6906 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006907 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006908 assert(Size == 32 || Size == 64);
6909 if (Size == 32)
6910 PassTy = llvm::Type::getFloatTy(getVMContext());
6911 else
6912 PassTy = llvm::Type::getDoubleTy(getVMContext());
6913 } else
6914 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6915 return ABIArgInfo::getDirect(PassTy);
6916 }
6917
6918 // Non-structure compounds are passed indirectly.
6919 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006920 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006921
Craig Topper8a13c412014-05-21 05:09:00 +00006922 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006923}
6924
6925//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006926// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006927//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006928
6929namespace {
6930
6931class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6932public:
Chris Lattner2b037972010-07-29 02:01:43 +00006933 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6934 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006935 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006936 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006937};
6938
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006939}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006940
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006941void MSP430TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006942 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6943 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006944 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006945 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006946 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
6947 if (!InterruptAttr)
6948 return;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006949
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006950 // Handle 'interrupt' attribute:
6951 llvm::Function *F = cast<llvm::Function>(GV);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006952
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006953 // Step 1: Set ISR calling convention.
6954 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006955
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006956 // Step 2: Add attributes goodness.
6957 F->addFnAttr(llvm::Attribute::NoInline);
6958 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006959 }
6960}
6961
Chris Lattner0cf24192010-06-28 20:05:43 +00006962//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006963// MIPS ABI Implementation. This works for both little-endian and
6964// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006965//===----------------------------------------------------------------------===//
6966
John McCall943fae92010-05-27 06:19:26 +00006967namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006968class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006969 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006970 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6971 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006972 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006973 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006974 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006975 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006976public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006977 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006978 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006979 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006980
6981 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006982 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006983 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006984 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6985 QualType Ty) const override;
Alex Bradburye41a5e22018-01-12 20:08:16 +00006986 ABIArgInfo extendType(QualType Ty) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006987};
6988
John McCall943fae92010-05-27 06:19:26 +00006989class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006990 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006991public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006992 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6993 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006994 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006995
Craig Topper4f12f102014-03-12 06:41:41 +00006996 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006997 return 29;
6998 }
6999
Eric Christopher162c91c2015-06-05 22:03:00 +00007000 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007001 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007002 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00007003 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00007004 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007005
7006 if (FD->hasAttr<MipsLongCallAttr>())
7007 Fn->addFnAttr("long-call");
7008 else if (FD->hasAttr<MipsShortCallAttr>())
7009 Fn->addFnAttr("short-call");
7010
7011 // Other attributes do not have a meaning for declarations.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007012 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007013 return;
7014
Reed Kotler3d5966f2013-03-13 20:40:30 +00007015 if (FD->hasAttr<Mips16Attr>()) {
7016 Fn->addFnAttr("mips16");
7017 }
7018 else if (FD->hasAttr<NoMips16Attr>()) {
7019 Fn->addFnAttr("nomips16");
7020 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00007021
Simon Atanasyan2c87f532017-05-22 12:47:43 +00007022 if (FD->hasAttr<MicroMipsAttr>())
7023 Fn->addFnAttr("micromips");
7024 else if (FD->hasAttr<NoMicroMipsAttr>())
7025 Fn->addFnAttr("nomicromips");
7026
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00007027 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7028 if (!Attr)
7029 return;
7030
7031 const char *Kind;
7032 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00007033 case MipsInterruptAttr::eic: Kind = "eic"; break;
7034 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
7035 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
7036 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
7037 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
7038 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
7039 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
7040 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
7041 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
7042 }
7043
7044 Fn->addFnAttr("interrupt", Kind);
7045
Reed Kotler373feca2013-01-16 17:10:28 +00007046 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00007047
John McCall943fae92010-05-27 06:19:26 +00007048 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007049 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00007050
Craig Topper4f12f102014-03-12 06:41:41 +00007051 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00007052 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00007053 }
John McCall943fae92010-05-27 06:19:26 +00007054};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007055}
John McCall943fae92010-05-27 06:19:26 +00007056
Eric Christopher7565e0d2015-05-29 23:09:49 +00007057void MipsABIInfo::CoerceToIntArgs(
7058 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007059 llvm::IntegerType *IntTy =
7060 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007061
7062 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7063 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7064 ArgList.push_back(IntTy);
7065
7066 // If necessary, add one more integer type to ArgList.
7067 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7068
7069 if (R)
7070 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007071}
7072
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007073// In N32/64, an aligned double precision floating point field is passed in
7074// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007075llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007076 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7077
7078 if (IsO32) {
7079 CoerceToIntArgs(TySize, ArgList);
7080 return llvm::StructType::get(getVMContext(), ArgList);
7081 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007082
Akira Hatanaka02e13e52012-01-12 00:52:17 +00007083 if (Ty->isComplexType())
7084 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00007085
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00007086 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007087
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007088 // Unions/vectors are passed in integer registers.
7089 if (!RT || !RT->isStructureOrClassType()) {
7090 CoerceToIntArgs(TySize, ArgList);
7091 return llvm::StructType::get(getVMContext(), ArgList);
7092 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007093
7094 const RecordDecl *RD = RT->getDecl();
7095 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007096 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00007097
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007098 uint64_t LastOffset = 0;
7099 unsigned idx = 0;
7100 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7101
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00007102 // Iterate over fields in the struct/class and check if there are any aligned
7103 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007104 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7105 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007106 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007107 const BuiltinType *BT = Ty->getAs<BuiltinType>();
7108
7109 if (!BT || BT->getKind() != BuiltinType::Double)
7110 continue;
7111
7112 uint64_t Offset = Layout.getFieldOffset(idx);
7113 if (Offset % 64) // Ignore doubles that are not aligned.
7114 continue;
7115
7116 // Add ((Offset - LastOffset) / 64) args of type i64.
7117 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7118 ArgList.push_back(I64);
7119
7120 // Add double type.
7121 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7122 LastOffset = Offset + 64;
7123 }
7124
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007125 CoerceToIntArgs(TySize - LastOffset, IntArgList);
7126 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007127
7128 return llvm::StructType::get(getVMContext(), ArgList);
7129}
7130
Akira Hatanakaddd66342013-10-29 18:41:15 +00007131llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7132 uint64_t Offset) const {
7133 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00007134 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00007135
Akira Hatanakaddd66342013-10-29 18:41:15 +00007136 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007137}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00007138
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007139ABIArgInfo
7140MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00007141 Ty = useFirstFieldIfTransparentUnion(Ty);
7142
Akira Hatanaka1632af62012-01-09 19:31:25 +00007143 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007144 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007145 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007146
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007147 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7148 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007149 unsigned CurrOffset = llvm::alignTo(Offset, Align);
7150 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00007151
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007152 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00007153 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007154 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00007155 return ABIArgInfo::getIgnore();
7156
Mark Lacey3825e832013-10-06 01:33:34 +00007157 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007158 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00007159 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007160 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00007161
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007162 // If we have reached here, aggregates are passed directly by coercing to
7163 // another structure type. Padding is inserted if the offset of the
7164 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00007165 ABIArgInfo ArgInfo =
7166 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7167 getPaddingType(OrigOffset, CurrOffset));
7168 ArgInfo.setInReg(true);
7169 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007170 }
7171
7172 // Treat an enum type as its underlying type.
7173 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7174 Ty = EnumTy->getDecl()->getIntegerType();
7175
Daniel Sanders5b445b32014-10-24 14:42:42 +00007176 // All integral types are promoted to the GPR width.
7177 if (Ty->isIntegralOrEnumerationType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00007178 return extendType(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007179
Akira Hatanakaddd66342013-10-29 18:41:15 +00007180 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00007181 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00007182}
7183
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007184llvm::Type*
7185MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00007186 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007187 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007188
Akira Hatanakab6f74432012-02-09 18:49:26 +00007189 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007190 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00007191 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7192 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007193
Akira Hatanakab6f74432012-02-09 18:49:26 +00007194 // N32/64 returns struct/classes in floating point registers if the
7195 // following conditions are met:
7196 // 1. The size of the struct/class is no larger than 128-bit.
7197 // 2. The struct/class has one or two fields all of which are floating
7198 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007199 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00007200 //
7201 // Any other composite results are returned in integer registers.
7202 //
7203 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7204 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7205 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007206 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007207
Akira Hatanakab6f74432012-02-09 18:49:26 +00007208 if (!BT || !BT->isFloatingPoint())
7209 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007210
David Blaikie2d7c57e2012-04-30 02:36:29 +00007211 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00007212 }
7213
7214 if (b == e)
7215 return llvm::StructType::get(getVMContext(), RTList,
7216 RD->hasAttr<PackedAttr>());
7217
7218 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007219 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007220 }
7221
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007222 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007223 return llvm::StructType::get(getVMContext(), RTList);
7224}
7225
Akira Hatanakab579fe52011-06-02 00:09:17 +00007226ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00007227 uint64_t Size = getContext().getTypeSize(RetTy);
7228
Daniel Sandersed39f582014-09-04 13:28:14 +00007229 if (RetTy->isVoidType())
7230 return ABIArgInfo::getIgnore();
7231
7232 // O32 doesn't treat zero-sized structs differently from other structs.
7233 // However, N32/N64 ignores zero sized return values.
7234 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00007235 return ABIArgInfo::getIgnore();
7236
Akira Hatanakac37eddf2012-05-11 21:01:17 +00007237 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007238 if (Size <= 128) {
7239 if (RetTy->isAnyComplexType())
7240 return ABIArgInfo::getDirect();
7241
Daniel Sanderse5018b62014-09-04 15:05:39 +00007242 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00007243 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00007244 if (!IsO32 ||
7245 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7246 ABIArgInfo ArgInfo =
7247 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7248 ArgInfo.setInReg(true);
7249 return ArgInfo;
7250 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007251 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00007252
John McCall7f416cc2015-09-08 08:05:57 +00007253 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007254 }
7255
7256 // Treat an enum type as its underlying type.
7257 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7258 RetTy = EnumTy->getDecl()->getIntegerType();
7259
Stefan Maksimovicb9da8a52018-07-30 10:44:46 +00007260 if (RetTy->isPromotableIntegerType())
7261 return ABIArgInfo::getExtend(RetTy);
7262
7263 if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7264 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7265 return ABIArgInfo::getSignExtend(RetTy);
7266
7267 return ABIArgInfo::getDirect();
Akira Hatanakab579fe52011-06-02 00:09:17 +00007268}
7269
7270void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00007271 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00007272 if (!getCXXABI().classifyReturnType(FI))
7273 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00007274
Eric Christopher7565e0d2015-05-29 23:09:49 +00007275 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007276 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00007277
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007278 for (auto &I : FI.arguments())
7279 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007280}
7281
John McCall7f416cc2015-09-08 08:05:57 +00007282Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7283 QualType OrigTy) const {
7284 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00007285
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007286 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7287 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00007288 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007289 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00007290 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007291 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00007292 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007293 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00007294 DidPromote = true;
7295 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7296 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00007297 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00007298
John McCall7f416cc2015-09-08 08:05:57 +00007299 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007300
John McCall7f416cc2015-09-08 08:05:57 +00007301 // The alignment of things in the argument area is never larger than
7302 // StackAlignInBytes.
7303 TyInfo.second =
7304 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7305
7306 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7307 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7308
7309 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7310 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7311
7312
7313 // If there was a promotion, "unpromote" into a temporary.
7314 // TODO: can we just use a pointer into a subset of the original slot?
7315 if (DidPromote) {
7316 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7317 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7318
7319 // Truncate down to the right width.
7320 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7321 : CGF.IntPtrTy);
7322 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7323 if (OrigTy->isPointerType())
7324 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7325
7326 CGF.Builder.CreateStore(V, Temp);
7327 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007328 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007329
John McCall7f416cc2015-09-08 08:05:57 +00007330 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007331}
7332
Alex Bradburye41a5e22018-01-12 20:08:16 +00007333ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007334 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007335
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007336 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7337 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
Alex Bradburye41a5e22018-01-12 20:08:16 +00007338 return ABIArgInfo::getSignExtend(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007339
Alex Bradburye41a5e22018-01-12 20:08:16 +00007340 return ABIArgInfo::getExtend(Ty);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007341}
7342
John McCall943fae92010-05-27 06:19:26 +00007343bool
7344MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7345 llvm::Value *Address) const {
7346 // This information comes from gcc's implementation, which seems to
7347 // as canonical as it gets.
7348
John McCall943fae92010-05-27 06:19:26 +00007349 // Everything on MIPS is 4 bytes. Double-precision FP registers
7350 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007351 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007352
7353 // 0-31 are the general purpose registers, $0 - $31.
7354 // 32-63 are the floating-point registers, $f0 - $f31.
7355 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7356 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007357 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007358
7359 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7360 // They are one bit wide and ignored here.
7361
7362 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7363 // (coprocessor 1 is the FP unit)
7364 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7365 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7366 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007367 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007368 return false;
7369}
7370
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007371//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007372// AVR ABI Implementation.
7373//===----------------------------------------------------------------------===//
7374
7375namespace {
7376class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7377public:
7378 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7379 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7380
7381 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007382 CodeGen::CodeGenModule &CGM) const override {
7383 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007384 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007385 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7386 if (!FD) return;
7387 auto *Fn = cast<llvm::Function>(GV);
7388
7389 if (FD->getAttr<AVRInterruptAttr>())
7390 Fn->addFnAttr("interrupt");
7391
7392 if (FD->getAttr<AVRSignalAttr>())
7393 Fn->addFnAttr("signal");
7394 }
7395};
7396}
7397
7398//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007399// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007400// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007401// handling.
7402//===----------------------------------------------------------------------===//
7403
7404namespace {
7405
7406class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7407public:
7408 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7409 : DefaultTargetCodeGenInfo(CGT) {}
7410
Eric Christopher162c91c2015-06-05 22:03:00 +00007411 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007412 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007413};
7414
Eric Christopher162c91c2015-06-05 22:03:00 +00007415void TCETargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007416 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7417 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007418 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007419 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007420 if (!FD) return;
7421
7422 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007423
David Blaikiebbafb8a2012-03-11 07:00:24 +00007424 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007425 if (FD->hasAttr<OpenCLKernelAttr>()) {
7426 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007427 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007428 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7429 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007430 // Convert the reqd_work_group_size() attributes to metadata.
7431 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007432 llvm::NamedMDNode *OpenCLMetadata =
7433 M.getModule().getOrInsertNamedMetadata(
7434 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007435
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007436 SmallVector<llvm::Metadata *, 5> Operands;
7437 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007438
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007439 Operands.push_back(
7440 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7441 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7442 Operands.push_back(
7443 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7444 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7445 Operands.push_back(
7446 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7447 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007448
Eric Christopher7565e0d2015-05-29 23:09:49 +00007449 // Add a boolean constant operand for "required" (true) or "hint"
7450 // (false) for implementing the work_group_size_hint attr later.
7451 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007452 Operands.push_back(
7453 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007454 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7455 }
7456 }
7457 }
7458}
7459
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007460}
John McCall943fae92010-05-27 06:19:26 +00007461
Tony Linthicum76329bf2011-12-12 21:14:55 +00007462//===----------------------------------------------------------------------===//
7463// Hexagon ABI Implementation
7464//===----------------------------------------------------------------------===//
7465
7466namespace {
7467
7468class HexagonABIInfo : public ABIInfo {
7469
7470
7471public:
7472 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7473
7474private:
7475
7476 ABIArgInfo classifyReturnType(QualType RetTy) const;
7477 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7478
Craig Topper4f12f102014-03-12 06:41:41 +00007479 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007480
John McCall7f416cc2015-09-08 08:05:57 +00007481 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7482 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007483};
7484
7485class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7486public:
7487 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7488 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7489
Craig Topper4f12f102014-03-12 06:41:41 +00007490 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007491 return 29;
7492 }
7493};
7494
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007495}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007496
7497void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007498 if (!getCXXABI().classifyReturnType(FI))
7499 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007500 for (auto &I : FI.arguments())
7501 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007502}
7503
7504ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7505 if (!isAggregateTypeForABI(Ty)) {
7506 // Treat an enum type as its underlying type.
7507 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7508 Ty = EnumTy->getDecl()->getIntegerType();
7509
Alex Bradburye41a5e22018-01-12 20:08:16 +00007510 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7511 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007512 }
7513
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007514 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7515 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7516
Tony Linthicum76329bf2011-12-12 21:14:55 +00007517 // Ignore empty records.
7518 if (isEmptyRecord(getContext(), Ty, true))
7519 return ABIArgInfo::getIgnore();
7520
Tony Linthicum76329bf2011-12-12 21:14:55 +00007521 uint64_t Size = getContext().getTypeSize(Ty);
7522 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007523 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007524 // Pass in the smallest viable integer type.
7525 else if (Size > 32)
7526 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7527 else if (Size > 16)
7528 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7529 else if (Size > 8)
7530 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7531 else
7532 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7533}
7534
7535ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7536 if (RetTy->isVoidType())
7537 return ABIArgInfo::getIgnore();
7538
7539 // Large vector types should be returned via memory.
7540 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007541 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007542
7543 if (!isAggregateTypeForABI(RetTy)) {
7544 // Treat an enum type as its underlying type.
7545 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7546 RetTy = EnumTy->getDecl()->getIntegerType();
7547
Alex Bradburye41a5e22018-01-12 20:08:16 +00007548 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7549 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007550 }
7551
Tony Linthicum76329bf2011-12-12 21:14:55 +00007552 if (isEmptyRecord(getContext(), RetTy, true))
7553 return ABIArgInfo::getIgnore();
7554
7555 // Aggregates <= 8 bytes are returned in r0; other aggregates
7556 // are returned indirectly.
7557 uint64_t Size = getContext().getTypeSize(RetTy);
7558 if (Size <= 64) {
7559 // Return in the smallest viable integer type.
7560 if (Size <= 8)
7561 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7562 if (Size <= 16)
7563 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7564 if (Size <= 32)
7565 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7566 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7567 }
7568
John McCall7f416cc2015-09-08 08:05:57 +00007569 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007570}
7571
John McCall7f416cc2015-09-08 08:05:57 +00007572Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7573 QualType Ty) const {
7574 // FIXME: Someone needs to audit that this handle alignment correctly.
7575 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7576 getContext().getTypeInfoInChars(Ty),
7577 CharUnits::fromQuantity(4),
7578 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007579}
7580
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007581//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007582// Lanai ABI Implementation
7583//===----------------------------------------------------------------------===//
7584
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007585namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007586class LanaiABIInfo : public DefaultABIInfo {
7587public:
7588 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7589
7590 bool shouldUseInReg(QualType Ty, CCState &State) const;
7591
7592 void computeInfo(CGFunctionInfo &FI) const override {
7593 CCState State(FI.getCallingConvention());
7594 // Lanai uses 4 registers to pass arguments unless the function has the
7595 // regparm attribute set.
7596 if (FI.getHasRegParm()) {
7597 State.FreeRegs = FI.getRegParm();
7598 } else {
7599 State.FreeRegs = 4;
7600 }
7601
7602 if (!getCXXABI().classifyReturnType(FI))
7603 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7604 for (auto &I : FI.arguments())
7605 I.info = classifyArgumentType(I.type, State);
7606 }
7607
Jacques Pienaare74d9132016-04-26 00:09:29 +00007608 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007609 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7610};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007611} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007612
7613bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7614 unsigned Size = getContext().getTypeSize(Ty);
7615 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7616
7617 if (SizeInRegs == 0)
7618 return false;
7619
7620 if (SizeInRegs > State.FreeRegs) {
7621 State.FreeRegs = 0;
7622 return false;
7623 }
7624
7625 State.FreeRegs -= SizeInRegs;
7626
7627 return true;
7628}
7629
Jacques Pienaare74d9132016-04-26 00:09:29 +00007630ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7631 CCState &State) const {
7632 if (!ByVal) {
7633 if (State.FreeRegs) {
7634 --State.FreeRegs; // Non-byval indirects just use one pointer.
7635 return getNaturalAlignIndirectInReg(Ty);
7636 }
7637 return getNaturalAlignIndirect(Ty, false);
7638 }
7639
7640 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007641 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007642 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7643 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7644 /*Realign=*/TypeAlign >
7645 MinABIStackAlignInBytes);
7646}
7647
Jacques Pienaard964cc22016-03-28 21:02:54 +00007648ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7649 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007650 // Check with the C++ ABI first.
7651 const RecordType *RT = Ty->getAs<RecordType>();
7652 if (RT) {
7653 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7654 if (RAA == CGCXXABI::RAA_Indirect) {
7655 return getIndirectResult(Ty, /*ByVal=*/false, State);
7656 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7657 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7658 }
7659 }
7660
7661 if (isAggregateTypeForABI(Ty)) {
7662 // Structures with flexible arrays are always indirect.
7663 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7664 return getIndirectResult(Ty, /*ByVal=*/true, State);
7665
7666 // Ignore empty structs/unions.
7667 if (isEmptyRecord(getContext(), Ty, true))
7668 return ABIArgInfo::getIgnore();
7669
7670 llvm::LLVMContext &LLVMContext = getVMContext();
7671 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7672 if (SizeInRegs <= State.FreeRegs) {
7673 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7674 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7675 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7676 State.FreeRegs -= SizeInRegs;
7677 return ABIArgInfo::getDirectInReg(Result);
7678 } else {
7679 State.FreeRegs = 0;
7680 }
7681 return getIndirectResult(Ty, true, State);
7682 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007683
7684 // Treat an enum type as its underlying type.
7685 if (const auto *EnumTy = Ty->getAs<EnumType>())
7686 Ty = EnumTy->getDecl()->getIntegerType();
7687
Jacques Pienaare74d9132016-04-26 00:09:29 +00007688 bool InReg = shouldUseInReg(Ty, State);
7689 if (Ty->isPromotableIntegerType()) {
7690 if (InReg)
7691 return ABIArgInfo::getDirectInReg();
Alex Bradburye41a5e22018-01-12 20:08:16 +00007692 return ABIArgInfo::getExtend(Ty);
Jacques Pienaare74d9132016-04-26 00:09:29 +00007693 }
7694 if (InReg)
7695 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007696 return ABIArgInfo::getDirect();
7697}
7698
7699namespace {
7700class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7701public:
7702 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7703 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7704};
7705}
7706
7707//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007708// AMDGPU ABI Implementation
7709//===----------------------------------------------------------------------===//
7710
7711namespace {
7712
Matt Arsenault88d7da02016-08-22 19:25:59 +00007713class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007714private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007715 static const unsigned MaxNumRegsForArgsRet = 16;
7716
Matt Arsenault3fe73952017-08-09 21:44:58 +00007717 unsigned numRegsForType(QualType Ty) const;
7718
7719 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7720 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7721 uint64_t Members) const override;
7722
Michael Liao15140e42019-11-04 11:41:07 -05007723 // Coerce HIP pointer arguments from generic pointers to global ones.
7724 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
7725 unsigned ToAS) const {
7726 // Structure types.
7727 if (auto STy = dyn_cast<llvm::StructType>(Ty)) {
7728 SmallVector<llvm::Type *, 8> EltTys;
7729 bool Changed = false;
7730 for (auto T : STy->elements()) {
7731 auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
7732 EltTys.push_back(NT);
7733 Changed |= (NT != T);
7734 }
7735 // Skip if there is no change in element types.
7736 if (!Changed)
7737 return STy;
7738 if (STy->hasName())
7739 return llvm::StructType::create(
7740 EltTys, (STy->getName() + ".coerce").str(), STy->isPacked());
7741 return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked());
7742 }
7743 // Arrary types.
7744 if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) {
7745 auto T = ATy->getElementType();
7746 auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
7747 // Skip if there is no change in that element type.
7748 if (NT == T)
7749 return ATy;
7750 return llvm::ArrayType::get(NT, ATy->getNumElements());
7751 }
7752 // Single value types.
7753 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
7754 return llvm::PointerType::get(
7755 cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
7756 return Ty;
7757 }
7758
Matt Arsenault3fe73952017-08-09 21:44:58 +00007759public:
7760 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7761 DefaultABIInfo(CGT) {}
7762
7763 ABIArgInfo classifyReturnType(QualType RetTy) const;
7764 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7765 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007766
7767 void computeInfo(CGFunctionInfo &FI) const override;
Michael Liao5a486782019-10-24 11:41:11 -04007768 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7769 QualType Ty) const override;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007770};
7771
Matt Arsenault3fe73952017-08-09 21:44:58 +00007772bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7773 return true;
7774}
7775
7776bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7777 const Type *Base, uint64_t Members) const {
7778 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7779
7780 // Homogeneous Aggregates may occupy at most 16 registers.
7781 return Members * NumRegs <= MaxNumRegsForArgsRet;
7782}
7783
Matt Arsenault3fe73952017-08-09 21:44:58 +00007784/// Estimate number of registers the type will use when passed in registers.
7785unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7786 unsigned NumRegs = 0;
7787
7788 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7789 // Compute from the number of elements. The reported size is based on the
7790 // in-memory size, which includes the padding 4th element for 3-vectors.
7791 QualType EltTy = VT->getElementType();
7792 unsigned EltSize = getContext().getTypeSize(EltTy);
7793
7794 // 16-bit element vectors should be passed as packed.
7795 if (EltSize == 16)
7796 return (VT->getNumElements() + 1) / 2;
7797
7798 unsigned EltNumRegs = (EltSize + 31) / 32;
7799 return EltNumRegs * VT->getNumElements();
7800 }
7801
7802 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7803 const RecordDecl *RD = RT->getDecl();
7804 assert(!RD->hasFlexibleArrayMember());
7805
7806 for (const FieldDecl *Field : RD->fields()) {
7807 QualType FieldTy = Field->getType();
7808 NumRegs += numRegsForType(FieldTy);
7809 }
7810
7811 return NumRegs;
7812 }
7813
7814 return (getContext().getTypeSize(Ty) + 31) / 32;
7815}
7816
Matt Arsenault88d7da02016-08-22 19:25:59 +00007817void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007818 llvm::CallingConv::ID CC = FI.getCallingConvention();
7819
Matt Arsenault88d7da02016-08-22 19:25:59 +00007820 if (!getCXXABI().classifyReturnType(FI))
7821 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7822
Matt Arsenault3fe73952017-08-09 21:44:58 +00007823 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7824 for (auto &Arg : FI.arguments()) {
7825 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7826 Arg.info = classifyKernelArgumentType(Arg.type);
7827 } else {
7828 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7829 }
7830 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007831}
7832
Michael Liao5a486782019-10-24 11:41:11 -04007833Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7834 QualType Ty) const {
7835 llvm_unreachable("AMDGPU does not support varargs");
7836}
7837
Matt Arsenault3fe73952017-08-09 21:44:58 +00007838ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7839 if (isAggregateTypeForABI(RetTy)) {
7840 // Records with non-trivial destructors/copy-constructors should not be
7841 // returned by value.
7842 if (!getRecordArgABI(RetTy, getCXXABI())) {
7843 // Ignore empty structs/unions.
7844 if (isEmptyRecord(getContext(), RetTy, true))
7845 return ABIArgInfo::getIgnore();
7846
7847 // Lower single-element structs to just return a regular value.
7848 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7849 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7850
7851 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7852 const RecordDecl *RD = RT->getDecl();
7853 if (RD->hasFlexibleArrayMember())
7854 return DefaultABIInfo::classifyReturnType(RetTy);
7855 }
7856
7857 // Pack aggregates <= 4 bytes into single VGPR or pair.
7858 uint64_t Size = getContext().getTypeSize(RetTy);
7859 if (Size <= 16)
7860 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7861
7862 if (Size <= 32)
7863 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7864
7865 if (Size <= 64) {
7866 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7867 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7868 }
7869
7870 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7871 return ABIArgInfo::getDirect();
7872 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007873 }
7874
Matt Arsenault3fe73952017-08-09 21:44:58 +00007875 // Otherwise just do the default thing.
7876 return DefaultABIInfo::classifyReturnType(RetTy);
7877}
7878
7879/// For kernels all parameters are really passed in a special buffer. It doesn't
7880/// make sense to pass anything byval, so everything must be direct.
7881ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7882 Ty = useFirstFieldIfTransparentUnion(Ty);
7883
7884 // TODO: Can we omit empty structs?
7885
Michael Liao15140e42019-11-04 11:41:07 -05007886 llvm::Type *LTy = nullptr;
Matt Arsenault3fe73952017-08-09 21:44:58 +00007887 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
Michael Liao15140e42019-11-04 11:41:07 -05007888 LTy = CGT.ConvertType(QualType(SeltTy, 0));
7889
7890 if (getContext().getLangOpts().HIP) {
7891 if (!LTy)
7892 LTy = CGT.ConvertType(Ty);
7893 LTy = coerceKernelArgumentType(
7894 LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
7895 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
7896 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007897
7898 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7899 // individual elements, which confuses the Clover OpenCL backend; therefore we
7900 // have to set it to false here. Other args of getDirect() are just defaults.
Michael Liao15140e42019-11-04 11:41:07 -05007901 return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
Matt Arsenault88d7da02016-08-22 19:25:59 +00007902}
7903
Matt Arsenault3fe73952017-08-09 21:44:58 +00007904ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7905 unsigned &NumRegsLeft) const {
7906 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7907
7908 Ty = useFirstFieldIfTransparentUnion(Ty);
7909
7910 if (isAggregateTypeForABI(Ty)) {
7911 // Records with non-trivial destructors/copy-constructors should not be
7912 // passed by value.
7913 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7914 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7915
7916 // Ignore empty structs/unions.
7917 if (isEmptyRecord(getContext(), Ty, true))
7918 return ABIArgInfo::getIgnore();
7919
7920 // Lower single-element structs to just pass a regular value. TODO: We
7921 // could do reasonable-size multiple-element structs too, using getExpand(),
7922 // though watch out for things like bitfields.
7923 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7924 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7925
7926 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7927 const RecordDecl *RD = RT->getDecl();
7928 if (RD->hasFlexibleArrayMember())
7929 return DefaultABIInfo::classifyArgumentType(Ty);
7930 }
7931
7932 // Pack aggregates <= 8 bytes into single VGPR or pair.
7933 uint64_t Size = getContext().getTypeSize(Ty);
7934 if (Size <= 64) {
7935 unsigned NumRegs = (Size + 31) / 32;
7936 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7937
7938 if (Size <= 16)
7939 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7940
7941 if (Size <= 32)
7942 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7943
7944 // XXX: Should this be i64 instead, and should the limit increase?
7945 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7946 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7947 }
7948
7949 if (NumRegsLeft > 0) {
7950 unsigned NumRegs = numRegsForType(Ty);
7951 if (NumRegsLeft >= NumRegs) {
7952 NumRegsLeft -= NumRegs;
7953 return ABIArgInfo::getDirect();
7954 }
7955 }
7956 }
7957
7958 // Otherwise just do the default thing.
7959 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7960 if (!ArgInfo.isIndirect()) {
7961 unsigned NumRegs = numRegsForType(Ty);
7962 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7963 }
7964
7965 return ArgInfo;
7966}
7967
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007968class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7969public:
7970 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007971 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007972 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007973 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007974 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007975
Yaxun Liu402804b2016-12-15 08:09:08 +00007976 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7977 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007978
Alexander Richardson6d989432017-10-15 18:48:14 +00007979 LangAS getASTAllocaAddressSpace() const override {
7980 return getLangASFromTargetAS(
7981 getABIInfo().getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007982 }
Alexander Richardson6d989432017-10-15 18:48:14 +00007983 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7984 const VarDecl *D) const override;
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +00007985 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
7986 SyncScope Scope,
7987 llvm::AtomicOrdering Ordering,
7988 llvm::LLVMContext &Ctx) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007989 llvm::Function *
7990 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7991 llvm::Function *BlockInvokeFunc,
7992 llvm::Value *BlockLiteral) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00007993 bool shouldEmitStaticExternCAliases() const override;
Yaxun Liu6c10a662018-06-12 00:16:33 +00007994 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007995};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007996}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007997
Scott Linder80a1ee42019-02-12 18:30:38 +00007998static bool requiresAMDGPUProtectedVisibility(const Decl *D,
7999 llvm::GlobalValue *GV) {
8000 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8001 return false;
8002
8003 return D->hasAttr<OpenCLKernelAttr>() ||
8004 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
Michael Liao38205062019-04-26 19:31:48 +00008005 (isa<VarDecl>(D) &&
Yaxun Liuc3dfe902019-06-26 03:47:37 +00008006 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8007 D->hasAttr<HIPPinnedShadowAttr>()));
8008}
8009
8010static bool requiresAMDGPUDefaultVisibility(const Decl *D,
8011 llvm::GlobalValue *GV) {
8012 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8013 return false;
8014
8015 return isa<VarDecl>(D) && D->hasAttr<HIPPinnedShadowAttr>();
Scott Linder80a1ee42019-02-12 18:30:38 +00008016}
8017
Eric Christopher162c91c2015-06-05 22:03:00 +00008018void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00008019 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Yaxun Liuc3dfe902019-06-26 03:47:37 +00008020 if (requiresAMDGPUDefaultVisibility(D, GV)) {
8021 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
8022 GV->setDSOLocal(false);
8023 } else if (requiresAMDGPUProtectedVisibility(D, GV)) {
Scott Linder80a1ee42019-02-12 18:30:38 +00008024 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8025 GV->setDSOLocal(true);
8026 }
8027
Rafael Espindoladeb10be2018-02-07 19:04:41 +00008028 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00008029 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00008030 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008031 if (!FD)
8032 return;
8033
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00008034 llvm::Function *F = cast<llvm::Function>(GV);
8035
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00008036 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8037 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
Tony Tye1a3f3a22018-03-23 18:43:15 +00008038
Matt Arsenaulteac783a2019-08-27 19:25:40 +00008039
8040 const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8041 FD->hasAttr<OpenCLKernelAttr>();
Yaxun Liu1bea97c2019-09-03 18:50:24 +00008042 const bool IsHIPKernel = M.getLangOpts().HIP &&
8043 FD->hasAttr<CUDAGlobalAttr>();
8044 if ((IsOpenCLKernel || IsHIPKernel) &&
Tony Tye1a3f3a22018-03-23 18:43:15 +00008045 (M.getTriple().getOS() == llvm::Triple::AMDHSA))
Christudasan Devadasan18ba9d62019-07-10 15:10:08 +00008046 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
Tony Tye1a3f3a22018-03-23 18:43:15 +00008047
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00008048 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
8049 if (ReqdWGS || FlatWGS) {
Michael Liao7557afa2019-02-26 18:49:36 +00008050 unsigned Min = 0;
8051 unsigned Max = 0;
8052 if (FlatWGS) {
8053 Min = FlatWGS->getMin()
8054 ->EvaluateKnownConstInt(M.getContext())
8055 .getExtValue();
8056 Max = FlatWGS->getMax()
8057 ->EvaluateKnownConstInt(M.getContext())
8058 .getExtValue();
8059 }
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00008060 if (ReqdWGS && Min == 0 && Max == 0)
8061 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00008062
8063 if (Min != 0) {
8064 assert(Min <= Max && "Min must be less than or equal Max");
8065
8066 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
8067 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8068 } else
8069 assert(Max == 0 && "Max must be zero");
Yaxun Liu1bea97c2019-09-03 18:50:24 +00008070 } else if (IsOpenCLKernel || IsHIPKernel) {
Matt Arsenaulteac783a2019-08-27 19:25:40 +00008071 // By default, restrict the maximum size to 256.
8072 F->addFnAttr("amdgpu-flat-work-group-size", "1,256");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008073 }
8074
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00008075 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
Michael Liao7557afa2019-02-26 18:49:36 +00008076 unsigned Min =
8077 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
8078 unsigned Max = Attr->getMax() ? Attr->getMax()
8079 ->EvaluateKnownConstInt(M.getContext())
8080 .getExtValue()
8081 : 0;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00008082
8083 if (Min != 0) {
8084 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
8085
8086 std::string AttrVal = llvm::utostr(Min);
8087 if (Max != 0)
8088 AttrVal = AttrVal + "," + llvm::utostr(Max);
8089 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
8090 } else
8091 assert(Max == 0 && "Max must be zero");
8092 }
8093
8094 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008095 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00008096
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008097 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00008098 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
8099 }
8100
8101 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
8102 uint32_t NumVGPR = Attr->getNumVGPR();
8103
8104 if (NumVGPR != 0)
8105 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008106 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00008107}
Tony Linthicum76329bf2011-12-12 21:14:55 +00008108
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008109unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8110 return llvm::CallingConv::AMDGPU_KERNEL;
8111}
8112
Yaxun Liu402804b2016-12-15 08:09:08 +00008113// Currently LLVM assumes null pointers always have value 0,
8114// which results in incorrectly transformed IR. Therefore, instead of
8115// emitting null pointers in private and local address spaces, a null
8116// pointer in generic address space is emitted which is casted to a
8117// pointer in local or private address space.
8118llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
8119 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
8120 QualType QT) const {
8121 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
8122 return llvm::ConstantPointerNull::get(PT);
8123
8124 auto &Ctx = CGM.getContext();
8125 auto NPT = llvm::PointerType::get(PT->getElementType(),
8126 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
8127 return llvm::ConstantExpr::getAddrSpaceCast(
8128 llvm::ConstantPointerNull::get(NPT), PT);
8129}
8130
Alexander Richardson6d989432017-10-15 18:48:14 +00008131LangAS
Yaxun Liucbf647c2017-07-08 13:24:52 +00008132AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
8133 const VarDecl *D) const {
8134 assert(!CGM.getLangOpts().OpenCL &&
8135 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
8136 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +00008137 LangAS DefaultGlobalAS = getLangASFromTargetAS(
8138 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
Yaxun Liucbf647c2017-07-08 13:24:52 +00008139 if (!D)
8140 return DefaultGlobalAS;
8141
Alexander Richardson6d989432017-10-15 18:48:14 +00008142 LangAS AddrSpace = D->getType().getAddressSpace();
8143 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
Yaxun Liucbf647c2017-07-08 13:24:52 +00008144 if (AddrSpace != LangAS::Default)
8145 return AddrSpace;
8146
8147 if (CGM.isTypeConstant(D->getType(), false)) {
8148 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
8149 return ConstAS.getValue();
8150 }
8151 return DefaultGlobalAS;
8152}
8153
Yaxun Liu39195062017-08-04 18:16:31 +00008154llvm::SyncScope::ID
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +00008155AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
8156 SyncScope Scope,
8157 llvm::AtomicOrdering Ordering,
8158 llvm::LLVMContext &Ctx) const {
8159 std::string Name;
8160 switch (Scope) {
Yaxun Liu39195062017-08-04 18:16:31 +00008161 case SyncScope::OpenCLWorkGroup:
8162 Name = "workgroup";
8163 break;
8164 case SyncScope::OpenCLDevice:
8165 Name = "agent";
8166 break;
8167 case SyncScope::OpenCLAllSVMDevices:
8168 Name = "";
8169 break;
8170 case SyncScope::OpenCLSubGroup:
Konstantin Zhuravlyov3161c892019-03-06 20:54:48 +00008171 Name = "wavefront";
Yaxun Liu39195062017-08-04 18:16:31 +00008172 }
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +00008173
8174 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
8175 if (!Name.empty())
8176 Name = Twine(Twine(Name) + Twine("-")).str();
8177
8178 Name = Twine(Twine(Name) + Twine("one-as")).str();
8179 }
8180
8181 return Ctx.getOrInsertSyncScopeID(Name);
Yaxun Liu39195062017-08-04 18:16:31 +00008182}
8183
Yaxun Liub0eee292018-03-29 14:50:00 +00008184bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
8185 return false;
8186}
8187
Yaxun Liu4306f202018-04-20 17:01:03 +00008188void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
Yaxun Liu6c10a662018-06-12 00:16:33 +00008189 const FunctionType *&FT) const {
8190 FT = getABIInfo().getContext().adjustFunctionType(
8191 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
Yaxun Liu4306f202018-04-20 17:01:03 +00008192}
8193
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008194//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008195// SPARC v8 ABI Implementation.
8196// Based on the SPARC Compliance Definition version 2.4.1.
8197//
8198// Ensures that complex values are passed in registers.
8199//
8200namespace {
8201class SparcV8ABIInfo : public DefaultABIInfo {
8202public:
8203 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8204
8205private:
8206 ABIArgInfo classifyReturnType(QualType RetTy) const;
8207 void computeInfo(CGFunctionInfo &FI) const override;
8208};
8209} // end anonymous namespace
8210
8211
8212ABIArgInfo
8213SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
8214 if (Ty->isAnyComplexType()) {
8215 return ABIArgInfo::getDirect();
8216 }
8217 else {
8218 return DefaultABIInfo::classifyReturnType(Ty);
8219 }
8220}
8221
8222void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8223
8224 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8225 for (auto &Arg : FI.arguments())
8226 Arg.info = classifyArgumentType(Arg.type);
8227}
8228
8229namespace {
8230class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
8231public:
8232 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
8233 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
8234};
8235} // end anonymous namespace
8236
8237//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008238// SPARC v9 ABI Implementation.
8239// Based on the SPARC Compliance Definition version 2.4.1.
8240//
8241// Function arguments a mapped to a nominal "parameter array" and promoted to
8242// registers depending on their type. Each argument occupies 8 or 16 bytes in
8243// the array, structs larger than 16 bytes are passed indirectly.
8244//
8245// One case requires special care:
8246//
8247// struct mixed {
8248// int i;
8249// float f;
8250// };
8251//
8252// When a struct mixed is passed by value, it only occupies 8 bytes in the
8253// parameter array, but the int is passed in an integer register, and the float
8254// is passed in a floating point register. This is represented as two arguments
8255// with the LLVM IR inreg attribute:
8256//
8257// declare void f(i32 inreg %i, float inreg %f)
8258//
8259// The code generator will only allocate 4 bytes from the parameter array for
8260// the inreg arguments. All other arguments are allocated a multiple of 8
8261// bytes.
8262//
8263namespace {
8264class SparcV9ABIInfo : public ABIInfo {
8265public:
8266 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
8267
8268private:
8269 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00008270 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00008271 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8272 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008273
8274 // Coercion type builder for structs passed in registers. The coercion type
8275 // serves two purposes:
8276 //
8277 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
8278 // in registers.
8279 // 2. Expose aligned floating point elements as first-level elements, so the
8280 // code generator knows to pass them in floating point registers.
8281 //
8282 // We also compute the InReg flag which indicates that the struct contains
8283 // aligned 32-bit floats.
8284 //
8285 struct CoerceBuilder {
8286 llvm::LLVMContext &Context;
8287 const llvm::DataLayout &DL;
8288 SmallVector<llvm::Type*, 8> Elems;
8289 uint64_t Size;
8290 bool InReg;
8291
8292 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
8293 : Context(c), DL(dl), Size(0), InReg(false) {}
8294
8295 // Pad Elems with integers until Size is ToSize.
8296 void pad(uint64_t ToSize) {
8297 assert(ToSize >= Size && "Cannot remove elements");
8298 if (ToSize == Size)
8299 return;
8300
8301 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00008302 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008303 if (Aligned > Size && Aligned <= ToSize) {
8304 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
8305 Size = Aligned;
8306 }
8307
8308 // Add whole 64-bit words.
8309 while (Size + 64 <= ToSize) {
8310 Elems.push_back(llvm::Type::getInt64Ty(Context));
8311 Size += 64;
8312 }
8313
8314 // Final in-word padding.
8315 if (Size < ToSize) {
8316 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
8317 Size = ToSize;
8318 }
8319 }
8320
8321 // Add a floating point element at Offset.
8322 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
8323 // Unaligned floats are treated as integers.
8324 if (Offset % Bits)
8325 return;
8326 // The InReg flag is only required if there are any floats < 64 bits.
8327 if (Bits < 64)
8328 InReg = true;
8329 pad(Offset);
8330 Elems.push_back(Ty);
8331 Size = Offset + Bits;
8332 }
8333
8334 // Add a struct type to the coercion type, starting at Offset (in bits).
8335 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
8336 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
8337 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
8338 llvm::Type *ElemTy = StrTy->getElementType(i);
8339 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
8340 switch (ElemTy->getTypeID()) {
8341 case llvm::Type::StructTyID:
8342 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
8343 break;
8344 case llvm::Type::FloatTyID:
8345 addFloat(ElemOffset, ElemTy, 32);
8346 break;
8347 case llvm::Type::DoubleTyID:
8348 addFloat(ElemOffset, ElemTy, 64);
8349 break;
8350 case llvm::Type::FP128TyID:
8351 addFloat(ElemOffset, ElemTy, 128);
8352 break;
8353 case llvm::Type::PointerTyID:
8354 if (ElemOffset % 64 == 0) {
8355 pad(ElemOffset);
8356 Elems.push_back(ElemTy);
8357 Size += 64;
8358 }
8359 break;
8360 default:
8361 break;
8362 }
8363 }
8364 }
8365
8366 // Check if Ty is a usable substitute for the coercion type.
8367 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00008368 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008369 }
8370
8371 // Get the coercion type as a literal struct type.
8372 llvm::Type *getType() const {
8373 if (Elems.size() == 1)
8374 return Elems.front();
8375 else
8376 return llvm::StructType::get(Context, Elems);
8377 }
8378 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008379};
8380} // end anonymous namespace
8381
8382ABIArgInfo
8383SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
8384 if (Ty->isVoidType())
8385 return ABIArgInfo::getIgnore();
8386
8387 uint64_t Size = getContext().getTypeSize(Ty);
8388
8389 // Anything too big to fit in registers is passed with an explicit indirect
8390 // pointer / sret pointer.
8391 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00008392 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008393
8394 // Treat an enum type as its underlying type.
8395 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8396 Ty = EnumTy->getDecl()->getIntegerType();
8397
8398 // Integer types smaller than a register are extended.
8399 if (Size < 64 && Ty->isIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00008400 return ABIArgInfo::getExtend(Ty);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008401
8402 // Other non-aggregates go in registers.
8403 if (!isAggregateTypeForABI(Ty))
8404 return ABIArgInfo::getDirect();
8405
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008406 // If a C++ object has either a non-trivial copy constructor or a non-trivial
8407 // destructor, it is passed with an explicit indirect pointer / sret pointer.
8408 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00008409 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008410
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008411 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008412 // Build a coercion type from the LLVM struct type.
8413 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8414 if (!StrTy)
8415 return ABIArgInfo::getDirect();
8416
8417 CoerceBuilder CB(getVMContext(), getDataLayout());
8418 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00008419 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008420
8421 // Try to use the original type for coercion.
8422 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8423
8424 if (CB.InReg)
8425 return ABIArgInfo::getDirectInReg(CoerceTy);
8426 else
8427 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008428}
8429
John McCall7f416cc2015-09-08 08:05:57 +00008430Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8431 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008432 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8433 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8434 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8435 AI.setCoerceToType(ArgTy);
8436
John McCall7f416cc2015-09-08 08:05:57 +00008437 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008438
John McCall7f416cc2015-09-08 08:05:57 +00008439 CGBuilderTy &Builder = CGF.Builder;
8440 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8441 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8442
8443 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8444
8445 Address ArgAddr = Address::invalid();
8446 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008447 switch (AI.getKind()) {
8448 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008449 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008450 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008451 llvm_unreachable("Unsupported ABI kind for va_arg");
8452
John McCall7f416cc2015-09-08 08:05:57 +00008453 case ABIArgInfo::Extend: {
8454 Stride = SlotSize;
8455 CharUnits Offset = SlotSize - TypeInfo.first;
8456 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008457 break;
John McCall7f416cc2015-09-08 08:05:57 +00008458 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008459
John McCall7f416cc2015-09-08 08:05:57 +00008460 case ABIArgInfo::Direct: {
8461 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008462 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008463 ArgAddr = Addr;
8464 break;
John McCall7f416cc2015-09-08 08:05:57 +00008465 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008466
8467 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008468 Stride = SlotSize;
8469 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8470 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8471 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008472 break;
8473
8474 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008475 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008476 }
8477
8478 // Update VAList.
James Y Knight3d2df5a2019-02-05 19:01:33 +00008479 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
8480 Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008481
John McCall7f416cc2015-09-08 08:05:57 +00008482 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008483}
8484
8485void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8486 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008487 for (auto &I : FI.arguments())
8488 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008489}
8490
8491namespace {
8492class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8493public:
8494 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8495 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008496
Craig Topper4f12f102014-03-12 06:41:41 +00008497 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008498 return 14;
8499 }
8500
8501 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008502 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008503};
8504} // end anonymous namespace
8505
Roman Divackyf02c9942014-02-24 18:46:27 +00008506bool
8507SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8508 llvm::Value *Address) const {
8509 // This is calculated from the LLVM and GCC tables and verified
8510 // against gcc output. AFAIK all ABIs use the same encoding.
8511
8512 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8513
8514 llvm::IntegerType *i8 = CGF.Int8Ty;
8515 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8516 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8517
8518 // 0-31: the 8-byte general-purpose registers
8519 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8520
8521 // 32-63: f0-31, the 4-byte floating-point registers
8522 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8523
8524 // Y = 64
8525 // PSR = 65
8526 // WIM = 66
8527 // TBR = 67
8528 // PC = 68
8529 // NPC = 69
8530 // FSR = 70
8531 // CSR = 71
8532 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008533
Roman Divackyf02c9942014-02-24 18:46:27 +00008534 // 72-87: d0-15, the 8-byte floating-point registers
8535 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8536
8537 return false;
8538}
8539
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008540// ARC ABI implementation.
8541namespace {
8542
8543class ARCABIInfo : public DefaultABIInfo {
8544public:
8545 using DefaultABIInfo::DefaultABIInfo;
8546
8547private:
8548 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8549 QualType Ty) const override;
8550
8551 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
8552 if (!State.FreeRegs)
8553 return;
8554 if (Info.isIndirect() && Info.getInReg())
8555 State.FreeRegs--;
8556 else if (Info.isDirect() && Info.getInReg()) {
8557 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
8558 if (sz < State.FreeRegs)
8559 State.FreeRegs -= sz;
8560 else
8561 State.FreeRegs = 0;
8562 }
8563 }
8564
8565 void computeInfo(CGFunctionInfo &FI) const override {
8566 CCState State(FI.getCallingConvention());
8567 // ARC uses 8 registers to pass arguments.
8568 State.FreeRegs = 8;
8569
8570 if (!getCXXABI().classifyReturnType(FI))
8571 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8572 updateState(FI.getReturnInfo(), FI.getReturnType(), State);
8573 for (auto &I : FI.arguments()) {
8574 I.info = classifyArgumentType(I.type, State.FreeRegs);
8575 updateState(I.info, I.type, State);
8576 }
8577 }
8578
8579 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
8580 ABIArgInfo getIndirectByValue(QualType Ty) const;
8581 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
8582 ABIArgInfo classifyReturnType(QualType RetTy) const;
8583};
8584
8585class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
8586public:
8587 ARCTargetCodeGenInfo(CodeGenTypes &CGT)
8588 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {}
8589};
8590
8591
8592ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
8593 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
8594 getNaturalAlignIndirect(Ty, false);
8595}
8596
8597ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
Daniel Dunbara39bab32019-01-03 23:24:50 +00008598 // Compute the byval alignment.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008599 const unsigned MinABIStackAlignInBytes = 4;
8600 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8601 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8602 TypeAlign > MinABIStackAlignInBytes);
8603}
8604
8605Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8606 QualType Ty) const {
8607 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8608 getContext().getTypeInfoInChars(Ty),
8609 CharUnits::fromQuantity(4), true);
8610}
8611
8612ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
8613 uint8_t FreeRegs) const {
8614 // Handle the generic C++ ABI.
8615 const RecordType *RT = Ty->getAs<RecordType>();
8616 if (RT) {
8617 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8618 if (RAA == CGCXXABI::RAA_Indirect)
8619 return getIndirectByRef(Ty, FreeRegs > 0);
8620
8621 if (RAA == CGCXXABI::RAA_DirectInMemory)
8622 return getIndirectByValue(Ty);
8623 }
8624
8625 // Treat an enum type as its underlying type.
8626 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8627 Ty = EnumTy->getDecl()->getIntegerType();
8628
8629 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
8630
8631 if (isAggregateTypeForABI(Ty)) {
8632 // Structures with flexible arrays are always indirect.
8633 if (RT && RT->getDecl()->hasFlexibleArrayMember())
8634 return getIndirectByValue(Ty);
8635
8636 // Ignore empty structs/unions.
8637 if (isEmptyRecord(getContext(), Ty, true))
8638 return ABIArgInfo::getIgnore();
8639
8640 llvm::LLVMContext &LLVMContext = getVMContext();
8641
8642 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8643 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8644 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8645
8646 return FreeRegs >= SizeInRegs ?
8647 ABIArgInfo::getDirectInReg(Result) :
8648 ABIArgInfo::getDirect(Result, 0, nullptr, false);
8649 }
8650
8651 return Ty->isPromotableIntegerType() ?
8652 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) :
8653 ABIArgInfo::getExtend(Ty)) :
8654 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() :
8655 ABIArgInfo::getDirect());
8656}
8657
8658ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
8659 if (RetTy->isAnyComplexType())
8660 return ABIArgInfo::getDirectInReg();
8661
Daniel Dunbara39bab32019-01-03 23:24:50 +00008662 // Arguments of size > 4 registers are indirect.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008663 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
8664 if (RetSize > 4)
8665 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
8666
8667 return DefaultABIInfo::classifyReturnType(RetTy);
8668}
8669
8670} // End anonymous namespace.
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008671
Robert Lytton0e076492013-08-13 09:43:10 +00008672//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008673// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008674//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008675
Robert Lytton0e076492013-08-13 09:43:10 +00008676namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008677
8678/// A SmallStringEnc instance is used to build up the TypeString by passing
8679/// it by reference between functions that append to it.
8680typedef llvm::SmallString<128> SmallStringEnc;
8681
8682/// TypeStringCache caches the meta encodings of Types.
8683///
8684/// The reason for caching TypeStrings is two fold:
8685/// 1. To cache a type's encoding for later uses;
8686/// 2. As a means to break recursive member type inclusion.
8687///
8688/// A cache Entry can have a Status of:
8689/// NonRecursive: The type encoding is not recursive;
8690/// Recursive: The type encoding is recursive;
8691/// Incomplete: An incomplete TypeString;
8692/// IncompleteUsed: An incomplete TypeString that has been used in a
8693/// Recursive type encoding.
8694///
8695/// A NonRecursive entry will have all of its sub-members expanded as fully
8696/// as possible. Whilst it may contain types which are recursive, the type
8697/// itself is not recursive and thus its encoding may be safely used whenever
8698/// the type is encountered.
8699///
8700/// A Recursive entry will have all of its sub-members expanded as fully as
8701/// possible. The type itself is recursive and it may contain other types which
8702/// are recursive. The Recursive encoding must not be used during the expansion
8703/// of a recursive type's recursive branch. For simplicity the code uses
8704/// IncompleteCount to reject all usage of Recursive encodings for member types.
8705///
8706/// An Incomplete entry is always a RecordType and only encodes its
8707/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8708/// are placed into the cache during type expansion as a means to identify and
8709/// handle recursive inclusion of types as sub-members. If there is recursion
8710/// the entry becomes IncompleteUsed.
8711///
8712/// During the expansion of a RecordType's members:
8713///
8714/// If the cache contains a NonRecursive encoding for the member type, the
8715/// cached encoding is used;
8716///
8717/// If the cache contains a Recursive encoding for the member type, the
8718/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8719///
8720/// If the member is a RecordType, an Incomplete encoding is placed into the
8721/// cache to break potential recursive inclusion of itself as a sub-member;
8722///
8723/// Once a member RecordType has been expanded, its temporary incomplete
8724/// entry is removed from the cache. If a Recursive encoding was swapped out
8725/// it is swapped back in;
8726///
8727/// If an incomplete entry is used to expand a sub-member, the incomplete
8728/// entry is marked as IncompleteUsed. The cache keeps count of how many
8729/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8730///
8731/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8732/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8733/// Else the member is part of a recursive type and thus the recursion has
8734/// been exited too soon for the encoding to be correct for the member.
8735///
8736class TypeStringCache {
8737 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8738 struct Entry {
8739 std::string Str; // The encoded TypeString for the type.
8740 enum Status State; // Information about the encoding in 'Str'.
8741 std::string Swapped; // A temporary place holder for a Recursive encoding
8742 // during the expansion of RecordType's members.
8743 };
8744 std::map<const IdentifierInfo *, struct Entry> Map;
8745 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8746 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8747public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008748 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008749 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8750 bool removeIncomplete(const IdentifierInfo *ID);
8751 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8752 bool IsRecursive);
8753 StringRef lookupStr(const IdentifierInfo *ID);
8754};
8755
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008756/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008757/// FieldEncoding is a helper for this ordering process.
8758class FieldEncoding {
8759 bool HasName;
8760 std::string Enc;
8761public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008762 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008763 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008764 bool operator<(const FieldEncoding &rhs) const {
8765 if (HasName != rhs.HasName) return HasName;
8766 return Enc < rhs.Enc;
8767 }
8768};
8769
Robert Lytton7d1db152013-08-19 09:46:39 +00008770class XCoreABIInfo : public DefaultABIInfo {
8771public:
8772 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008773 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8774 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008775};
8776
Robert Lyttond21e2d72014-03-03 13:45:29 +00008777class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008778 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008779public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008780 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008781 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008782 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8783 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008784};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008785
Robert Lytton2d196952013-10-11 10:29:34 +00008786} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008787
James Y Knight29b5f082016-02-24 02:59:33 +00008788// TODO: this implementation is likely now redundant with the default
8789// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008790Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8791 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008792 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008793
Robert Lytton2d196952013-10-11 10:29:34 +00008794 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008795 CharUnits SlotSize = CharUnits::fromQuantity(4);
8796 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008797
Robert Lytton2d196952013-10-11 10:29:34 +00008798 // Handle the argument.
8799 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008800 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008801 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8802 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8803 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008804 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008805
8806 Address Val = Address::invalid();
8807 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008808 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008809 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008810 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008811 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008812 llvm_unreachable("Unsupported ABI kind for va_arg");
8813 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008814 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8815 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008816 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008817 case ABIArgInfo::Extend:
8818 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008819 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8820 ArgSize = CharUnits::fromQuantity(
8821 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008822 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008823 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008824 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008825 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8826 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8827 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008828 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008829 }
Robert Lytton2d196952013-10-11 10:29:34 +00008830
8831 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008832 if (!ArgSize.isZero()) {
James Y Knight3d2df5a2019-02-05 19:01:33 +00008833 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
8834 Builder.CreateStore(APN.getPointer(), VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008835 }
John McCall7f416cc2015-09-08 08:05:57 +00008836
Robert Lytton2d196952013-10-11 10:29:34 +00008837 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008838}
Robert Lytton0e076492013-08-13 09:43:10 +00008839
Robert Lytton844aeeb2014-05-02 09:33:20 +00008840/// During the expansion of a RecordType, an incomplete TypeString is placed
8841/// into the cache as a means to identify and break recursion.
8842/// If there is a Recursive encoding in the cache, it is swapped out and will
8843/// be reinserted by removeIncomplete().
8844/// All other types of encoding should have been used rather than arriving here.
8845void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8846 std::string StubEnc) {
8847 if (!ID)
8848 return;
8849 Entry &E = Map[ID];
8850 assert( (E.Str.empty() || E.State == Recursive) &&
8851 "Incorrectly use of addIncomplete");
8852 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8853 E.Swapped.swap(E.Str); // swap out the Recursive
8854 E.Str.swap(StubEnc);
8855 E.State = Incomplete;
8856 ++IncompleteCount;
8857}
8858
8859/// Once the RecordType has been expanded, the temporary incomplete TypeString
8860/// must be removed from the cache.
8861/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8862/// Returns true if the RecordType was defined recursively.
8863bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8864 if (!ID)
8865 return false;
8866 auto I = Map.find(ID);
8867 assert(I != Map.end() && "Entry not present");
8868 Entry &E = I->second;
8869 assert( (E.State == Incomplete ||
8870 E.State == IncompleteUsed) &&
8871 "Entry must be an incomplete type");
8872 bool IsRecursive = false;
8873 if (E.State == IncompleteUsed) {
8874 // We made use of our Incomplete encoding, thus we are recursive.
8875 IsRecursive = true;
8876 --IncompleteUsedCount;
8877 }
8878 if (E.Swapped.empty())
8879 Map.erase(I);
8880 else {
8881 // Swap the Recursive back.
8882 E.Swapped.swap(E.Str);
8883 E.Swapped.clear();
8884 E.State = Recursive;
8885 }
8886 --IncompleteCount;
8887 return IsRecursive;
8888}
8889
8890/// Add the encoded TypeString to the cache only if it is NonRecursive or
8891/// Recursive (viz: all sub-members were expanded as fully as possible).
8892void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8893 bool IsRecursive) {
8894 if (!ID || IncompleteUsedCount)
8895 return; // No key or it is is an incomplete sub-type so don't add.
8896 Entry &E = Map[ID];
8897 if (IsRecursive && !E.Str.empty()) {
8898 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8899 "This is not the same Recursive entry");
8900 // The parent container was not recursive after all, so we could have used
8901 // this Recursive sub-member entry after all, but we assumed the worse when
8902 // we started viz: IncompleteCount!=0.
8903 return;
8904 }
8905 assert(E.Str.empty() && "Entry already present");
8906 E.Str = Str.str();
8907 E.State = IsRecursive? Recursive : NonRecursive;
8908}
8909
8910/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8911/// are recursively expanding a type (IncompleteCount != 0) and the cached
8912/// encoding is Recursive, return an empty StringRef.
8913StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8914 if (!ID)
8915 return StringRef(); // We have no key.
8916 auto I = Map.find(ID);
8917 if (I == Map.end())
8918 return StringRef(); // We have no encoding.
8919 Entry &E = I->second;
8920 if (E.State == Recursive && IncompleteCount)
8921 return StringRef(); // We don't use Recursive encodings for member types.
8922
8923 if (E.State == Incomplete) {
8924 // The incomplete type is being used to break out of recursion.
8925 E.State = IncompleteUsed;
8926 ++IncompleteUsedCount;
8927 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008928 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008929}
8930
8931/// The XCore ABI includes a type information section that communicates symbol
8932/// type information to the linker. The linker uses this information to verify
8933/// safety/correctness of things such as array bound and pointers et al.
8934/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8935/// This type information (TypeString) is emitted into meta data for all global
8936/// symbols: definitions, declarations, functions & variables.
8937///
8938/// The TypeString carries type, qualifier, name, size & value details.
8939/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008940/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008941/// The output is tested by test/CodeGen/xcore-stringtype.c.
8942///
8943static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8944 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8945
8946/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8947void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8948 CodeGen::CodeGenModule &CGM) const {
8949 SmallStringEnc Enc;
8950 if (getTypeString(Enc, D, CGM, TSC)) {
8951 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008952 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8953 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008954 llvm::NamedMDNode *MD =
8955 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8956 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8957 }
8958}
8959
Xiuli Pan972bea82016-03-24 03:57:17 +00008960//===----------------------------------------------------------------------===//
8961// SPIR ABI Implementation
8962//===----------------------------------------------------------------------===//
8963
8964namespace {
8965class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8966public:
8967 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8968 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008969 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008970};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008971
Xiuli Pan972bea82016-03-24 03:57:17 +00008972} // End anonymous namespace.
8973
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008974namespace clang {
8975namespace CodeGen {
8976void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8977 DefaultABIInfo SPIRABI(CGM.getTypes());
8978 SPIRABI.computeInfo(FI);
8979}
8980}
8981}
8982
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008983unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8984 return llvm::CallingConv::SPIR_KERNEL;
8985}
8986
Robert Lytton844aeeb2014-05-02 09:33:20 +00008987static bool appendType(SmallStringEnc &Enc, QualType QType,
8988 const CodeGen::CodeGenModule &CGM,
8989 TypeStringCache &TSC);
8990
8991/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008992/// Builds a SmallVector containing the encoded field types in declaration
8993/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008994static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8995 const RecordDecl *RD,
8996 const CodeGen::CodeGenModule &CGM,
8997 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008998 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008999 SmallStringEnc Enc;
9000 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00009001 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00009002 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00009003 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00009004 Enc += "b(";
9005 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00009006 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00009007 Enc += ':';
9008 }
Hans Wennborga302cd92014-08-21 16:06:57 +00009009 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00009010 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00009011 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00009012 Enc += ')';
9013 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00009014 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00009015 }
9016 return true;
9017}
9018
9019/// Appends structure and union types to Enc and adds encoding to cache.
9020/// Recursively calls appendType (via extractFieldType) for each field.
9021/// Union types have their fields ordered according to the ABI.
9022static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
9023 const CodeGen::CodeGenModule &CGM,
9024 TypeStringCache &TSC, const IdentifierInfo *ID) {
9025 // Append the cached TypeString if we have one.
9026 StringRef TypeString = TSC.lookupStr(ID);
9027 if (!TypeString.empty()) {
9028 Enc += TypeString;
9029 return true;
9030 }
9031
9032 // Start to emit an incomplete TypeString.
9033 size_t Start = Enc.size();
9034 Enc += (RT->isUnionType()? 'u' : 's');
9035 Enc += '(';
9036 if (ID)
9037 Enc += ID->getName();
9038 Enc += "){";
9039
9040 // We collect all encoded fields and order as necessary.
9041 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00009042 const RecordDecl *RD = RT->getDecl()->getDefinition();
9043 if (RD && !RD->field_empty()) {
9044 // An incomplete TypeString stub is placed in the cache for this RecordType
9045 // so that recursive calls to this RecordType will use it whilst building a
9046 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00009047 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00009048 std::string StubEnc(Enc.substr(Start).str());
9049 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
9050 TSC.addIncomplete(ID, std::move(StubEnc));
9051 if (!extractFieldType(FE, RD, CGM, TSC)) {
9052 (void) TSC.removeIncomplete(ID);
9053 return false;
9054 }
9055 IsRecursive = TSC.removeIncomplete(ID);
9056 // The ABI requires unions to be sorted but not structures.
9057 // See FieldEncoding::operator< for sort algorithm.
9058 if (RT->isUnionType())
Fangrui Song55fab262018-09-26 22:16:28 +00009059 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00009060 // We can now complete the TypeString.
9061 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00009062 for (unsigned I = 0; I != E; ++I) {
9063 if (I)
9064 Enc += ',';
9065 Enc += FE[I].str();
9066 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00009067 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00009068 Enc += '}';
9069 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
9070 return true;
9071}
9072
9073/// Appends enum types to Enc and adds the encoding to the cache.
9074static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
9075 TypeStringCache &TSC,
9076 const IdentifierInfo *ID) {
9077 // Append the cached TypeString if we have one.
9078 StringRef TypeString = TSC.lookupStr(ID);
9079 if (!TypeString.empty()) {
9080 Enc += TypeString;
9081 return true;
9082 }
9083
9084 size_t Start = Enc.size();
9085 Enc += "e(";
9086 if (ID)
9087 Enc += ID->getName();
9088 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00009089
9090 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00009091 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00009092 SmallVector<FieldEncoding, 16> FE;
9093 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
9094 ++I) {
9095 SmallStringEnc EnumEnc;
9096 EnumEnc += "m(";
9097 EnumEnc += I->getName();
9098 EnumEnc += "){";
9099 I->getInitVal().toString(EnumEnc);
9100 EnumEnc += '}';
9101 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
9102 }
Fangrui Song55fab262018-09-26 22:16:28 +00009103 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00009104 unsigned E = FE.size();
9105 for (unsigned I = 0; I != E; ++I) {
9106 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00009107 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00009108 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00009109 }
9110 }
9111 Enc += '}';
9112 TSC.addIfComplete(ID, Enc.substr(Start), false);
9113 return true;
9114}
9115
9116/// Appends type's qualifier to Enc.
9117/// This is done prior to appending the type's encoding.
9118static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
9119 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00009120 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00009121 int Lookup = 0;
9122 if (QT.isConstQualified())
9123 Lookup += 1<<0;
9124 if (QT.isRestrictQualified())
9125 Lookup += 1<<1;
9126 if (QT.isVolatileQualified())
9127 Lookup += 1<<2;
9128 Enc += Table[Lookup];
9129}
9130
9131/// Appends built-in types to Enc.
9132static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
9133 const char *EncType;
9134 switch (BT->getKind()) {
9135 case BuiltinType::Void:
9136 EncType = "0";
9137 break;
9138 case BuiltinType::Bool:
9139 EncType = "b";
9140 break;
9141 case BuiltinType::Char_U:
9142 EncType = "uc";
9143 break;
9144 case BuiltinType::UChar:
9145 EncType = "uc";
9146 break;
9147 case BuiltinType::SChar:
9148 EncType = "sc";
9149 break;
9150 case BuiltinType::UShort:
9151 EncType = "us";
9152 break;
9153 case BuiltinType::Short:
9154 EncType = "ss";
9155 break;
9156 case BuiltinType::UInt:
9157 EncType = "ui";
9158 break;
9159 case BuiltinType::Int:
9160 EncType = "si";
9161 break;
9162 case BuiltinType::ULong:
9163 EncType = "ul";
9164 break;
9165 case BuiltinType::Long:
9166 EncType = "sl";
9167 break;
9168 case BuiltinType::ULongLong:
9169 EncType = "ull";
9170 break;
9171 case BuiltinType::LongLong:
9172 EncType = "sll";
9173 break;
9174 case BuiltinType::Float:
9175 EncType = "ft";
9176 break;
9177 case BuiltinType::Double:
9178 EncType = "d";
9179 break;
9180 case BuiltinType::LongDouble:
9181 EncType = "ld";
9182 break;
9183 default:
9184 return false;
9185 }
9186 Enc += EncType;
9187 return true;
9188}
9189
9190/// Appends a pointer encoding to Enc before calling appendType for the pointee.
9191static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
9192 const CodeGen::CodeGenModule &CGM,
9193 TypeStringCache &TSC) {
9194 Enc += "p(";
9195 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
9196 return false;
9197 Enc += ')';
9198 return true;
9199}
9200
9201/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00009202static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
9203 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00009204 const CodeGen::CodeGenModule &CGM,
9205 TypeStringCache &TSC, StringRef NoSizeEnc) {
9206 if (AT->getSizeModifier() != ArrayType::Normal)
9207 return false;
9208 Enc += "a(";
9209 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
9210 CAT->getSize().toStringUnsigned(Enc);
9211 else
9212 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
9213 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00009214 // The Qualifiers should be attached to the type rather than the array.
9215 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00009216 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
9217 return false;
9218 Enc += ')';
9219 return true;
9220}
9221
9222/// Appends a function encoding to Enc, calling appendType for the return type
9223/// and the arguments.
9224static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
9225 const CodeGen::CodeGenModule &CGM,
9226 TypeStringCache &TSC) {
9227 Enc += "f{";
9228 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
9229 return false;
9230 Enc += "}(";
9231 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
9232 // N.B. we are only interested in the adjusted param types.
9233 auto I = FPT->param_type_begin();
9234 auto E = FPT->param_type_end();
9235 if (I != E) {
9236 do {
9237 if (!appendType(Enc, *I, CGM, TSC))
9238 return false;
9239 ++I;
9240 if (I != E)
9241 Enc += ',';
9242 } while (I != E);
9243 if (FPT->isVariadic())
9244 Enc += ",va";
9245 } else {
9246 if (FPT->isVariadic())
9247 Enc += "va";
9248 else
9249 Enc += '0';
9250 }
9251 }
9252 Enc += ')';
9253 return true;
9254}
9255
9256/// Handles the type's qualifier before dispatching a call to handle specific
9257/// type encodings.
9258static bool appendType(SmallStringEnc &Enc, QualType QType,
9259 const CodeGen::CodeGenModule &CGM,
9260 TypeStringCache &TSC) {
9261
9262 QualType QT = QType.getCanonicalType();
9263
Robert Lytton6adb20f2014-06-05 09:06:21 +00009264 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
9265 // The Qualifiers should be attached to the type rather than the array.
9266 // Thus we don't call appendQualifier() here.
9267 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
9268
Robert Lytton844aeeb2014-05-02 09:33:20 +00009269 appendQualifier(Enc, QT);
9270
9271 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
9272 return appendBuiltinType(Enc, BT);
9273
Robert Lytton844aeeb2014-05-02 09:33:20 +00009274 if (const PointerType *PT = QT->getAs<PointerType>())
9275 return appendPointerType(Enc, PT, CGM, TSC);
9276
9277 if (const EnumType *ET = QT->getAs<EnumType>())
9278 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
9279
9280 if (const RecordType *RT = QT->getAsStructureType())
9281 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9282
9283 if (const RecordType *RT = QT->getAsUnionType())
9284 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9285
9286 if (const FunctionType *FT = QT->getAs<FunctionType>())
9287 return appendFunctionType(Enc, FT, CGM, TSC);
9288
9289 return false;
9290}
9291
9292static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9293 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
9294 if (!D)
9295 return false;
9296
9297 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9298 if (FD->getLanguageLinkage() != CLanguageLinkage)
9299 return false;
9300 return appendType(Enc, FD->getType(), CGM, TSC);
9301 }
9302
9303 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9304 if (VD->getLanguageLinkage() != CLanguageLinkage)
9305 return false;
9306 QualType QT = VD->getType().getCanonicalType();
9307 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
9308 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00009309 // The Qualifiers should be attached to the type rather than the array.
9310 // Thus we don't call appendQualifier() here.
9311 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00009312 }
9313 return appendType(Enc, QT, CGM, TSC);
9314 }
9315 return false;
9316}
9317
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009318//===----------------------------------------------------------------------===//
9319// RISCV ABI Implementation
9320//===----------------------------------------------------------------------===//
9321
9322namespace {
9323class RISCVABIInfo : public DefaultABIInfo {
9324private:
Alex Bradburye078967a2019-07-18 18:29:59 +00009325 // Size of the integer ('x') registers in bits.
9326 unsigned XLen;
9327 // Size of the floating point ('f') registers in bits. Note that the target
9328 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
9329 // with soft float ABI has FLen==0).
9330 unsigned FLen;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009331 static const int NumArgGPRs = 8;
Alex Bradburye078967a2019-07-18 18:29:59 +00009332 static const int NumArgFPRs = 8;
9333 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
9334 llvm::Type *&Field1Ty,
9335 CharUnits &Field1Off,
9336 llvm::Type *&Field2Ty,
9337 CharUnits &Field2Off) const;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009338
9339public:
Alex Bradburye078967a2019-07-18 18:29:59 +00009340 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
9341 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009342
9343 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
9344 // non-virtual, but computeInfo is virtual, so we overload it.
9345 void computeInfo(CGFunctionInfo &FI) const override;
9346
Alex Bradburye078967a2019-07-18 18:29:59 +00009347 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
9348 int &ArgFPRsLeft) const;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009349 ABIArgInfo classifyReturnType(QualType RetTy) const;
9350
9351 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9352 QualType Ty) const override;
9353
9354 ABIArgInfo extendType(QualType Ty) const;
Alex Bradburye078967a2019-07-18 18:29:59 +00009355
9356 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
9357 CharUnits &Field1Off, llvm::Type *&Field2Ty,
9358 CharUnits &Field2Off, int &NeededArgGPRs,
9359 int &NeededArgFPRs) const;
9360 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
9361 CharUnits Field1Off,
9362 llvm::Type *Field2Ty,
9363 CharUnits Field2Off) const;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009364};
9365} // end anonymous namespace
9366
9367void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
9368 QualType RetTy = FI.getReturnType();
9369 if (!getCXXABI().classifyReturnType(FI))
9370 FI.getReturnInfo() = classifyReturnType(RetTy);
9371
9372 // IsRetIndirect is true if classifyArgumentType indicated the value should
9373 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128
9374 // is passed direct in LLVM IR, relying on the backend lowering code to
9375 // rewrite the argument list and pass indirectly on RV32.
9376 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect ||
9377 getContext().getTypeSize(RetTy) > (2 * XLen);
9378
9379 // We must track the number of GPRs used in order to conform to the RISC-V
9380 // ABI, as integer scalars passed in registers should have signext/zeroext
9381 // when promoted, but are anyext if passed on the stack. As GPR usage is
9382 // different for variadic arguments, we must also track whether we are
9383 // examining a vararg or not.
9384 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
Alex Bradburye078967a2019-07-18 18:29:59 +00009385 int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009386 int NumFixedArgs = FI.getNumRequiredArgs();
9387
9388 int ArgNum = 0;
9389 for (auto &ArgInfo : FI.arguments()) {
9390 bool IsFixed = ArgNum < NumFixedArgs;
Alex Bradburye078967a2019-07-18 18:29:59 +00009391 ArgInfo.info =
9392 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009393 ArgNum++;
9394 }
9395}
9396
Alex Bradburye078967a2019-07-18 18:29:59 +00009397// Returns true if the struct is a potential candidate for the floating point
9398// calling convention. If this function returns true, the caller is
9399// responsible for checking that if there is only a single field then that
9400// field is a float.
9401bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
9402 llvm::Type *&Field1Ty,
9403 CharUnits &Field1Off,
9404 llvm::Type *&Field2Ty,
9405 CharUnits &Field2Off) const {
9406 bool IsInt = Ty->isIntegralOrEnumerationType();
9407 bool IsFloat = Ty->isRealFloatingType();
9408
9409 if (IsInt || IsFloat) {
9410 uint64_t Size = getContext().getTypeSize(Ty);
9411 if (IsInt && Size > XLen)
9412 return false;
9413 // Can't be eligible if larger than the FP registers. Half precision isn't
9414 // currently supported on RISC-V and the ABI hasn't been confirmed, so
9415 // default to the integer ABI in that case.
9416 if (IsFloat && (Size > FLen || Size < 32))
9417 return false;
9418 // Can't be eligible if an integer type was already found (int+int pairs
9419 // are not eligible).
9420 if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
9421 return false;
9422 if (!Field1Ty) {
9423 Field1Ty = CGT.ConvertType(Ty);
9424 Field1Off = CurOff;
9425 return true;
9426 }
9427 if (!Field2Ty) {
9428 Field2Ty = CGT.ConvertType(Ty);
9429 Field2Off = CurOff;
9430 return true;
9431 }
9432 return false;
9433 }
9434
9435 if (auto CTy = Ty->getAs<ComplexType>()) {
9436 if (Field1Ty)
9437 return false;
9438 QualType EltTy = CTy->getElementType();
9439 if (getContext().getTypeSize(EltTy) > FLen)
9440 return false;
9441 Field1Ty = CGT.ConvertType(EltTy);
9442 Field1Off = CurOff;
9443 assert(CurOff.isZero() && "Unexpected offset for first field");
9444 Field2Ty = Field1Ty;
9445 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
9446 return true;
9447 }
9448
9449 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
9450 uint64_t ArraySize = ATy->getSize().getZExtValue();
9451 QualType EltTy = ATy->getElementType();
9452 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
9453 for (uint64_t i = 0; i < ArraySize; ++i) {
9454 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
9455 Field1Off, Field2Ty, Field2Off);
9456 if (!Ret)
9457 return false;
9458 CurOff += EltSize;
9459 }
9460 return true;
9461 }
9462
9463 if (const auto *RTy = Ty->getAs<RecordType>()) {
9464 // Structures with either a non-trivial destructor or a non-trivial
9465 // copy constructor are not eligible for the FP calling convention.
Denis Bakhvalova29002e2019-07-19 21:59:42 +00009466 if (getRecordArgABI(Ty, CGT.getCXXABI()))
Alex Bradburye078967a2019-07-18 18:29:59 +00009467 return false;
9468 if (isEmptyRecord(getContext(), Ty, true))
9469 return true;
9470 const RecordDecl *RD = RTy->getDecl();
9471 // Unions aren't eligible unless they're empty (which is caught above).
9472 if (RD->isUnion())
9473 return false;
9474 int ZeroWidthBitFieldCount = 0;
9475 for (const FieldDecl *FD : RD->fields()) {
9476 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
9477 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
9478 QualType QTy = FD->getType();
9479 if (FD->isBitField()) {
9480 unsigned BitWidth = FD->getBitWidthValue(getContext());
9481 // Allow a bitfield with a type greater than XLen as long as the
9482 // bitwidth is XLen or less.
9483 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
9484 QTy = getContext().getIntTypeForBitwidth(XLen, false);
9485 if (BitWidth == 0) {
9486 ZeroWidthBitFieldCount++;
9487 continue;
9488 }
9489 }
9490
9491 bool Ret = detectFPCCEligibleStructHelper(
9492 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
9493 Field1Ty, Field1Off, Field2Ty, Field2Off);
9494 if (!Ret)
9495 return false;
9496
9497 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
9498 // or int+fp structs, but are ignored for a struct with an fp field and
9499 // any number of zero-width bitfields.
9500 if (Field2Ty && ZeroWidthBitFieldCount > 0)
9501 return false;
9502 }
9503 return Field1Ty != nullptr;
9504 }
9505
9506 return false;
9507}
9508
9509// Determine if a struct is eligible for passing according to the floating
9510// point calling convention (i.e., when flattened it contains a single fp
9511// value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
9512// NeededArgGPRs are incremented appropriately.
9513bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
9514 CharUnits &Field1Off,
9515 llvm::Type *&Field2Ty,
9516 CharUnits &Field2Off,
9517 int &NeededArgGPRs,
9518 int &NeededArgFPRs) const {
9519 Field1Ty = nullptr;
9520 Field2Ty = nullptr;
9521 NeededArgGPRs = 0;
9522 NeededArgFPRs = 0;
9523 bool IsCandidate = detectFPCCEligibleStructHelper(
9524 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
9525 // Not really a candidate if we have a single int but no float.
9526 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
Sylvestre Ledrufb190c82019-10-08 09:17:46 +00009527 return false;
Alex Bradburye078967a2019-07-18 18:29:59 +00009528 if (!IsCandidate)
9529 return false;
9530 if (Field1Ty && Field1Ty->isFloatingPointTy())
9531 NeededArgFPRs++;
9532 else if (Field1Ty)
9533 NeededArgGPRs++;
9534 if (Field2Ty && Field2Ty->isFloatingPointTy())
9535 NeededArgFPRs++;
9536 else if (Field2Ty)
9537 NeededArgGPRs++;
9538 return IsCandidate;
9539}
9540
9541// Call getCoerceAndExpand for the two-element flattened struct described by
9542// Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
9543// appropriate coerceToType and unpaddedCoerceToType.
9544ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
9545 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
9546 CharUnits Field2Off) const {
9547 SmallVector<llvm::Type *, 3> CoerceElts;
9548 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
9549 if (!Field1Off.isZero())
9550 CoerceElts.push_back(llvm::ArrayType::get(
9551 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
9552
9553 CoerceElts.push_back(Field1Ty);
9554 UnpaddedCoerceElts.push_back(Field1Ty);
9555
9556 if (!Field2Ty) {
9557 return ABIArgInfo::getCoerceAndExpand(
9558 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
9559 UnpaddedCoerceElts[0]);
9560 }
9561
9562 CharUnits Field2Align =
9563 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
9564 CharUnits Field1Size =
9565 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
9566 CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align);
9567
9568 CharUnits Padding = CharUnits::Zero();
9569 if (Field2Off > Field2OffNoPadNoPack)
9570 Padding = Field2Off - Field2OffNoPadNoPack;
9571 else if (Field2Off != Field2Align && Field2Off > Field1Size)
9572 Padding = Field2Off - Field1Size;
9573
9574 bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
9575
9576 if (!Padding.isZero())
9577 CoerceElts.push_back(llvm::ArrayType::get(
9578 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
9579
9580 CoerceElts.push_back(Field2Ty);
9581 UnpaddedCoerceElts.push_back(Field2Ty);
9582
9583 auto CoerceToType =
9584 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
9585 auto UnpaddedCoerceToType =
9586 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
9587
9588 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
9589}
9590
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009591ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
Alex Bradburye078967a2019-07-18 18:29:59 +00009592 int &ArgGPRsLeft,
9593 int &ArgFPRsLeft) const {
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009594 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
9595 Ty = useFirstFieldIfTransparentUnion(Ty);
9596
9597 // Structures with either a non-trivial destructor or a non-trivial
9598 // copy constructor are always passed indirectly.
9599 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
9600 if (ArgGPRsLeft)
9601 ArgGPRsLeft -= 1;
9602 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
9603 CGCXXABI::RAA_DirectInMemory);
9604 }
9605
9606 // Ignore empty structs/unions.
9607 if (isEmptyRecord(getContext(), Ty, true))
9608 return ABIArgInfo::getIgnore();
9609
9610 uint64_t Size = getContext().getTypeSize(Ty);
Alex Bradburye078967a2019-07-18 18:29:59 +00009611
9612 // Pass floating point values via FPRs if possible.
9613 if (IsFixed && Ty->isFloatingType() && FLen >= Size && ArgFPRsLeft) {
9614 ArgFPRsLeft--;
9615 return ABIArgInfo::getDirect();
9616 }
9617
9618 // Complex types for the hard float ABI must be passed direct rather than
9619 // using CoerceAndExpand.
9620 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00009621 QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
Alex Bradburye078967a2019-07-18 18:29:59 +00009622 if (getContext().getTypeSize(EltTy) <= FLen) {
9623 ArgFPRsLeft -= 2;
9624 return ABIArgInfo::getDirect();
9625 }
9626 }
9627
9628 if (IsFixed && FLen && Ty->isStructureOrClassType()) {
9629 llvm::Type *Field1Ty = nullptr;
9630 llvm::Type *Field2Ty = nullptr;
9631 CharUnits Field1Off = CharUnits::Zero();
9632 CharUnits Field2Off = CharUnits::Zero();
9633 int NeededArgGPRs;
9634 int NeededArgFPRs;
9635 bool IsCandidate =
9636 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
9637 NeededArgGPRs, NeededArgFPRs);
9638 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
9639 NeededArgFPRs <= ArgFPRsLeft) {
9640 ArgGPRsLeft -= NeededArgGPRs;
9641 ArgFPRsLeft -= NeededArgFPRs;
9642 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
9643 Field2Off);
9644 }
9645 }
9646
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009647 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
9648 bool MustUseStack = false;
9649 // Determine the number of GPRs needed to pass the current argument
9650 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
9651 // register pairs, so may consume 3 registers.
9652 int NeededArgGPRs = 1;
9653 if (!IsFixed && NeededAlign == 2 * XLen)
9654 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
9655 else if (Size > XLen && Size <= 2 * XLen)
9656 NeededArgGPRs = 2;
9657
9658 if (NeededArgGPRs > ArgGPRsLeft) {
9659 MustUseStack = true;
9660 NeededArgGPRs = ArgGPRsLeft;
9661 }
9662
9663 ArgGPRsLeft -= NeededArgGPRs;
9664
9665 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
9666 // Treat an enum type as its underlying type.
9667 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9668 Ty = EnumTy->getDecl()->getIntegerType();
9669
9670 // All integral types are promoted to XLen width, unless passed on the
9671 // stack.
9672 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
9673 return extendType(Ty);
9674 }
9675
9676 return ABIArgInfo::getDirect();
9677 }
9678
9679 // Aggregates which are <= 2*XLen will be passed in registers if possible,
9680 // so coerce to integers.
9681 if (Size <= 2 * XLen) {
9682 unsigned Alignment = getContext().getTypeAlign(Ty);
9683
9684 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
9685 // required, and a 2-element XLen array if only XLen alignment is required.
9686 if (Size <= XLen) {
9687 return ABIArgInfo::getDirect(
9688 llvm::IntegerType::get(getVMContext(), XLen));
9689 } else if (Alignment == 2 * XLen) {
9690 return ABIArgInfo::getDirect(
9691 llvm::IntegerType::get(getVMContext(), 2 * XLen));
9692 } else {
9693 return ABIArgInfo::getDirect(llvm::ArrayType::get(
9694 llvm::IntegerType::get(getVMContext(), XLen), 2));
9695 }
9696 }
9697 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9698}
9699
9700ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
9701 if (RetTy->isVoidType())
9702 return ABIArgInfo::getIgnore();
9703
9704 int ArgGPRsLeft = 2;
Alex Bradburye078967a2019-07-18 18:29:59 +00009705 int ArgFPRsLeft = FLen ? 2 : 0;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009706
9707 // The rules for return and argument types are the same, so defer to
9708 // classifyArgumentType.
Alex Bradburye078967a2019-07-18 18:29:59 +00009709 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
9710 ArgFPRsLeft);
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009711}
9712
9713Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9714 QualType Ty) const {
9715 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
9716
9717 // Empty records are ignored for parameter passing purposes.
9718 if (isEmptyRecord(getContext(), Ty, true)) {
9719 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
9720 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
9721 return Addr;
9722 }
9723
9724 std::pair<CharUnits, CharUnits> SizeAndAlign =
9725 getContext().getTypeInfoInChars(Ty);
9726
9727 // Arguments bigger than 2*Xlen bytes are passed indirectly.
9728 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
9729
9730 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
9731 SlotSize, /*AllowHigherAlign=*/true);
9732}
9733
9734ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
9735 int TySize = getContext().getTypeSize(Ty);
9736 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
9737 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
9738 return ABIArgInfo::getSignExtend(Ty);
9739 return ABIArgInfo::getExtend(Ty);
9740}
9741
9742namespace {
9743class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
9744public:
Alex Bradburye078967a2019-07-18 18:29:59 +00009745 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
9746 unsigned FLen)
9747 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen, FLen)) {}
Ana Pazos1eee1b72018-07-26 17:37:45 +00009748
9749 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9750 CodeGen::CodeGenModule &CGM) const override {
9751 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
9752 if (!FD) return;
9753
9754 const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
9755 if (!Attr)
9756 return;
9757
9758 const char *Kind;
9759 switch (Attr->getInterrupt()) {
9760 case RISCVInterruptAttr::user: Kind = "user"; break;
9761 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
9762 case RISCVInterruptAttr::machine: Kind = "machine"; break;
9763 }
9764
9765 auto *Fn = cast<llvm::Function>(GV);
9766
9767 Fn->addFnAttr("interrupt", Kind);
9768 }
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009769};
9770} // namespace
Robert Lytton844aeeb2014-05-02 09:33:20 +00009771
Robert Lytton0e076492013-08-13 09:43:10 +00009772//===----------------------------------------------------------------------===//
9773// Driver code
9774//===----------------------------------------------------------------------===//
9775
Rafael Espindola9f834732014-09-19 01:54:22 +00009776bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00009777 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00009778}
9779
Chris Lattner2b037972010-07-29 02:01:43 +00009780const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009781 if (TheTargetCodeGenInfo)
9782 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009783
Reid Kleckner9305fd12016-04-13 23:37:17 +00009784 // Helper to set the unique_ptr while still keeping the return value.
9785 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
9786 this->TheTargetCodeGenInfo.reset(P);
9787 return *P;
9788 };
9789
John McCallc8e01702013-04-16 22:48:15 +00009790 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00009791 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00009792 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009793 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00009794
Derek Schuff09338a22012-09-06 17:37:28 +00009795 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009796 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00009797 case llvm::Triple::mips:
9798 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00009799 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00009800 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9801 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009802
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00009803 case llvm::Triple::mips64:
9804 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009805 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009806
Dylan McKaye8232d72017-02-08 05:09:26 +00009807 case llvm::Triple::avr:
9808 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
9809
Tim Northover25e8a672014-05-24 12:51:25 +00009810 case llvm::Triple::aarch64:
Tim Northover44e58792018-09-18 10:34:39 +01009811 case llvm::Triple::aarch64_32:
Tim Northover40956e62014-07-23 12:32:58 +00009812 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00009813 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00009814 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00009815 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00009816 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00009817 return SetCGInfo(
9818 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00009819
Reid Kleckner9305fd12016-04-13 23:37:17 +00009820 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00009821 }
9822
Dan Gohmanc2853072015-09-03 22:51:53 +00009823 case llvm::Triple::wasm32:
9824 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009825 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00009826
Daniel Dunbard59655c2009-09-12 00:59:49 +00009827 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00009828 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00009829 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009830 case llvm::Triple::thumbeb: {
9831 if (Triple.getOS() == llvm::Triple::Win32) {
9832 return SetCGInfo(
9833 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00009834 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00009835
Reid Kleckner9305fd12016-04-13 23:37:17 +00009836 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9837 StringRef ABIStr = getTarget().getABI();
9838 if (ABIStr == "apcs-gnu")
9839 Kind = ARMABIInfo::APCS;
9840 else if (ABIStr == "aapcs16")
9841 Kind = ARMABIInfo::AAPCS16_VFP;
9842 else if (CodeGenOpts.FloatABI == "hard" ||
9843 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009844 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00009845 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009846 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00009847 Kind = ARMABIInfo::AAPCS_VFP;
9848
9849 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9850 }
9851
John McCallea8d8bb2010-03-11 00:10:12 +00009852 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009853 return SetCGInfo(
Justin Hibbits3dac2142019-09-05 13:38:46 +00009854 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft" ||
9855 getTarget().hasFeature("spe")));
Roman Divackyd966e722012-05-09 18:22:46 +00009856 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00009857 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00009858 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00009859 if (getTarget().getABI() == "elfv2")
9860 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009861 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009862 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009863
Hal Finkel415c2a32016-10-02 02:10:45 +00009864 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9865 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009866 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00009867 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009868 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00009869 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00009870 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009871 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00009872 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009873 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009874 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009875
Hal Finkel415c2a32016-10-02 02:10:45 +00009876 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9877 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009878 }
John McCallea8d8bb2010-03-11 00:10:12 +00009879
Peter Collingbournec947aae2012-05-20 23:28:41 +00009880 case llvm::Triple::nvptx:
9881 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009882 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00009883
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009884 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009885 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00009886
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009887 case llvm::Triple::riscv32:
Alex Bradburye078967a2019-07-18 18:29:59 +00009888 case llvm::Triple::riscv64: {
9889 StringRef ABIStr = getTarget().getABI();
9890 unsigned XLen = getTarget().getPointerWidth(0);
9891 unsigned ABIFLen = 0;
9892 if (ABIStr.endswith("f"))
9893 ABIFLen = 32;
9894 else if (ABIStr.endswith("d"))
9895 ABIFLen = 64;
9896 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
9897 }
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009898
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009899 case llvm::Triple::systemz: {
9900 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00009901 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009902 }
Ulrich Weigand47445072013-05-06 16:26:41 +00009903
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009904 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00009905 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009906 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009907
Eli Friedman33465822011-07-08 23:31:17 +00009908 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00009909 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00009910 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00009911 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00009912 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00009913
John McCall1fe2a8c2013-06-18 02:46:29 +00009914 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009915 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9916 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9917 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00009918 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009919 return SetCGInfo(new X86_32TargetCodeGenInfo(
9920 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9921 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
Hans Wennborgd874c052019-06-19 11:34:08 +00009922 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009923 }
Eli Friedman33465822011-07-08 23:31:17 +00009924 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009925
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009926 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009927 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00009928 X86AVXABILevel AVXLevel =
9929 (ABI == "avx512"
9930 ? X86AVXABILevel::AVX512
9931 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009932
Chris Lattner04dc9572010-08-31 16:44:54 +00009933 switch (Triple.getOS()) {
9934 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009935 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009936 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009937 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009938 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00009939 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00009940 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009941 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00009942 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009943 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00009944 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009945 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00009946 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009947 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00009948 case llvm::Triple::sparc:
9949 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00009950 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009951 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00009952 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009953 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00009954 case llvm::Triple::arc:
9955 return SetCGInfo(new ARCTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00009956 case llvm::Triple::spir:
9957 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009958 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009959 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009960}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009961
9962/// Create an OpenCL kernel for an enqueued block.
9963///
9964/// The kernel has the same function type as the block invoke function. Its
9965/// name is the name of the block invoke function postfixed with "_kernel".
9966/// It simply calls the block invoke function then returns.
9967llvm::Function *
9968TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
9969 llvm::Function *Invoke,
9970 llvm::Value *BlockLiteral) const {
9971 auto *InvokeFT = Invoke->getFunctionType();
9972 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9973 for (auto &P : InvokeFT->params())
9974 ArgTys.push_back(P);
9975 auto &C = CGF.getLLVMContext();
9976 std::string Name = Invoke->getName().str() + "_kernel";
9977 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9978 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9979 &CGF.CGM.getModule());
9980 auto IP = CGF.Builder.saveIP();
9981 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9982 auto &Builder = CGF.Builder;
9983 Builder.SetInsertPoint(BB);
9984 llvm::SmallVector<llvm::Value *, 2> Args;
9985 for (auto &A : F->args())
9986 Args.push_back(&A);
9987 Builder.CreateCall(Invoke, Args);
9988 Builder.CreateRetVoid();
9989 Builder.restoreIP(IP);
9990 return F;
9991}
9992
9993/// Create an OpenCL kernel for an enqueued block.
9994///
9995/// The type of the first argument (the block literal) is the struct type
9996/// of the block literal instead of a pointer type. The first argument
9997/// (block literal) is passed directly by value to the kernel. The kernel
9998/// allocates the same type of struct on stack and stores the block literal
9999/// to it and passes its pointer to the block invoke function. The kernel
10000/// has "enqueued-block" function attribute and kernel argument metadata.
10001llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
10002 CodeGenFunction &CGF, llvm::Function *Invoke,
10003 llvm::Value *BlockLiteral) const {
10004 auto &Builder = CGF.Builder;
10005 auto &C = CGF.getLLVMContext();
10006
10007 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
10008 auto *InvokeFT = Invoke->getFunctionType();
10009 llvm::SmallVector<llvm::Type *, 2> ArgTys;
10010 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
10011 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
10012 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
10013 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
10014 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
10015 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
10016
10017 ArgTys.push_back(BlockTy);
10018 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10019 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
10020 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10021 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10022 AccessQuals.push_back(llvm::MDString::get(C, "none"));
10023 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
10024 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
10025 ArgTys.push_back(InvokeFT->getParamType(I));
Yaxun Liuc2a87a02017-10-14 12:23:50 +000010026 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
10027 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
10028 AccessQuals.push_back(llvm::MDString::get(C, "none"));
10029 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
10030 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10031 ArgNames.push_back(
Yaxun Liu98f0c432017-10-14 12:51:52 +000010032 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
Yaxun Liuc2a87a02017-10-14 12:23:50 +000010033 }
10034 std::string Name = Invoke->getName().str() + "_kernel";
10035 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
10036 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
10037 &CGF.CGM.getModule());
10038 F->addFnAttr("enqueued-block");
10039 auto IP = CGF.Builder.saveIP();
10040 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
10041 Builder.SetInsertPoint(BB);
10042 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
10043 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
Guillaume Chateletab11b912019-09-30 13:34:44 +000010044 BlockPtr->setAlignment(llvm::MaybeAlign(BlockAlign));
Yaxun Liuc2a87a02017-10-14 12:23:50 +000010045 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
10046 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
10047 llvm::SmallVector<llvm::Value *, 2> Args;
10048 Args.push_back(Cast);
10049 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
10050 Args.push_back(I);
10051 Builder.CreateCall(Invoke, Args);
10052 Builder.CreateRetVoid();
10053 Builder.restoreIP(IP);
10054
10055 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
10056 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
10057 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
10058 F->setMetadata("kernel_arg_base_type",
10059 llvm::MDNode::get(C, ArgBaseTypeNames));
10060 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
10061 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
10062 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
10063
10064 return F;
10065}