blob: 89ec73670a7350b09ae57b6548cb4339234456a6 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Yaxun Liuc2a87a02017-10-14 12:23:50 +000017#include "CGBlocks.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000018#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000019#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000020#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000032#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000033
Anton Korobeynikov244360d2009-06-05 22:08:42 +000034using namespace clang;
35using namespace CodeGen;
36
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +000037// Helper for coercing an aggregate argument or return value into an integer
38// array of the same size (including padding) and alignment. This alternate
39// coercion happens only for the RenderScript ABI and can be removed after
40// runtimes that rely on it are no longer supported.
41//
42// RenderScript assumes that the size of the argument / return value in the IR
43// is the same as the size of the corresponding qualified type. This helper
44// coerces the aggregate type into an array of the same size (including
45// padding). This coercion is used in lieu of expansion of struct members or
46// other canonical coercions that return a coerced-type of larger size.
47//
48// Ty - The argument / return value type
49// Context - The associated ASTContext
50// LLVMContext - The associated LLVMContext
51static ABIArgInfo coerceToIntArray(QualType Ty,
52 ASTContext &Context,
53 llvm::LLVMContext &LLVMContext) {
54 // Alignment and Size are measured in bits.
55 const uint64_t Size = Context.getTypeSize(Ty);
56 const uint64_t Alignment = Context.getTypeAlign(Ty);
57 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
58 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
59 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
60}
61
John McCall943fae92010-05-27 06:19:26 +000062static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
63 llvm::Value *Array,
64 llvm::Value *Value,
65 unsigned FirstIndex,
66 unsigned LastIndex) {
67 // Alternatively, we could emit this as a loop in the source.
68 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000069 llvm::Value *Cell =
70 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000071 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000072 }
73}
74
John McCalla1dee5302010-08-22 10:59:02 +000075static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000076 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000077 T->isMemberFunctionPointerType();
78}
79
John McCall7f416cc2015-09-08 08:05:57 +000080ABIArgInfo
81ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
82 llvm::Type *Padding) const {
83 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
84 ByRef, Realign, Padding);
85}
86
87ABIArgInfo
88ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
89 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
90 /*ByRef*/ false, Realign);
91}
92
Charles Davisc7d5c942015-09-17 20:55:33 +000093Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
94 QualType Ty) const {
95 return Address::invalid();
96}
97
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000098ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000099
John McCall12f23522016-04-04 18:33:08 +0000100/// Does the given lowering require more than the given number of
101/// registers when expanded?
102///
103/// This is intended to be the basis of a reasonable basic implementation
104/// of should{Pass,Return}IndirectlyForSwift.
105///
106/// For most targets, a limit of four total registers is reasonable; this
107/// limits the amount of code required in order to move around the value
108/// in case it wasn't produced immediately prior to the call by the caller
109/// (or wasn't produced in exactly the right registers) or isn't used
110/// immediately within the callee. But some targets may need to further
111/// limit the register count due to an inability to support that many
112/// return registers.
113static bool occupiesMoreThan(CodeGenTypes &cgt,
114 ArrayRef<llvm::Type*> scalarTypes,
115 unsigned maxAllRegisters) {
116 unsigned intCount = 0, fpCount = 0;
117 for (llvm::Type *type : scalarTypes) {
118 if (type->isPointerTy()) {
119 intCount++;
120 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
121 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
122 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
123 } else {
124 assert(type->isVectorTy() || type->isFloatingPointTy());
125 fpCount++;
126 }
127 }
128
129 return (intCount + fpCount > maxAllRegisters);
130}
131
132bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
133 llvm::Type *eltTy,
134 unsigned numElts) const {
135 // The default implementation of this assumes that the target guarantees
136 // 128-bit SIMD support but nothing more.
137 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
138}
139
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000140static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000141 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000142 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
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);
John McCall7f416cc2015-09-08 08:05:57 +0000313 llvm::Value *NextPtr =
314 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
315 "argp.next");
316 CGF.Builder.CreateStore(NextPtr, VAListAddr);
317
318 // If the argument is smaller than a slot, and this is a big-endian
319 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000320 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
321 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000322 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
323 }
324
325 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
326 return Addr;
327}
328
329/// Emit va_arg for a platform using the common void* representation,
330/// where arguments are simply emitted in an array of slots on the stack.
331///
332/// \param IsIndirect - Values of this type are passed indirectly.
333/// \param ValueInfo - The size and alignment of this type, generally
334/// computed with getContext().getTypeInfoInChars(ValueTy).
335/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
336/// Each argument will be allocated to a multiple of this number of
337/// slots, and all the slots will be aligned to this value.
338/// \param AllowHigherAlign - The slot alignment is not a cap;
339/// an argument type with an alignment greater than the slot size
340/// will be emitted on a higher-alignment address, potentially
341/// leaving one or more empty slots behind as padding.
342static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
343 QualType ValueTy, bool IsIndirect,
344 std::pair<CharUnits, CharUnits> ValueInfo,
345 CharUnits SlotSizeAndAlign,
346 bool AllowHigherAlign) {
347 // The size and alignment of the value that was passed directly.
348 CharUnits DirectSize, DirectAlign;
349 if (IsIndirect) {
350 DirectSize = CGF.getPointerSize();
351 DirectAlign = CGF.getPointerAlign();
352 } else {
353 DirectSize = ValueInfo.first;
354 DirectAlign = ValueInfo.second;
355 }
356
357 // Cast the address we've calculated to the right type.
358 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
359 if (IsIndirect)
360 DirectTy = DirectTy->getPointerTo(0);
361
362 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
363 DirectSize, DirectAlign,
364 SlotSizeAndAlign,
365 AllowHigherAlign);
366
367 if (IsIndirect) {
368 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
369 }
370
371 return Addr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000372
John McCall7f416cc2015-09-08 08:05:57 +0000373}
374
375static Address emitMergePHI(CodeGenFunction &CGF,
376 Address Addr1, llvm::BasicBlock *Block1,
377 Address Addr2, llvm::BasicBlock *Block2,
378 const llvm::Twine &Name = "") {
379 assert(Addr1.getType() == Addr2.getType());
380 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
381 PHI->addIncoming(Addr1.getPointer(), Block1);
382 PHI->addIncoming(Addr2.getPointer(), Block2);
383 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
384 return Address(PHI, Align);
385}
386
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000387TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
388
John McCall3480ef22011-08-30 01:42:09 +0000389// If someone can figure out a general rule for this, that would be great.
390// It's probably just doomed to be platform-dependent, though.
391unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
392 // Verified for:
393 // x86-64 FreeBSD, Linux, Darwin
394 // x86-32 FreeBSD, Linux, Darwin
395 // PowerPC Linux, Darwin
396 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000397 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000398 return 32;
399}
400
John McCalla729c622012-02-17 03:33:10 +0000401bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
402 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000403 // The following conventions are known to require this to be false:
404 // x86_stdcall
405 // MIPS
406 // For everything else, we just prefer false unless we opt out.
407 return false;
408}
409
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000410void
411TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
412 llvm::SmallString<24> &Opt) const {
413 // This assumes the user is passing a library name like "rt" instead of a
414 // filename like "librt.a/so", and that they don't care whether it's static or
415 // dynamic.
416 Opt = "-l";
417 Opt += Lib;
418}
419
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000420unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000421 // OpenCL kernels are called via an explicit runtime API with arguments
422 // set with clSetKernelArg(), not as normal sub-functions.
423 // Return SPIR_KERNEL by default as the kernel calling convention to
424 // ensure the fingerprint is fixed such way that each OpenCL argument
425 // gets one matching argument in the produced kernel function argument
426 // list to enable feasible implementation of clSetKernelArg() with
427 // aggregates etc. In case we would use the default C calling conv here,
428 // clSetKernelArg() might break depending on the target-specific
429 // conventions; different targets might split structs passed as values
430 // to multiple function arguments etc.
431 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000432}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000433
Yaxun Liu402804b2016-12-15 08:09:08 +0000434llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
435 llvm::PointerType *T, QualType QT) const {
436 return llvm::ConstantPointerNull::get(T);
437}
438
Alexander Richardson6d989432017-10-15 18:48:14 +0000439LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
440 const VarDecl *D) const {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000441 assert(!CGM.getLangOpts().OpenCL &&
442 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
443 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +0000444 return D ? D->getType().getAddressSpace() : LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000445}
446
Yaxun Liu402804b2016-12-15 08:09:08 +0000447llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Alexander Richardson6d989432017-10-15 18:48:14 +0000448 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
449 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000450 // Since target may map different address spaces in AST to the same address
451 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000452 if (auto *C = dyn_cast<llvm::Constant>(Src))
453 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000454 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000455}
456
Yaxun Liucbf647c2017-07-08 13:24:52 +0000457llvm::Constant *
458TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
Alexander Richardson6d989432017-10-15 18:48:14 +0000459 LangAS SrcAddr, LangAS DestAddr,
Yaxun Liucbf647c2017-07-08 13:24:52 +0000460 llvm::Type *DestTy) const {
461 // Since target may map different address spaces in AST to the same address
462 // space, an address space conversion may end up as a bitcast.
463 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
464}
465
Yaxun Liu39195062017-08-04 18:16:31 +0000466llvm::SyncScope::ID
467TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
468 return C.getOrInsertSyncScopeID(""); /* default sync scope */
469}
470
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000471static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000472
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000473/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000474/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000475static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
476 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000477 if (FD->isUnnamedBitfield())
478 return true;
479
480 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000481
Eli Friedman0b3f2012011-11-18 03:47:20 +0000482 // Constant arrays of empty records count as empty, strip them off.
483 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000484 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000485 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
486 if (AT->getSize() == 0)
487 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000488 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000489 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000490
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000491 const RecordType *RT = FT->getAs<RecordType>();
492 if (!RT)
493 return false;
494
495 // C++ record fields are never empty, at least in the Itanium ABI.
496 //
497 // FIXME: We should use a predicate for whether this behavior is true in the
498 // current ABI.
499 if (isa<CXXRecordDecl>(RT->getDecl()))
500 return false;
501
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000502 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000503}
504
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000505/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000506/// fields. Note that a structure with a flexible array member is not
507/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000508static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000509 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000510 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000511 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000512 const RecordDecl *RD = RT->getDecl();
513 if (RD->hasFlexibleArrayMember())
514 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000515
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000516 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000517 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000518 for (const auto &I : CXXRD->bases())
519 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000520 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000521
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000522 for (const auto *I : RD->fields())
523 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000524 return false;
525 return true;
526}
527
528/// isSingleElementStruct - Determine if a structure is a "single
529/// element struct", i.e. it has exactly one non-empty field or
530/// exactly one field which is itself a single element
531/// struct. Structures with flexible array members are never
532/// considered single element structs.
533///
534/// \return The field declaration for the single non-empty field, if
535/// it exists.
536static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000537 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000538 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000539 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000540
541 const RecordDecl *RD = RT->getDecl();
542 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000543 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000544
Craig Topper8a13c412014-05-21 05:09:00 +0000545 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000546
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000547 // If this is a C++ record, check the bases first.
548 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000549 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000550 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000551 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000552 continue;
553
554 // If we already found an element then this isn't a single-element struct.
555 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000556 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000557
558 // If this is non-empty and not a single element struct, the composite
559 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000560 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000561 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000562 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000563 }
564 }
565
566 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000567 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000568 QualType FT = FD->getType();
569
570 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000571 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000572 continue;
573
574 // If we already found an element then this isn't a single-element
575 // struct.
576 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000577 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578
579 // Treat single element arrays as the element.
580 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
581 if (AT->getSize().getZExtValue() != 1)
582 break;
583 FT = AT->getElementType();
584 }
585
John McCalla1dee5302010-08-22 10:59:02 +0000586 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000587 Found = FT.getTypePtr();
588 } else {
589 Found = isSingleElementStruct(FT, Context);
590 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000591 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000592 }
593 }
594
Eli Friedmanee945342011-11-18 01:25:50 +0000595 // We don't consider a struct a single-element struct if it has
596 // padding beyond the element type.
597 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000598 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000599
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000600 return Found;
601}
602
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000603namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000604Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
605 const ABIArgInfo &AI) {
606 // This default implementation defers to the llvm backend's va_arg
607 // instruction. It can handle only passing arguments directly
608 // (typically only handled in the backend for primitive types), or
609 // aggregates passed indirectly by pointer (NOTE: if the "byval"
610 // flag has ABI impact in the callee, this implementation cannot
611 // work.)
612
613 // Only a few cases are covered here at the moment -- those needed
614 // by the default abi.
615 llvm::Value *Val;
616
617 if (AI.isIndirect()) {
618 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000619 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000620 assert(
621 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000622 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000623
624 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
625 CharUnits TyAlignForABI = TyInfo.second;
626
627 llvm::Type *BaseTy =
628 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
629 llvm::Value *Addr =
630 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
631 return Address(Addr, TyAlignForABI);
632 } else {
633 assert((AI.isDirect() || AI.isExtend()) &&
634 "Unexpected ArgInfo Kind in generic VAArg emitter!");
635
636 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000637 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000638 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000639 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000640 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000641 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000642 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000643 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000644
645 Address Temp = CGF.CreateMemTemp(Ty, "varet");
646 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
647 CGF.Builder.CreateStore(Val, Temp);
648 return Temp;
649 }
650}
651
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000652/// DefaultABIInfo - The default implementation for ABI specific
653/// details. This implementation provides information which results in
654/// self-consistent and sensible LLVM IR generation, but does not
655/// conform to any particular ABI.
656class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000657public:
658 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000659
Chris Lattner458b2aa2010-07-29 02:16:43 +0000660 ABIArgInfo classifyReturnType(QualType RetTy) const;
661 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000662
Craig Topper4f12f102014-03-12 06:41:41 +0000663 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000664 if (!getCXXABI().classifyReturnType(FI))
665 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000666 for (auto &I : FI.arguments())
667 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000668 }
669
John McCall7f416cc2015-09-08 08:05:57 +0000670 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000671 QualType Ty) const override {
672 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
673 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000674};
675
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000676class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
677public:
Chris Lattner2b037972010-07-29 02:01:43 +0000678 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
679 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000680};
681
Chris Lattner458b2aa2010-07-29 02:16:43 +0000682ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000683 Ty = useFirstFieldIfTransparentUnion(Ty);
684
685 if (isAggregateTypeForABI(Ty)) {
686 // Records with non-trivial destructors/copy-constructors should not be
687 // passed by value.
688 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000689 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000690
John McCall7f416cc2015-09-08 08:05:57 +0000691 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000692 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000693
Chris Lattner9723d6c2010-03-11 18:19:55 +0000694 // Treat an enum type as its underlying type.
695 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
696 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000697
Alex Bradburye41a5e22018-01-12 20:08:16 +0000698 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
699 : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000700}
701
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000702ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
703 if (RetTy->isVoidType())
704 return ABIArgInfo::getIgnore();
705
706 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000707 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000708
709 // Treat an enum type as its underlying type.
710 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
711 RetTy = EnumTy->getDecl()->getIntegerType();
712
Alex Bradburye41a5e22018-01-12 20:08:16 +0000713 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
714 : ABIArgInfo::getDirect());
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000715}
716
Derek Schuff09338a22012-09-06 17:37:28 +0000717//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000718// WebAssembly ABI Implementation
719//
720// This is a very simple ABI that relies a lot on DefaultABIInfo.
721//===----------------------------------------------------------------------===//
722
Daniel Dunbara39bab32019-01-03 23:24:50 +0000723class WebAssemblyABIInfo final : public SwiftABIInfo {
724 DefaultABIInfo defaultInfo;
725
Dan Gohmanc2853072015-09-03 22:51:53 +0000726public:
727 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
Daniel Dunbara39bab32019-01-03 23:24:50 +0000728 : SwiftABIInfo(CGT), defaultInfo(CGT) {}
Dan Gohmanc2853072015-09-03 22:51:53 +0000729
730private:
731 ABIArgInfo classifyReturnType(QualType RetTy) const;
732 ABIArgInfo classifyArgumentType(QualType Ty) const;
733
734 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000735 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000736 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000737 void computeInfo(CGFunctionInfo &FI) const override {
738 if (!getCXXABI().classifyReturnType(FI))
739 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
740 for (auto &Arg : FI.arguments())
741 Arg.info = classifyArgumentType(Arg.type);
742 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000743
744 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
745 QualType Ty) const override;
Daniel Dunbara39bab32019-01-03 23:24:50 +0000746
747 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
748 bool asReturnValue) const override {
749 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
750 }
751
752 bool isSwiftErrorInRegister() const override {
753 return false;
754 }
Dan Gohmanc2853072015-09-03 22:51:53 +0000755};
756
757class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
758public:
759 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
760 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
Sam Clegg6fd7d682018-06-25 18:47:32 +0000761
762 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
763 CodeGen::CodeGenModule &CGM) const override {
764 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
765 llvm::Function *Fn = cast<llvm::Function>(GV);
766 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
767 Fn->addFnAttr("no-prototype");
768 }
769 }
Dan Gohmanc2853072015-09-03 22:51:53 +0000770};
771
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000772/// Classify argument of given type \p Ty.
Dan Gohmanc2853072015-09-03 22:51:53 +0000773ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
774 Ty = useFirstFieldIfTransparentUnion(Ty);
775
776 if (isAggregateTypeForABI(Ty)) {
777 // Records with non-trivial destructors/copy-constructors should not be
778 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000779 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000780 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000781 // Ignore empty structs/unions.
782 if (isEmptyRecord(getContext(), Ty, true))
783 return ABIArgInfo::getIgnore();
784 // Lower single-element structs to just pass a regular value. TODO: We
785 // could do reasonable-size multiple-element structs too, using getExpand(),
786 // though watch out for things like bitfields.
787 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
788 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000789 }
790
791 // Otherwise just do the default thing.
Daniel Dunbara39bab32019-01-03 23:24:50 +0000792 return defaultInfo.classifyArgumentType(Ty);
Dan Gohmanc2853072015-09-03 22:51:53 +0000793}
794
795ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
796 if (isAggregateTypeForABI(RetTy)) {
797 // Records with non-trivial destructors/copy-constructors should not be
798 // returned by value.
799 if (!getRecordArgABI(RetTy, getCXXABI())) {
800 // Ignore empty structs/unions.
801 if (isEmptyRecord(getContext(), RetTy, true))
802 return ABIArgInfo::getIgnore();
803 // Lower single-element structs to just return a regular value. TODO: We
804 // could do reasonable-size multiple-element structs too, using
805 // ABIArgInfo::getDirect().
806 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
807 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
808 }
809 }
810
811 // Otherwise just do the default thing.
Daniel Dunbara39bab32019-01-03 23:24:50 +0000812 return defaultInfo.classifyReturnType(RetTy);
Dan Gohmanc2853072015-09-03 22:51:53 +0000813}
814
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000815Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
816 QualType Ty) const {
817 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
818 getContext().getTypeInfoInChars(Ty),
819 CharUnits::fromQuantity(4),
820 /*AllowHigherAlign=*/ true);
821}
822
Dan Gohmanc2853072015-09-03 22:51:53 +0000823//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000824// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000825//
826// This is a simplified version of the x86_32 ABI. Arguments and return values
827// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000828//===----------------------------------------------------------------------===//
829
830class PNaClABIInfo : public ABIInfo {
831 public:
832 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
833
834 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000835 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000836
Craig Topper4f12f102014-03-12 06:41:41 +0000837 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000838 Address EmitVAArg(CodeGenFunction &CGF,
839 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000840};
841
842class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
843 public:
844 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
845 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
846};
847
848void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000849 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000850 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
851
Reid Kleckner40ca9132014-05-13 22:05:45 +0000852 for (auto &I : FI.arguments())
853 I.info = classifyArgumentType(I.type);
854}
Derek Schuff09338a22012-09-06 17:37:28 +0000855
John McCall7f416cc2015-09-08 08:05:57 +0000856Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
857 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000858 // The PNaCL ABI is a bit odd, in that varargs don't use normal
859 // function classification. Structs get passed directly for varargs
860 // functions, through a rewriting transform in
861 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
862 // this target to actually support a va_arg instructions with an
863 // aggregate type, unlike other targets.
864 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000865}
866
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000867/// Classify argument of given type \p Ty.
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000868ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000869 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000870 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000871 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
872 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000873 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
874 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000875 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000876 } else if (Ty->isFloatingType()) {
877 // Floating-point types don't go inreg.
878 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000879 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000880
Alex Bradburye41a5e22018-01-12 20:08:16 +0000881 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
882 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000883}
884
885ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
886 if (RetTy->isVoidType())
887 return ABIArgInfo::getIgnore();
888
Eli Benderskye20dad62013-04-04 22:49:35 +0000889 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000890 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000891 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000892
893 // Treat an enum type as its underlying type.
894 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
895 RetTy = EnumTy->getDecl()->getIntegerType();
896
Alex Bradburye41a5e22018-01-12 20:08:16 +0000897 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
898 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000899}
900
Chad Rosier651c1832013-03-25 21:00:27 +0000901/// IsX86_MMXType - Return true if this is an MMX type.
902bool IsX86_MMXType(llvm::Type *IRType) {
903 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendling5cd41c42010-10-18 03:41:31 +0000904 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
905 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
906 IRType->getScalarSizeInBits() != 64;
907}
908
Jay Foad7c57be32011-07-11 09:56:20 +0000909static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000910 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000911 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000912 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
913 .Cases("y", "&y", "^Ym", true)
914 .Default(false);
915 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000916 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
917 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000918 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000919 }
920
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000921 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000922 }
923
924 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000925 return Ty;
926}
927
Reid Kleckner80944df2014-10-31 22:00:51 +0000928/// Returns true if this type can be passed in SSE registers with the
929/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
930static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
931 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000932 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
933 if (BT->getKind() == BuiltinType::LongDouble) {
934 if (&Context.getTargetInfo().getLongDoubleFormat() ==
935 &llvm::APFloat::x87DoubleExtended())
936 return false;
937 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000938 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000939 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000940 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
941 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
942 // registers specially.
943 unsigned VecSize = Context.getTypeSize(VT);
944 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
945 return true;
946 }
947 return false;
948}
949
950/// Returns true if this aggregate is small enough to be passed in SSE registers
951/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
952static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
953 return NumMembers <= 4;
954}
955
Erich Keane521ed962017-01-05 00:20:51 +0000956/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
957static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
958 auto AI = ABIArgInfo::getDirect(T);
959 AI.setInReg(true);
960 AI.setCanBeFlattened(false);
961 return AI;
962}
963
Chris Lattner0cf24192010-06-28 20:05:43 +0000964//===----------------------------------------------------------------------===//
965// X86-32 ABI Implementation
966//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000967
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000968/// Similar to llvm::CCState, but for Clang.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000969struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000970 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000971
972 unsigned CC;
973 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000974 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000975};
976
Erich Keane521ed962017-01-05 00:20:51 +0000977enum {
978 // Vectorcall only allows the first 6 parameters to be passed in registers.
979 VectorcallMaxParamNumAsReg = 6
980};
981
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000982/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000983class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000984 enum Class {
985 Integer,
986 Float
987 };
988
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000989 static const unsigned MinABIStackAlignInBytes = 4;
990
David Chisnallde3a0692009-08-17 23:08:21 +0000991 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000992 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000993 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000994 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000995 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000996 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000997
998 static bool isRegisterSize(unsigned Size) {
999 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1000 }
1001
Reid Kleckner80944df2014-10-31 22:00:51 +00001002 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1003 // FIXME: Assumes vectorcall is in use.
1004 return isX86VectorTypeForVectorCall(getContext(), Ty);
1005 }
1006
1007 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1008 uint64_t NumMembers) const override {
1009 // FIXME: Assumes vectorcall is in use.
1010 return isX86VectorCallAggregateSmallEnough(NumMembers);
1011 }
1012
Reid Kleckner40ca9132014-05-13 22:05:45 +00001013 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001014
Daniel Dunbar557893d2010-04-21 19:10:51 +00001015 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1016 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +00001017 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1018
John McCall7f416cc2015-09-08 08:05:57 +00001019 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +00001020
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001021 /// Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001022 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001023
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001024 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +00001025 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001026 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +00001027
Fangrui Song6907ce22018-07-30 19:24:48 +00001028 /// Updates the number of available free registers, returns
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001029 /// true if any registers were allocated.
1030 bool updateFreeRegs(QualType Ty, CCState &State) const;
1031
1032 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1033 bool &NeedsPadding) const;
1034 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001035
Reid Kleckner04046052016-05-02 17:41:07 +00001036 bool canExpandIndirectArgument(QualType Ty) const;
1037
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001038 /// Rewrite the function info so that all memory arguments use
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001039 /// inalloca.
1040 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1041
1042 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001043 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001044 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001045 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1046 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001047
Rafael Espindola75419dc2012-07-23 23:30:29 +00001048public:
1049
Craig Topper4f12f102014-03-12 06:41:41 +00001050 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001051 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1052 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001053
Michael Kupersteindc745202015-10-19 07:52:25 +00001054 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1055 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001056 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001057 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Fangrui Song6907ce22018-07-30 19:24:48 +00001058 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001059 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001060 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001061 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001062 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001063
John McCall56331e22018-01-07 06:28:49 +00001064 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00001065 bool asReturnValue) const override {
1066 // LLVM's x86-32 lowering currently only assigns up to three
1067 // integer registers and three fp registers. Oddly, it'll use up to
1068 // four vector registers for vectors, but those can overlap with the
1069 // scalar registers.
1070 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
Fangrui Song6907ce22018-07-30 19:24:48 +00001071 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001072
1073 bool isSwiftErrorInRegister() const override {
1074 // x86-32 lowering does not support passing swifterror in a register.
1075 return false;
1076 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001077};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001078
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001079class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1080public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001081 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1082 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001083 unsigned NumRegisterParameters, bool SoftFloatABI)
1084 : TargetCodeGenInfo(new X86_32ABIInfo(
1085 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1086 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001087
John McCall1fe2a8c2013-06-18 02:46:29 +00001088 static bool isStructReturnInRegABI(
1089 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1090
Eric Christopher162c91c2015-06-05 22:03:00 +00001091 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001092 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001093
Craig Topper4f12f102014-03-12 06:41:41 +00001094 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001095 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001096 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001097 return 4;
1098 }
1099
1100 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001101 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001102
Jay Foad7c57be32011-07-11 09:56:20 +00001103 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001104 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001105 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001106 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1107 }
1108
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001109 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1110 std::string &Constraints,
1111 std::vector<llvm::Type *> &ResultRegTypes,
1112 std::vector<llvm::Type *> &ResultTruncRegTypes,
1113 std::vector<LValue> &ResultRegDests,
1114 std::string &AsmString,
1115 unsigned NumOutputs) const override;
1116
Craig Topper4f12f102014-03-12 06:41:41 +00001117 llvm::Constant *
1118 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001119 unsigned Sig = (0xeb << 0) | // jmp rel8
1120 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001121 ('v' << 16) |
1122 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001123 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1124 }
John McCall01391782016-02-05 21:37:38 +00001125
1126 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1127 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001128 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001129 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001130};
1131
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001132}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001133
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001134/// Rewrite input constraint references after adding some output constraints.
1135/// In the case where there is one output and one input and we add one output,
1136/// we need to replace all operand references greater than or equal to 1:
1137/// mov $0, $1
1138/// mov eax, $1
1139/// The result will be:
1140/// mov $0, $2
1141/// mov eax, $2
1142static void rewriteInputConstraintReferences(unsigned FirstIn,
1143 unsigned NumNewOuts,
1144 std::string &AsmString) {
1145 std::string Buf;
1146 llvm::raw_string_ostream OS(Buf);
1147 size_t Pos = 0;
1148 while (Pos < AsmString.size()) {
1149 size_t DollarStart = AsmString.find('$', Pos);
1150 if (DollarStart == std::string::npos)
1151 DollarStart = AsmString.size();
1152 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1153 if (DollarEnd == std::string::npos)
1154 DollarEnd = AsmString.size();
1155 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1156 Pos = DollarEnd;
1157 size_t NumDollars = DollarEnd - DollarStart;
1158 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1159 // We have an operand reference.
1160 size_t DigitStart = Pos;
1161 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1162 if (DigitEnd == std::string::npos)
1163 DigitEnd = AsmString.size();
1164 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1165 unsigned OperandIndex;
1166 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1167 if (OperandIndex >= FirstIn)
1168 OperandIndex += NumNewOuts;
1169 OS << OperandIndex;
1170 } else {
1171 OS << OperandStr;
1172 }
1173 Pos = DigitEnd;
1174 }
1175 }
1176 AsmString = std::move(OS.str());
1177}
1178
1179/// Add output constraints for EAX:EDX because they are return registers.
1180void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1181 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1182 std::vector<llvm::Type *> &ResultRegTypes,
1183 std::vector<llvm::Type *> &ResultTruncRegTypes,
1184 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1185 unsigned NumOutputs) const {
1186 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1187
1188 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1189 // larger.
1190 if (!Constraints.empty())
1191 Constraints += ',';
1192 if (RetWidth <= 32) {
1193 Constraints += "={eax}";
1194 ResultRegTypes.push_back(CGF.Int32Ty);
1195 } else {
1196 // Use the 'A' constraint for EAX:EDX.
1197 Constraints += "=A";
1198 ResultRegTypes.push_back(CGF.Int64Ty);
1199 }
1200
1201 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1202 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1203 ResultTruncRegTypes.push_back(CoerceTy);
1204
1205 // Coerce the integer by bitcasting the return slot pointer.
1206 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1207 CoerceTy->getPointerTo()));
1208 ResultRegDests.push_back(ReturnSlot);
1209
1210 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1211}
1212
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001213/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001214/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001215bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1216 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001217 uint64_t Size = Context.getTypeSize(Ty);
1218
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001219 // For i386, type must be register sized.
1220 // For the MCU ABI, it only needs to be <= 8-byte
1221 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1222 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001223
1224 if (Ty->isVectorType()) {
1225 // 64- and 128- bit vectors inside structures are not returned in
1226 // registers.
1227 if (Size == 64 || Size == 128)
1228 return false;
1229
1230 return true;
1231 }
1232
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001233 // If this is a builtin, pointer, enum, complex type, member pointer, or
1234 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001235 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001236 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001237 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001238 return true;
1239
1240 // Arrays are treated like records.
1241 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001242 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001243
1244 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001245 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001246 if (!RT) return false;
1247
Anders Carlsson40446e82010-01-27 03:25:19 +00001248 // FIXME: Traverse bases here too.
1249
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001250 // Structure types are passed in register if all fields would be
1251 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001252 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001253 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001254 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001255 continue;
1256
1257 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001258 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001259 return false;
1260 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001261 return true;
1262}
1263
Reid Kleckner04046052016-05-02 17:41:07 +00001264static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1265 // Treat complex types as the element type.
1266 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1267 Ty = CTy->getElementType();
1268
1269 // Check for a type which we know has a simple scalar argument-passing
1270 // convention without any padding. (We're specifically looking for 32
1271 // and 64-bit integer and integer-equivalents, float, and double.)
1272 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1273 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1274 return false;
1275
1276 uint64_t Size = Context.getTypeSize(Ty);
1277 return Size == 32 || Size == 64;
1278}
1279
Reid Kleckner791bbf62017-01-13 17:18:19 +00001280static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1281 uint64_t &Size) {
1282 for (const auto *FD : RD->fields()) {
1283 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1284 // argument is smaller than 32-bits, expanding the struct will create
1285 // alignment padding.
1286 if (!is32Or64BitBasicType(FD->getType(), Context))
1287 return false;
1288
1289 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1290 // how to expand them yet, and the predicate for telling if a bitfield still
1291 // counts as "basic" is more complicated than what we were doing previously.
1292 if (FD->isBitField())
1293 return false;
1294
1295 Size += Context.getTypeSize(FD->getType());
1296 }
1297 return true;
1298}
1299
1300static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1301 uint64_t &Size) {
1302 // Don't do this if there are any non-empty bases.
1303 for (const CXXBaseSpecifier &Base : RD->bases()) {
1304 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1305 Size))
1306 return false;
1307 }
1308 if (!addFieldSizes(Context, RD, Size))
1309 return false;
1310 return true;
1311}
1312
Reid Kleckner04046052016-05-02 17:41:07 +00001313/// Test whether an argument type which is to be passed indirectly (on the
1314/// stack) would have the equivalent layout if it was expanded into separate
1315/// arguments. If so, we prefer to do the latter to avoid inhibiting
1316/// optimizations.
1317bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1318 // We can only expand structure types.
1319 const RecordType *RT = Ty->getAs<RecordType>();
1320 if (!RT)
1321 return false;
1322 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001323 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001324 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001325 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001326 // On non-Windows, we have to conservatively match our old bitcode
1327 // prototypes in order to be ABI-compatible at the bitcode level.
1328 if (!CXXRD->isCLike())
1329 return false;
1330 } else {
1331 // Don't do this for dynamic classes.
1332 if (CXXRD->isDynamicClass())
1333 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001334 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001335 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001336 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001337 } else {
1338 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001339 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001340 }
1341
1342 // We can do this if there was no alignment padding.
1343 return Size == getContext().getTypeSize(Ty);
1344}
1345
John McCall7f416cc2015-09-08 08:05:57 +00001346ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001347 // If the return value is indirect, then the hidden argument is consuming one
1348 // integer register.
1349 if (State.FreeRegs) {
1350 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001351 if (!IsMCUABI)
1352 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001353 }
John McCall7f416cc2015-09-08 08:05:57 +00001354 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001355}
1356
Eric Christopher7565e0d2015-05-29 23:09:49 +00001357ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1358 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001359 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001360 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001361
Reid Kleckner80944df2014-10-31 22:00:51 +00001362 const Type *Base = nullptr;
1363 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001364 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1365 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001366 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1367 // The LLVM struct type for such an aggregate should lower properly.
1368 return ABIArgInfo::getDirect();
1369 }
1370
Chris Lattner458b2aa2010-07-29 02:16:43 +00001371 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001372 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001373 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001374 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001375
1376 // 128-bit vectors are a special case; they are returned in
1377 // registers and we need to make sure to pick a type the LLVM
1378 // backend will like.
1379 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001380 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001381 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001382
1383 // Always return in register if it fits in a general purpose
1384 // register, or if it is 64 bits and has a single element.
1385 if ((Size == 8 || Size == 16 || Size == 32) ||
1386 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001387 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001388 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001389
John McCall7f416cc2015-09-08 08:05:57 +00001390 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001391 }
1392
1393 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001394 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001395
John McCalla1dee5302010-08-22 10:59:02 +00001396 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001397 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001398 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001399 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001400 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001401 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001402
David Chisnallde3a0692009-08-17 23:08:21 +00001403 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001404 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001405 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001406
Denis Zobnin380b2242016-02-11 11:26:03 +00001407 // Ignore empty structs/unions.
1408 if (isEmptyRecord(getContext(), RetTy, true))
1409 return ABIArgInfo::getIgnore();
1410
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001411 // Small structures which are register sized are generally returned
1412 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001413 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001414 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001415
1416 // As a special-case, if the struct is a "single-element" struct, and
1417 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001418 // floating-point register. (MSVC does not apply this special case.)
1419 // We apply a similar transformation for pointer types to improve the
1420 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001421 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001422 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001423 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001424 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1425
1426 // FIXME: We should be able to narrow this integer in cases with dead
1427 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001428 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001429 }
1430
John McCall7f416cc2015-09-08 08:05:57 +00001431 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001432 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001433
Chris Lattner458b2aa2010-07-29 02:16:43 +00001434 // Treat an enum type as its underlying type.
1435 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1436 RetTy = EnumTy->getDecl()->getIntegerType();
1437
Alex Bradburye41a5e22018-01-12 20:08:16 +00001438 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1439 : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001440}
1441
Eli Friedman7919bea2012-06-05 19:40:46 +00001442static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1443 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1444}
1445
Daniel Dunbared23de32010-09-16 20:42:00 +00001446static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1447 const RecordType *RT = Ty->getAs<RecordType>();
1448 if (!RT)
1449 return 0;
1450 const RecordDecl *RD = RT->getDecl();
1451
1452 // If this is a C++ record, check the bases first.
1453 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001454 for (const auto &I : CXXRD->bases())
1455 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001456 return false;
1457
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001458 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001459 QualType FT = i->getType();
1460
Eli Friedman7919bea2012-06-05 19:40:46 +00001461 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001462 return true;
1463
1464 if (isRecordWithSSEVectorType(Context, FT))
1465 return true;
1466 }
1467
1468 return false;
1469}
1470
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001471unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1472 unsigned Align) const {
1473 // Otherwise, if the alignment is less than or equal to the minimum ABI
1474 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001475 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001476 return 0; // Use default alignment.
1477
1478 // On non-Darwin, the stack type alignment is always 4.
1479 if (!IsDarwinVectorABI) {
1480 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001481 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001482 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001483
Daniel Dunbared23de32010-09-16 20:42:00 +00001484 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001485 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1486 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001487 return 16;
1488
1489 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001490}
1491
Rafael Espindola703c47f2012-10-19 05:04:37 +00001492ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001493 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001494 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001495 if (State.FreeRegs) {
1496 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001497 if (!IsMCUABI)
1498 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001499 }
John McCall7f416cc2015-09-08 08:05:57 +00001500 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001501 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001502
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001503 // Compute the byval alignment.
1504 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1505 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1506 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001507 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001508
1509 // If the stack alignment is less than the type alignment, realign the
1510 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001511 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001512 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1513 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001514}
1515
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001516X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1517 const Type *T = isSingleElementStruct(Ty, getContext());
1518 if (!T)
1519 T = Ty.getTypePtr();
1520
1521 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1522 BuiltinType::Kind K = BT->getKind();
1523 if (K == BuiltinType::Float || K == BuiltinType::Double)
1524 return Float;
1525 }
1526 return Integer;
1527}
1528
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001529bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001530 if (!IsSoftFloatABI) {
1531 Class C = classify(Ty);
1532 if (C == Float)
1533 return false;
1534 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001535
Rafael Espindola077dd592012-10-24 01:58:58 +00001536 unsigned Size = getContext().getTypeSize(Ty);
1537 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001538
1539 if (SizeInRegs == 0)
1540 return false;
1541
Michael Kuperstein68901882015-10-25 08:18:20 +00001542 if (!IsMCUABI) {
1543 if (SizeInRegs > State.FreeRegs) {
1544 State.FreeRegs = 0;
1545 return false;
1546 }
1547 } else {
1548 // The MCU psABI allows passing parameters in-reg even if there are
1549 // earlier parameters that are passed on the stack. Also,
1550 // it does not allow passing >8-byte structs in-register,
1551 // even if there are 3 free registers available.
1552 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1553 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001554 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001555
Reid Kleckner661f35b2014-01-18 01:12:41 +00001556 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001557 return true;
1558}
1559
Fangrui Song6907ce22018-07-30 19:24:48 +00001560bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001561 bool &InReg,
1562 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001563 // On Windows, aggregates other than HFAs are never passed in registers, and
1564 // they do not consume register slots. Homogenous floating-point aggregates
1565 // (HFAs) have already been dealt with at this point.
1566 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1567 return false;
1568
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001569 NeedsPadding = false;
1570 InReg = !IsMCUABI;
1571
1572 if (!updateFreeRegs(Ty, State))
1573 return false;
1574
1575 if (IsMCUABI)
1576 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001577
Reid Kleckner80944df2014-10-31 22:00:51 +00001578 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001579 State.CC == llvm::CallingConv::X86_VectorCall ||
1580 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001581 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001582 NeedsPadding = true;
1583
Rafael Espindola077dd592012-10-24 01:58:58 +00001584 return false;
1585 }
1586
Rafael Espindola703c47f2012-10-19 05:04:37 +00001587 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001588}
1589
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001590bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1591 if (!updateFreeRegs(Ty, State))
1592 return false;
1593
1594 if (IsMCUABI)
1595 return false;
1596
1597 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001598 State.CC == llvm::CallingConv::X86_VectorCall ||
1599 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001600 if (getContext().getTypeSize(Ty) > 32)
1601 return false;
1602
Fangrui Song6907ce22018-07-30 19:24:48 +00001603 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001604 Ty->isReferenceType());
1605 }
1606
1607 return true;
1608}
1609
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001610ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1611 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001612 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001613
Reid Klecknerb1be6832014-11-15 01:41:41 +00001614 Ty = useFirstFieldIfTransparentUnion(Ty);
1615
Reid Kleckner80944df2014-10-31 22:00:51 +00001616 // Check with the C++ ABI first.
1617 const RecordType *RT = Ty->getAs<RecordType>();
1618 if (RT) {
1619 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1620 if (RAA == CGCXXABI::RAA_Indirect) {
1621 return getIndirectResult(Ty, false, State);
1622 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1623 // The field index doesn't matter, we'll fix it up later.
1624 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1625 }
1626 }
1627
Erich Keane4bd39302017-06-21 16:37:22 +00001628 // Regcall uses the concept of a homogenous vector aggregate, similar
1629 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001630 const Type *Base = nullptr;
1631 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001632 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001633 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001634
Erich Keane4bd39302017-06-21 16:37:22 +00001635 if (State.FreeSSERegs >= NumElts) {
1636 State.FreeSSERegs -= NumElts;
1637 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001638 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001639 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001640 }
Erich Keane4bd39302017-06-21 16:37:22 +00001641 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001642 }
1643
1644 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001645 // Structures with flexible arrays are always indirect.
1646 // FIXME: This should not be byval!
1647 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1648 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001649
Reid Kleckner04046052016-05-02 17:41:07 +00001650 // Ignore empty structs/unions on non-Windows.
1651 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001652 return ABIArgInfo::getIgnore();
1653
Rafael Espindolafad28de2012-10-24 01:59:00 +00001654 llvm::LLVMContext &LLVMContext = getVMContext();
1655 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001656 bool NeedsPadding = false;
1657 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001658 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001659 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001660 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001661 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001662 if (InReg)
1663 return ABIArgInfo::getDirectInReg(Result);
1664 else
1665 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001666 }
Craig Topper8a13c412014-05-21 05:09:00 +00001667 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001668
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001669 // Expand small (<= 128-bit) record types when we know that the stack layout
1670 // of those arguments will match the struct. This is important because the
1671 // LLVM backend isn't smart enough to remove byval, which inhibits many
1672 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001673 // Don't do this for the MCU if there are still free integer registers
1674 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001675 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1676 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001677 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001678 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001679 State.CC == llvm::CallingConv::X86_VectorCall ||
1680 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001681 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001682
Reid Kleckner661f35b2014-01-18 01:12:41 +00001683 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001684 }
1685
Chris Lattnerd774ae92010-08-26 20:05:13 +00001686 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001687 // On Darwin, some vectors are passed in memory, we handle this by passing
1688 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001689 if (IsDarwinVectorABI) {
1690 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001691 if ((Size == 8 || Size == 16 || Size == 32) ||
1692 (Size == 64 && VT->getNumElements() == 1))
1693 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1694 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001695 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001696
Chad Rosier651c1832013-03-25 21:00:27 +00001697 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1698 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001699
Chris Lattnerd774ae92010-08-26 20:05:13 +00001700 return ABIArgInfo::getDirect();
1701 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001702
1703
Chris Lattner458b2aa2010-07-29 02:16:43 +00001704 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1705 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001706
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001707 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001708
1709 if (Ty->isPromotableIntegerType()) {
1710 if (InReg)
Alex Bradburye41a5e22018-01-12 20:08:16 +00001711 return ABIArgInfo::getExtendInReg(Ty);
1712 return ABIArgInfo::getExtend(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001713 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001714
Rafael Espindola703c47f2012-10-19 05:04:37 +00001715 if (InReg)
1716 return ABIArgInfo::getDirectInReg();
1717 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001718}
1719
Erich Keane521ed962017-01-05 00:20:51 +00001720void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1721 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001722 // Vectorcall x86 works subtly different than in x64, so the format is
1723 // a bit different than the x64 version. First, all vector types (not HVAs)
1724 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1725 // This differs from the x64 implementation, where the first 6 by INDEX get
1726 // registers.
1727 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1728 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1729 // first take up the remaining YMM/XMM registers. If insufficient registers
1730 // remain but an integer register (ECX/EDX) is available, it will be passed
1731 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001732 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001733 // First pass do all the vector types.
1734 const Type *Base = nullptr;
1735 uint64_t NumElts = 0;
1736 const QualType& Ty = I.type;
1737 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1738 isHomogeneousAggregate(Ty, Base, NumElts)) {
1739 if (State.FreeSSERegs >= NumElts) {
1740 State.FreeSSERegs -= NumElts;
1741 I.info = ABIArgInfo::getDirect();
1742 } else {
1743 I.info = classifyArgumentType(Ty, State);
1744 }
1745 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1746 }
Erich Keane521ed962017-01-05 00:20:51 +00001747 }
Erich Keane4bd39302017-06-21 16:37:22 +00001748
Erich Keane521ed962017-01-05 00:20:51 +00001749 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001750 // Second pass, do the rest!
1751 const Type *Base = nullptr;
1752 uint64_t NumElts = 0;
1753 const QualType& Ty = I.type;
1754 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1755
1756 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1757 // Assign true HVAs (non vector/native FP types).
1758 if (State.FreeSSERegs >= NumElts) {
1759 State.FreeSSERegs -= NumElts;
1760 I.info = getDirectX86Hva();
1761 } else {
1762 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1763 }
1764 } else if (!IsHva) {
1765 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1766 I.info = classifyArgumentType(Ty, State);
1767 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1768 }
Erich Keane521ed962017-01-05 00:20:51 +00001769 }
1770}
1771
Rafael Espindolaa6472962012-07-24 00:01:07 +00001772void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001773 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001774 if (IsMCUABI)
1775 State.FreeRegs = 3;
1776 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001777 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001778 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1779 State.FreeRegs = 2;
1780 State.FreeSSERegs = 6;
1781 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001782 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001783 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1784 State.FreeRegs = 5;
1785 State.FreeSSERegs = 8;
1786 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001787 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001788
Akira Hatanakad791e922018-03-19 17:38:40 +00001789 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001790 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001791 } else if (FI.getReturnInfo().isIndirect()) {
1792 // The C++ ABI is not aware of register usage, so we have to check if the
1793 // return value was sret and put it in a register ourselves if appropriate.
1794 if (State.FreeRegs) {
1795 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001796 if (!IsMCUABI)
1797 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001798 }
1799 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001800
Peter Collingbournef7706832014-12-12 23:41:25 +00001801 // The chain argument effectively gives us another free register.
1802 if (FI.isChainCall())
1803 ++State.FreeRegs;
1804
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001805 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001806 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1807 computeVectorCallArgs(FI, State, UsedInAlloca);
1808 } else {
1809 // If not vectorcall, revert to normal behavior.
1810 for (auto &I : FI.arguments()) {
1811 I.info = classifyArgumentType(I.type, State);
1812 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1813 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001814 }
1815
1816 // If we needed to use inalloca for any argument, do a second pass and rewrite
1817 // all the memory arguments to use inalloca.
1818 if (UsedInAlloca)
1819 rewriteWithInAlloca(FI);
1820}
1821
1822void
1823X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001824 CharUnits &StackOffset, ABIArgInfo &Info,
1825 QualType Type) const {
1826 // Arguments are always 4-byte-aligned.
1827 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1828
1829 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001830 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1831 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001832 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001833
John McCall7f416cc2015-09-08 08:05:57 +00001834 // Insert padding bytes to respect alignment.
1835 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001836 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001837 if (StackOffset != FieldEnd) {
1838 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001839 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001840 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001841 FrameFields.push_back(Ty);
1842 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001843}
1844
Reid Kleckner852361d2014-07-26 00:12:26 +00001845static bool isArgInAlloca(const ABIArgInfo &Info) {
1846 // Leave ignored and inreg arguments alone.
1847 switch (Info.getKind()) {
1848 case ABIArgInfo::InAlloca:
1849 return true;
1850 case ABIArgInfo::Indirect:
1851 assert(Info.getIndirectByVal());
1852 return true;
1853 case ABIArgInfo::Ignore:
1854 return false;
1855 case ABIArgInfo::Direct:
1856 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001857 if (Info.getInReg())
1858 return false;
1859 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001860 case ABIArgInfo::Expand:
1861 case ABIArgInfo::CoerceAndExpand:
1862 // These are aggregate types which are never passed in registers when
1863 // inalloca is involved.
1864 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001865 }
1866 llvm_unreachable("invalid enum");
1867}
1868
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001869void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1870 assert(IsWin32StructABI && "inalloca only supported on win32");
1871
1872 // Build a packed struct type for all of the arguments in memory.
1873 SmallVector<llvm::Type *, 6> FrameFields;
1874
John McCall7f416cc2015-09-08 08:05:57 +00001875 // The stack alignment is always 4.
1876 CharUnits StackAlign = CharUnits::fromQuantity(4);
1877
1878 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001879 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1880
1881 // Put 'this' into the struct before 'sret', if necessary.
1882 bool IsThisCall =
1883 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1884 ABIArgInfo &Ret = FI.getReturnInfo();
1885 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1886 isArgInAlloca(I->info)) {
1887 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1888 ++I;
1889 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001890
1891 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001892 if (Ret.isIndirect() && !Ret.getInReg()) {
1893 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1894 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001895 // On Windows, the hidden sret parameter is always returned in eax.
1896 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001897 }
1898
1899 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001900 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001901 ++I;
1902
1903 // Put arguments passed in memory into the struct.
1904 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001905 if (isArgInAlloca(I->info))
1906 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001907 }
1908
1909 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001910 /*isPacked=*/true),
1911 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001912}
1913
John McCall7f416cc2015-09-08 08:05:57 +00001914Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1915 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001916
John McCall7f416cc2015-09-08 08:05:57 +00001917 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001918
John McCall7f416cc2015-09-08 08:05:57 +00001919 // x86-32 changes the alignment of certain arguments on the stack.
1920 //
1921 // Just messing with TypeInfo like this works because we never pass
1922 // anything indirectly.
1923 TypeInfo.second = CharUnits::fromQuantity(
1924 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001925
John McCall7f416cc2015-09-08 08:05:57 +00001926 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1927 TypeInfo, CharUnits::fromQuantity(4),
1928 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001929}
1930
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001931bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1932 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1933 assert(Triple.getArch() == llvm::Triple::x86);
1934
1935 switch (Opts.getStructReturnConvention()) {
1936 case CodeGenOptions::SRCK_Default:
1937 break;
1938 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1939 return false;
1940 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1941 return true;
1942 }
1943
Michael Kupersteind749f232015-10-27 07:46:22 +00001944 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001945 return true;
1946
1947 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001948 case llvm::Triple::DragonFly:
1949 case llvm::Triple::FreeBSD:
1950 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001951 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001952 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001953 default:
1954 return false;
1955 }
1956}
1957
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001958void X86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001959 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1960 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001961 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001962 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001963 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001964 llvm::Function *Fn = cast<llvm::Function>(GV);
Erich Keaneb127a3942018-04-19 14:27:05 +00001965 Fn->addFnAttr("stackrealign");
Charles Davis4ea31ab2010-02-13 15:54:06 +00001966 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001967 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1968 llvm::Function *Fn = cast<llvm::Function>(GV);
1969 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1970 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001971 }
1972}
1973
John McCallbeec5a02010-03-06 00:35:14 +00001974bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1975 CodeGen::CodeGenFunction &CGF,
1976 llvm::Value *Address) const {
1977 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001978
Chris Lattnerece04092012-02-07 00:39:47 +00001979 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001980
John McCallbeec5a02010-03-06 00:35:14 +00001981 // 0-7 are the eight integer registers; the order is different
1982 // on Darwin (for EH), but the range is the same.
1983 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001984 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001985
John McCallc8e01702013-04-16 22:48:15 +00001986 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001987 // 12-16 are st(0..4). Not sure why we stop at 4.
1988 // These have size 16, which is sizeof(long double) on
1989 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001990 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001991 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001992
John McCallbeec5a02010-03-06 00:35:14 +00001993 } else {
1994 // 9 is %eflags, which doesn't get a size on Darwin for some
1995 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001996 Builder.CreateAlignedStore(
1997 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1998 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001999
2000 // 11-16 are st(0..5). Not sure why we stop at 5.
2001 // These have size 12, which is sizeof(long double) on
2002 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00002003 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00002004 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2005 }
John McCallbeec5a02010-03-06 00:35:14 +00002006
2007 return false;
2008}
2009
Chris Lattner0cf24192010-06-28 20:05:43 +00002010//===----------------------------------------------------------------------===//
2011// X86-64 ABI Implementation
2012//===----------------------------------------------------------------------===//
2013
2014
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002015namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002016/// The AVX ABI level for X86 targets.
2017enum class X86AVXABILevel {
2018 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002019 AVX,
2020 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002021};
2022
2023/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2024static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2025 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002026 case X86AVXABILevel::AVX512:
2027 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002028 case X86AVXABILevel::AVX:
2029 return 256;
2030 case X86AVXABILevel::None:
2031 return 128;
2032 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002033 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002034}
2035
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002036/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002037class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002038 enum Class {
2039 Integer = 0,
2040 SSE,
2041 SSEUp,
2042 X87,
2043 X87Up,
2044 ComplexX87,
2045 NoClass,
2046 Memory
2047 };
2048
2049 /// merge - Implement the X86_64 ABI merging algorithm.
2050 ///
2051 /// Merge an accumulating classification \arg Accum with a field
2052 /// classification \arg Field.
2053 ///
2054 /// \param Accum - The accumulating classification. This should
2055 /// always be either NoClass or the result of a previous merge
2056 /// call. In addition, this should never be Memory (the caller
2057 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002058 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002059
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002060 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2061 ///
2062 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2063 /// final MEMORY or SSE classes when necessary.
2064 ///
2065 /// \param AggregateSize - The size of the current aggregate in
2066 /// the classification process.
2067 ///
2068 /// \param Lo - The classification for the parts of the type
2069 /// residing in the low word of the containing object.
2070 ///
2071 /// \param Hi - The classification for the parts of the type
2072 /// residing in the higher words of the containing object.
2073 ///
2074 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2075
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002076 /// classify - Determine the x86_64 register classes in which the
2077 /// given type T should be passed.
2078 ///
2079 /// \param Lo - The classification for the parts of the type
2080 /// residing in the low word of the containing object.
2081 ///
2082 /// \param Hi - The classification for the parts of the type
2083 /// residing in the high word of the containing object.
2084 ///
2085 /// \param OffsetBase - The bit offset of this type in the
2086 /// containing object. Some parameters are classified different
2087 /// depending on whether they straddle an eightbyte boundary.
2088 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002089 /// \param isNamedArg - Whether the argument in question is a "named"
2090 /// argument, as used in AMD64-ABI 3.5.7.
2091 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002092 /// If a word is unused its result will be NoClass; if a type should
2093 /// be passed in Memory then at least the classification of \arg Lo
2094 /// will be Memory.
2095 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002096 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002097 ///
2098 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2099 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002100 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2101 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002102
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002103 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002104 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2105 unsigned IROffset, QualType SourceTy,
2106 unsigned SourceOffset) const;
2107 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2108 unsigned IROffset, QualType SourceTy,
2109 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002110
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002111 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002112 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002113 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002114
2115 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002116 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002117 ///
2118 /// \param freeIntRegs - The number of free integer registers remaining
2119 /// available.
2120 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002121
Chris Lattner458b2aa2010-07-29 02:16:43 +00002122 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002123
Erich Keane757d3172016-11-02 18:29:35 +00002124 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2125 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002126 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002127
Erich Keane757d3172016-11-02 18:29:35 +00002128 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2129 unsigned &NeededSSE) const;
2130
2131 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2132 unsigned &NeededSSE) const;
2133
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002134 bool IsIllegalVectorType(QualType Ty) const;
2135
John McCalle0fda732011-04-21 01:20:55 +00002136 /// The 0.98 ABI revision clarified a lot of ambiguities,
2137 /// unfortunately in ways that were not always consistent with
2138 /// certain previous compilers. In particular, platforms which
2139 /// required strict binary compatibility with older versions of GCC
2140 /// may need to exempt themselves.
2141 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002142 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002143 }
2144
Richard Smithf667ad52017-08-26 01:04:35 +00002145 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2146 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002147 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002148 // Clang <= 3.8 did not do this.
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002149 if (getContext().getLangOpts().getClangABICompat() <=
2150 LangOptions::ClangABI::Ver3_8)
Richard Smithf667ad52017-08-26 01:04:35 +00002151 return false;
2152
David Majnemere2ae2282016-03-04 05:26:16 +00002153 const llvm::Triple &Triple = getTarget().getTriple();
2154 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2155 return false;
2156 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2157 return false;
2158 return true;
2159 }
2160
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002161 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002162 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2163 // 64-bit hardware.
2164 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002165
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002166public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002167 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002168 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002169 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002170 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002171
John McCalla729c622012-02-17 03:33:10 +00002172 bool isPassedUsingAVXType(QualType type) const {
2173 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002174 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002175 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2176 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002177 if (info.isDirect()) {
2178 llvm::Type *ty = info.getCoerceToType();
2179 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2180 return (vectorTy->getBitWidth() > 128);
2181 }
2182 return false;
2183 }
2184
Craig Topper4f12f102014-03-12 06:41:41 +00002185 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002186
John McCall7f416cc2015-09-08 08:05:57 +00002187 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2188 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002189 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2190 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002191
2192 bool has64BitPointers() const {
2193 return Has64BitPointers;
2194 }
John McCall12f23522016-04-04 18:33:08 +00002195
John McCall56331e22018-01-07 06:28:49 +00002196 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00002197 bool asReturnValue) const override {
2198 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002199 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002200 bool isSwiftErrorInRegister() const override {
2201 return true;
2202 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002203};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002204
Chris Lattner04dc9572010-08-31 16:44:54 +00002205/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002206class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002207public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002208 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002209 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002210 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002211
Craig Topper4f12f102014-03-12 06:41:41 +00002212 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002213
John McCall7f416cc2015-09-08 08:05:57 +00002214 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2215 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002216
2217 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2218 // FIXME: Assumes vectorcall is in use.
2219 return isX86VectorTypeForVectorCall(getContext(), Ty);
2220 }
2221
2222 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2223 uint64_t NumMembers) const override {
2224 // FIXME: Assumes vectorcall is in use.
2225 return isX86VectorCallAggregateSmallEnough(NumMembers);
2226 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002227
John McCall56331e22018-01-07 06:28:49 +00002228 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002229 bool asReturnValue) const override {
2230 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2231 }
2232
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002233 bool isSwiftErrorInRegister() const override {
2234 return true;
2235 }
2236
Reid Kleckner11a17192015-10-28 22:29:52 +00002237private:
Erich Keane521ed962017-01-05 00:20:51 +00002238 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2239 bool IsVectorCall, bool IsRegCall) const;
2240 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2241 const ABIArgInfo &current) const;
2242 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2243 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002244
Erich Keane521ed962017-01-05 00:20:51 +00002245 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002246};
2247
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002248class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2249public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002250 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002251 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002252
John McCalla729c622012-02-17 03:33:10 +00002253 const X86_64ABIInfo &getABIInfo() const {
2254 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2255 }
2256
Craig Topper4f12f102014-03-12 06:41:41 +00002257 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002258 return 7;
2259 }
2260
2261 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002262 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002263 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002264
John McCall943fae92010-05-27 06:19:26 +00002265 // 0-15 are the 16 integer registers.
2266 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002267 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002268 return false;
2269 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002270
Jay Foad7c57be32011-07-11 09:56:20 +00002271 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002272 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002273 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002274 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2275 }
2276
John McCalla729c622012-02-17 03:33:10 +00002277 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002278 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002279 // The default CC on x86-64 sets %al to the number of SSA
2280 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002281 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002282 // that when AVX types are involved: the ABI explicitly states it is
2283 // undefined, and it doesn't work in practice because of how the ABI
2284 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002285 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002286 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002287 for (CallArgList::const_iterator
2288 it = args.begin(), ie = args.end(); it != ie; ++it) {
2289 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2290 HasAVXType = true;
2291 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002292 }
2293 }
John McCalla729c622012-02-17 03:33:10 +00002294
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002295 if (!HasAVXType)
2296 return true;
2297 }
John McCallcbc038a2011-09-21 08:08:30 +00002298
John McCalla729c622012-02-17 03:33:10 +00002299 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002300 }
2301
Craig Topper4f12f102014-03-12 06:41:41 +00002302 llvm::Constant *
2303 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002304 unsigned Sig = (0xeb << 0) | // jmp rel8
2305 (0x06 << 8) | // .+0x08
2306 ('v' << 16) |
2307 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002308 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2309 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002310
2311 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002312 CodeGen::CodeGenModule &CGM) const override {
2313 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002314 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002315 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002316 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002317 llvm::Function *Fn = cast<llvm::Function>(GV);
2318 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002319 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002320 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2321 llvm::Function *Fn = cast<llvm::Function>(GV);
2322 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2323 }
2324 }
2325 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002326};
2327
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002328class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2329public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002330 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2331 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002332
2333 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002334 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002335 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002336 // If the argument contains a space, enclose it in quotes.
2337 if (Lib.find(" ") != StringRef::npos)
2338 Opt += "\"" + Lib.str() + "\"";
2339 else
2340 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002341 }
2342};
2343
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002344static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002345 // If the argument does not end in .lib, automatically add the suffix.
2346 // If the argument contains a space, enclose it in quotes.
2347 // This matches the behavior of MSVC.
2348 bool Quote = (Lib.find(" ") != StringRef::npos);
2349 std::string ArgStr = Quote ? "\"" : "";
2350 ArgStr += Lib;
Martin Storsjo3cd67c92018-10-10 09:01:00 +00002351 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002352 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002353 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002354 return ArgStr;
2355}
2356
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002357class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2358public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002359 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002360 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2361 unsigned NumRegisterParameters)
2362 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002363 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002364
Eric Christopher162c91c2015-06-05 22:03:00 +00002365 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002366 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002367
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002368 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002369 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002370 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002371 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002372 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002373
2374 void getDetectMismatchOption(llvm::StringRef Name,
2375 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002376 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002377 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002378 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002379};
2380
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002381static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2382 CodeGen::CodeGenModule &CGM) {
2383 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002384
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002385 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
Eric Christopher7565e0d2015-05-29 23:09:49 +00002386 Fn->addFnAttr("stack-probe-size",
2387 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002388 if (CGM.getCodeGenOpts().NoStackArgProbe)
2389 Fn->addFnAttr("no-stack-arg-probe");
Hans Wennborg77dc2362015-01-20 19:45:50 +00002390 }
2391}
2392
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002393void WinX86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002394 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2395 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2396 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002397 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002398 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002399}
2400
Chris Lattner04dc9572010-08-31 16:44:54 +00002401class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2402public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002403 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2404 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002405 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002406
Eric Christopher162c91c2015-06-05 22:03:00 +00002407 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002408 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002409
Craig Topper4f12f102014-03-12 06:41:41 +00002410 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002411 return 7;
2412 }
2413
2414 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002415 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002416 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002417
Chris Lattner04dc9572010-08-31 16:44:54 +00002418 // 0-15 are the 16 integer registers.
2419 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002420 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002421 return false;
2422 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002423
2424 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002425 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002426 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002427 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002428 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002429
2430 void getDetectMismatchOption(llvm::StringRef Name,
2431 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002432 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002433 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002434 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002435};
2436
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002437void WinX86_64TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002438 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2439 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2440 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002441 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002442 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002443 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002444 llvm::Function *Fn = cast<llvm::Function>(GV);
2445 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002446 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002447 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2448 llvm::Function *Fn = cast<llvm::Function>(GV);
2449 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2450 }
2451 }
2452
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002453 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002454}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002455}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002456
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002457void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2458 Class &Hi) const {
2459 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2460 //
2461 // (a) If one of the classes is Memory, the whole argument is passed in
2462 // memory.
2463 //
2464 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2465 // memory.
2466 //
2467 // (c) If the size of the aggregate exceeds two eightbytes and the first
2468 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2469 // argument is passed in memory. NOTE: This is necessary to keep the
2470 // ABI working for processors that don't support the __m256 type.
2471 //
2472 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2473 //
2474 // Some of these are enforced by the merging logic. Others can arise
2475 // only with unions; for example:
2476 // union { _Complex double; unsigned; }
2477 //
2478 // Note that clauses (b) and (c) were added in 0.98.
2479 //
2480 if (Hi == Memory)
2481 Lo = Memory;
2482 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2483 Lo = Memory;
2484 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2485 Lo = Memory;
2486 if (Hi == SSEUp && Lo != SSE)
2487 Hi = SSE;
2488}
2489
Chris Lattnerd776fb12010-06-28 21:43:59 +00002490X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002491 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2492 // classified recursively so that always two fields are
2493 // considered. The resulting class is calculated according to
2494 // the classes of the fields in the eightbyte:
2495 //
2496 // (a) If both classes are equal, this is the resulting class.
2497 //
2498 // (b) If one of the classes is NO_CLASS, the resulting class is
2499 // the other class.
2500 //
2501 // (c) If one of the classes is MEMORY, the result is the MEMORY
2502 // class.
2503 //
2504 // (d) If one of the classes is INTEGER, the result is the
2505 // INTEGER.
2506 //
2507 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2508 // MEMORY is used as class.
2509 //
2510 // (f) Otherwise class SSE is used.
2511
2512 // Accum should never be memory (we should have returned) or
2513 // ComplexX87 (because this cannot be passed in a structure).
2514 assert((Accum != Memory && Accum != ComplexX87) &&
2515 "Invalid accumulated classification during merge.");
2516 if (Accum == Field || Field == NoClass)
2517 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002518 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002519 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002520 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002521 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002522 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002523 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002524 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2525 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002526 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002527 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002528}
2529
Chris Lattner5c740f12010-06-30 19:14:05 +00002530void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002531 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002532 // FIXME: This code can be simplified by introducing a simple value class for
2533 // Class pairs with appropriate constructor methods for the various
2534 // situations.
2535
2536 // FIXME: Some of the split computations are wrong; unaligned vectors
2537 // shouldn't be passed in registers for example, so there is no chance they
2538 // can straddle an eightbyte. Verify & simplify.
2539
2540 Lo = Hi = NoClass;
2541
2542 Class &Current = OffsetBase < 64 ? Lo : Hi;
2543 Current = Memory;
2544
John McCall9dd450b2009-09-21 23:43:11 +00002545 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002546 BuiltinType::Kind k = BT->getKind();
2547
2548 if (k == BuiltinType::Void) {
2549 Current = NoClass;
2550 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2551 Lo = Integer;
2552 Hi = Integer;
2553 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2554 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002555 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002556 Current = SSE;
2557 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002558 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002559 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002560 Lo = SSE;
2561 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002562 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002563 Lo = X87;
2564 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002565 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002566 Current = SSE;
2567 } else
2568 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002569 }
2570 // FIXME: _Decimal32 and _Decimal64 are SSE.
2571 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002572 return;
2573 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002574
Chris Lattnerd776fb12010-06-28 21:43:59 +00002575 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002576 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002577 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002578 return;
2579 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002580
Chris Lattnerd776fb12010-06-28 21:43:59 +00002581 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002582 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002583 return;
2584 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002585
Chris Lattnerd776fb12010-06-28 21:43:59 +00002586 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002587 if (Ty->isMemberFunctionPointerType()) {
2588 if (Has64BitPointers) {
2589 // If Has64BitPointers, this is an {i64, i64}, so classify both
2590 // Lo and Hi now.
2591 Lo = Hi = Integer;
2592 } else {
2593 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2594 // straddles an eightbyte boundary, Hi should be classified as well.
2595 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2596 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2597 if (EB_FuncPtr != EB_ThisAdj) {
2598 Lo = Hi = Integer;
2599 } else {
2600 Current = Integer;
2601 }
2602 }
2603 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002604 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002605 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002606 return;
2607 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002608
Chris Lattnerd776fb12010-06-28 21:43:59 +00002609 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002610 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002611 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2612 // gcc passes the following as integer:
2613 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2614 // 2 bytes - <2 x char>, <1 x short>
2615 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616 Current = Integer;
2617
2618 // If this type crosses an eightbyte boundary, it should be
2619 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002620 uint64_t EB_Lo = (OffsetBase) / 64;
2621 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2622 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002623 Hi = Lo;
2624 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002625 QualType ElementType = VT->getElementType();
2626
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002627 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002628 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002629 return;
2630
David Majnemere2ae2282016-03-04 05:26:16 +00002631 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2632 // pass them as integer. For platforms where clang is the de facto
2633 // platform compiler, we must continue to use integer.
2634 if (!classifyIntegerMMXAsSSE() &&
2635 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2636 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2637 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2638 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002639 Current = Integer;
2640 else
2641 Current = SSE;
2642
2643 // If this type crosses an eightbyte boundary, it should be
2644 // split.
2645 if (OffsetBase && OffsetBase != 64)
2646 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002647 } else if (Size == 128 ||
2648 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002649 // Arguments of 256-bits are split into four eightbyte chunks. The
2650 // least significant one belongs to class SSE and all the others to class
2651 // SSEUP. The original Lo and Hi design considers that types can't be
2652 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2653 // This design isn't correct for 256-bits, but since there're no cases
2654 // where the upper parts would need to be inspected, avoid adding
2655 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002656 //
2657 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2658 // registers if they are "named", i.e. not part of the "..." of a
2659 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002660 //
2661 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2662 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002663 Lo = SSE;
2664 Hi = SSEUp;
2665 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002666 return;
2667 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002668
Chris Lattnerd776fb12010-06-28 21:43:59 +00002669 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002670 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002671
Chris Lattner2b037972010-07-29 02:01:43 +00002672 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002673 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002674 if (Size <= 64)
2675 Current = Integer;
2676 else if (Size <= 128)
2677 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002678 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002679 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002680 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002681 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002682 } else if (ET == getContext().LongDoubleTy) {
2683 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002684 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002685 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002686 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002687 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002688 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002689 Lo = Hi = SSE;
2690 else
2691 llvm_unreachable("unexpected long double representation!");
2692 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002693
2694 // If this complex type crosses an eightbyte boundary then it
2695 // should be split.
2696 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002697 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002698 if (Hi == NoClass && EB_Real != EB_Imag)
2699 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002700
Chris Lattnerd776fb12010-06-28 21:43:59 +00002701 return;
2702 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002703
Chris Lattner2b037972010-07-29 02:01:43 +00002704 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002705 // Arrays are treated like structures.
2706
Chris Lattner2b037972010-07-29 02:01:43 +00002707 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002708
2709 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002710 // than eight eightbytes, ..., it has class MEMORY.
2711 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002712 return;
2713
2714 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2715 // fields, it has class MEMORY.
2716 //
2717 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002718 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002719 return;
2720
2721 // Otherwise implement simplified merge. We could be smarter about
2722 // this, but it isn't worth it and would be harder to verify.
2723 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002724 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002725 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002726
2727 // The only case a 256-bit wide vector could be used is when the array
2728 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2729 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002730 //
2731 if (Size > 128 &&
2732 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002733 return;
2734
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002735 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2736 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002737 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002738 Lo = merge(Lo, FieldLo);
2739 Hi = merge(Hi, FieldHi);
2740 if (Lo == Memory || Hi == Memory)
2741 break;
2742 }
2743
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002744 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002745 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002746 return;
2747 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002748
Chris Lattnerd776fb12010-06-28 21:43:59 +00002749 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002750 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002751
2752 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002753 // than eight eightbytes, ..., it has class MEMORY.
2754 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002755 return;
2756
Anders Carlsson20759ad2009-09-16 15:53:40 +00002757 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2758 // copy constructor or a non-trivial destructor, it is passed by invisible
2759 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002760 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002761 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002762
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002763 const RecordDecl *RD = RT->getDecl();
2764
2765 // Assume variable sized types are passed in memory.
2766 if (RD->hasFlexibleArrayMember())
2767 return;
2768
Chris Lattner2b037972010-07-29 02:01:43 +00002769 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002770
2771 // Reset Lo class, this will be recomputed.
2772 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002773
2774 // If this is a C++ record, classify the bases first.
2775 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002776 for (const auto &I : CXXRD->bases()) {
2777 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002778 "Unexpected base class!");
2779 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002780 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002781
2782 // Classify this field.
2783 //
2784 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2785 // single eightbyte, each is classified separately. Each eightbyte gets
2786 // initialized to class NO_CLASS.
2787 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002788 uint64_t Offset =
2789 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002790 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002791 Lo = merge(Lo, FieldLo);
2792 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002793 if (Lo == Memory || Hi == Memory) {
2794 postMerge(Size, Lo, Hi);
2795 return;
2796 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002797 }
2798 }
2799
2800 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002801 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002802 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002803 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002804 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2805 bool BitField = i->isBitField();
2806
David Majnemerb439dfe2016-08-15 07:20:40 +00002807 // Ignore padding bit-fields.
2808 if (BitField && i->isUnnamedBitfield())
2809 continue;
2810
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002811 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2812 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002813 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002814 // The only case a 256-bit wide vector could be used is when the struct
2815 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2816 // to work for sizes wider than 128, early check and fallback to memory.
2817 //
David Majnemerb229cb02016-08-15 06:39:18 +00002818 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2819 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002820 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002821 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002822 return;
2823 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002824 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002825 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002826 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002827 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002828 return;
2829 }
2830
2831 // Classify this field.
2832 //
2833 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2834 // exceeds a single eightbyte, each is classified
2835 // separately. Each eightbyte gets initialized to class
2836 // NO_CLASS.
2837 Class FieldLo, FieldHi;
2838
2839 // Bit-fields require special handling, they do not force the
2840 // structure to be passed in memory even if unaligned, and
2841 // therefore they can straddle an eightbyte.
2842 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002843 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002844 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002845 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002846
2847 uint64_t EB_Lo = Offset / 64;
2848 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002849
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002850 if (EB_Lo) {
2851 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2852 FieldLo = NoClass;
2853 FieldHi = Integer;
2854 } else {
2855 FieldLo = Integer;
2856 FieldHi = EB_Hi ? Integer : NoClass;
2857 }
2858 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002859 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002860 Lo = merge(Lo, FieldLo);
2861 Hi = merge(Hi, FieldHi);
2862 if (Lo == Memory || Hi == Memory)
2863 break;
2864 }
2865
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002866 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002867 }
2868}
2869
Chris Lattner22a931e2010-06-29 06:01:59 +00002870ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002871 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2872 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002873 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002874 // Treat an enum type as its underlying type.
2875 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2876 Ty = EnumTy->getDecl()->getIntegerType();
2877
Alex Bradburye41a5e22018-01-12 20:08:16 +00002878 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2879 : ABIArgInfo::getDirect());
Daniel Dunbar53fac692010-04-21 19:49:55 +00002880 }
2881
John McCall7f416cc2015-09-08 08:05:57 +00002882 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002883}
2884
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002885bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2886 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2887 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002888 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002889 if (Size <= 64 || Size > LargestVector)
2890 return true;
2891 }
2892
2893 return false;
2894}
2895
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002896ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2897 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002898 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2899 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002900 //
2901 // This assumption is optimistic, as there could be free registers available
2902 // when we need to pass this argument in memory, and LLVM could try to pass
2903 // the argument in the free register. This does not seem to happen currently,
2904 // but this code would be much safer if we could mark the argument with
2905 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002906 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002907 // Treat an enum type as its underlying type.
2908 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2909 Ty = EnumTy->getDecl()->getIntegerType();
2910
Alex Bradburye41a5e22018-01-12 20:08:16 +00002911 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2912 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002913 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002914
Mark Lacey3825e832013-10-06 01:33:34 +00002915 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002916 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002917
Chris Lattner44c2b902011-05-22 23:21:23 +00002918 // Compute the byval alignment. We specify the alignment of the byval in all
2919 // cases so that the mid-level optimizer knows the alignment of the byval.
2920 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002921
2922 // Attempt to avoid passing indirect results using byval when possible. This
2923 // is important for good codegen.
2924 //
2925 // We do this by coercing the value into a scalar type which the backend can
2926 // handle naturally (i.e., without using byval).
2927 //
2928 // For simplicity, we currently only do this when we have exhausted all of the
2929 // free integer registers. Doing this when there are free integer registers
2930 // would require more care, as we would have to ensure that the coerced value
2931 // did not claim the unused register. That would require either reording the
2932 // arguments to the function (so that any subsequent inreg values came first),
2933 // or only doing this optimization when there were no following arguments that
2934 // might be inreg.
2935 //
2936 // We currently expect it to be rare (particularly in well written code) for
2937 // arguments to be passed on the stack when there are still free integer
2938 // registers available (this would typically imply large structs being passed
2939 // by value), so this seems like a fair tradeoff for now.
2940 //
2941 // We can revisit this if the backend grows support for 'onstack' parameter
2942 // attributes. See PR12193.
2943 if (freeIntRegs == 0) {
2944 uint64_t Size = getContext().getTypeSize(Ty);
2945
2946 // If this type fits in an eightbyte, coerce it into the matching integral
2947 // type, which will end up on the stack (with alignment 8).
2948 if (Align == 8 && Size <= 64)
2949 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2950 Size));
2951 }
2952
John McCall7f416cc2015-09-08 08:05:57 +00002953 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002954}
2955
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002956/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2957/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002958llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002959 // Wrapper structs/arrays that only contain vectors are passed just like
2960 // vectors; strip them off if present.
2961 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2962 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002963
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002964 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002965 if (isa<llvm::VectorType>(IRType) ||
2966 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002967 return IRType;
2968
2969 // We couldn't find the preferred IR vector type for 'Ty'.
2970 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002971 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002972
2973 // Return a LLVM IR vector type based on the size of 'Ty'.
2974 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2975 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002976}
2977
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002978/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2979/// is known to either be off the end of the specified type or being in
2980/// alignment padding. The user type specified is known to be at most 128 bits
2981/// in size, and have passed through X86_64ABIInfo::classify with a successful
2982/// classification that put one of the two halves in the INTEGER class.
2983///
2984/// It is conservatively correct to return false.
2985static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2986 unsigned EndBit, ASTContext &Context) {
2987 // If the bytes being queried are off the end of the type, there is no user
2988 // data hiding here. This handles analysis of builtins, vectors and other
2989 // types that don't contain interesting padding.
2990 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2991 if (TySize <= StartBit)
2992 return true;
2993
Chris Lattner98076a22010-07-29 07:43:55 +00002994 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2995 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2996 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2997
2998 // Check each element to see if the element overlaps with the queried range.
2999 for (unsigned i = 0; i != NumElts; ++i) {
3000 // If the element is after the span we care about, then we're done..
3001 unsigned EltOffset = i*EltSize;
3002 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003003
Chris Lattner98076a22010-07-29 07:43:55 +00003004 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3005 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3006 EndBit-EltOffset, Context))
3007 return false;
3008 }
3009 // If it overlaps no elements, then it is safe to process as padding.
3010 return true;
3011 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003012
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003013 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3014 const RecordDecl *RD = RT->getDecl();
3015 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003016
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003017 // If this is a C++ record, check the bases first.
3018 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003019 for (const auto &I : CXXRD->bases()) {
3020 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003021 "Unexpected base class!");
3022 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003023 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003024
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003025 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003026 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003027 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003028
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003029 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003030 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003031 EndBit-BaseOffset, Context))
3032 return false;
3033 }
3034 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003035
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003036 // Verify that no field has data that overlaps the region of interest. Yes
3037 // this could be sped up a lot by being smarter about queried fields,
3038 // however we're only looking at structs up to 16 bytes, so we don't care
3039 // much.
3040 unsigned idx = 0;
3041 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3042 i != e; ++i, ++idx) {
3043 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003044
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003045 // If we found a field after the region we care about, then we're done.
3046 if (FieldOffset >= EndBit) break;
3047
3048 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3049 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3050 Context))
3051 return false;
3052 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003053
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003054 // If nothing in this record overlapped the area of interest, then we're
3055 // clean.
3056 return true;
3057 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003058
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003059 return false;
3060}
3061
Chris Lattnere556a712010-07-29 18:39:32 +00003062/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3063/// float member at the specified offset. For example, {int,{float}} has a
3064/// float at offset 4. It is conservatively correct for this routine to return
3065/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003066static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003067 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003068 // Base case if we find a float.
3069 if (IROffset == 0 && IRType->isFloatTy())
3070 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003071
Chris Lattnere556a712010-07-29 18:39:32 +00003072 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003073 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003074 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3075 unsigned Elt = SL->getElementContainingOffset(IROffset);
3076 IROffset -= SL->getElementOffset(Elt);
3077 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3078 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003079
Chris Lattnere556a712010-07-29 18:39:32 +00003080 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003081 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3082 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003083 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3084 IROffset -= IROffset/EltSize*EltSize;
3085 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3086 }
3087
3088 return false;
3089}
3090
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003091
3092/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3093/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003094llvm::Type *X86_64ABIInfo::
3095GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003096 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003097 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003098 // pass as float if the last 4 bytes is just padding. This happens for
3099 // structs that contain 3 floats.
3100 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3101 SourceOffset*8+64, getContext()))
3102 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003103
Chris Lattnere556a712010-07-29 18:39:32 +00003104 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3105 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3106 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003107 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3108 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003109 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003110
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003111 return llvm::Type::getDoubleTy(getVMContext());
3112}
3113
3114
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003115/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3116/// an 8-byte GPR. This means that we either have a scalar or we are talking
3117/// about the high or low part of an up-to-16-byte struct. This routine picks
3118/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003119/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3120/// etc).
3121///
3122/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3123/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3124/// the 8-byte value references. PrefType may be null.
3125///
Alp Toker9907f082014-07-09 14:06:35 +00003126/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003127/// an offset into this that we're processing (which is always either 0 or 8).
3128///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003129llvm::Type *X86_64ABIInfo::
3130GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003131 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003132 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3133 // returning an 8-byte unit starting with it. See if we can safely use it.
3134 if (IROffset == 0) {
3135 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003136 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3137 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003138 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003139
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003140 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3141 // goodness in the source type is just tail padding. This is allowed to
3142 // kick in for struct {double,int} on the int, but not on
3143 // struct{double,int,int} because we wouldn't return the second int. We
3144 // have to do this analysis on the source type because we can't depend on
3145 // unions being lowered a specific way etc.
3146 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003147 IRType->isIntegerTy(32) ||
3148 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3149 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3150 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003151
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003152 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3153 SourceOffset*8+64, getContext()))
3154 return IRType;
3155 }
3156 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003157
Chris Lattner2192fe52011-07-18 04:24:23 +00003158 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003159 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003160 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003161 if (IROffset < SL->getSizeInBytes()) {
3162 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3163 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003164
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003165 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3166 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003167 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003168 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003169
Chris Lattner2192fe52011-07-18 04:24:23 +00003170 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003171 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003172 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003173 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003174 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3175 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003176 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003177
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003178 // Okay, we don't have any better idea of what to pass, so we pass this in an
3179 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003180 unsigned TySizeInBytes =
3181 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003182
Chris Lattner3f763422010-07-29 17:34:39 +00003183 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003184
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003185 // It is always safe to classify this as an integer type up to i64 that
3186 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003187 return llvm::IntegerType::get(getVMContext(),
3188 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003189}
3190
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003191
3192/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3193/// be used as elements of a two register pair to pass or return, return a
3194/// first class aggregate to represent them. For example, if the low part of
3195/// a by-value argument should be passed as i32* and the high part as float,
3196/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003197static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003198GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003199 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003200 // In order to correctly satisfy the ABI, we need to the high part to start
3201 // at offset 8. If the high and low parts we inferred are both 4-byte types
3202 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3203 // the second element at offset 8. Check for this:
3204 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3205 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003206 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003207 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003208
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003209 // To handle this, we have to increase the size of the low part so that the
3210 // second element will start at an 8 byte offset. We can't increase the size
3211 // of the second element because it might make us access off the end of the
3212 // struct.
3213 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003214 // There are usually two sorts of types the ABI generation code can produce
3215 // for the low part of a pair that aren't 8 bytes in size: float or
3216 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3217 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003218 // Promote these to a larger type.
3219 if (Lo->isFloatTy())
3220 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3221 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003222 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3223 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003224 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3225 }
3226 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003227
Serge Guelton1d993272017-05-09 19:31:30 +00003228 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003229
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003230 // Verify that the second element is at an 8-byte offset.
3231 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3232 "Invalid x86-64 argument pair!");
3233 return Result;
3234}
3235
Chris Lattner31faff52010-07-28 23:06:14 +00003236ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003237classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003238 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3239 // classification algorithm.
3240 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003241 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003242
3243 // Check some invariants.
3244 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003245 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3246
Craig Topper8a13c412014-05-21 05:09:00 +00003247 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003248 switch (Lo) {
3249 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003250 if (Hi == NoClass)
3251 return ABIArgInfo::getIgnore();
3252 // If the low part is just padding, it takes no register, leave ResType
3253 // null.
3254 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3255 "Unknown missing lo part");
3256 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003257
3258 case SSEUp:
3259 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003260 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003261
3262 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3263 // hidden argument.
3264 case Memory:
3265 return getIndirectReturnResult(RetTy);
3266
3267 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3268 // available register of the sequence %rax, %rdx is used.
3269 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003270 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003271
Chris Lattner1f3a0632010-07-29 21:42:50 +00003272 // If we have a sign or zero extended integer, make sure to return Extend
3273 // so that the parameter gets the right LLVM IR attributes.
3274 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3275 // Treat an enum type as its underlying type.
3276 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3277 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003278
Chris Lattner1f3a0632010-07-29 21:42:50 +00003279 if (RetTy->isIntegralOrEnumerationType() &&
3280 RetTy->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003281 return ABIArgInfo::getExtend(RetTy);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003282 }
Chris Lattner31faff52010-07-28 23:06:14 +00003283 break;
3284
3285 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3286 // available SSE register of the sequence %xmm0, %xmm1 is used.
3287 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003288 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003289 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003290
3291 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3292 // returned on the X87 stack in %st0 as 80-bit x87 number.
3293 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003294 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003295 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003296
3297 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3298 // part of the value is returned in %st0 and the imaginary part in
3299 // %st1.
3300 case ComplexX87:
3301 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003302 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003303 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003304 break;
3305 }
3306
Craig Topper8a13c412014-05-21 05:09:00 +00003307 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003308 switch (Hi) {
3309 // Memory was handled previously and X87 should
3310 // never occur as a hi class.
3311 case Memory:
3312 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003313 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003314
3315 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003316 case NoClass:
3317 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003318
Chris Lattner52b3c132010-09-01 00:20:33 +00003319 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003320 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003321 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3322 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003323 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003324 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003325 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003326 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3327 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003328 break;
3329
3330 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003331 // is passed in the next available eightbyte chunk if the last used
3332 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003333 //
Chris Lattner57540c52011-04-15 05:22:18 +00003334 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003335 case SSEUp:
3336 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003337 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003338 break;
3339
3340 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3341 // returned together with the previous X87 value in %st0.
3342 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003343 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003344 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003345 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003346 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003347 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003348 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003349 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3350 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003351 }
Chris Lattner31faff52010-07-28 23:06:14 +00003352 break;
3353 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003354
Chris Lattner52b3c132010-09-01 00:20:33 +00003355 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003356 // known to pass in the high eightbyte of the result. We do this by forming a
3357 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003358 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003359 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003360
Chris Lattner1f3a0632010-07-29 21:42:50 +00003361 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003362}
3363
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003364ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003365 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3366 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003367 const
3368{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003369 Ty = useFirstFieldIfTransparentUnion(Ty);
3370
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003371 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003372 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003373
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003374 // Check some invariants.
3375 // FIXME: Enforce these by construction.
3376 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003377 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3378
3379 neededInt = 0;
3380 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003381 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003382 switch (Lo) {
3383 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003384 if (Hi == NoClass)
3385 return ABIArgInfo::getIgnore();
3386 // If the low part is just padding, it takes no register, leave ResType
3387 // null.
3388 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3389 "Unknown missing lo part");
3390 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003391
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003392 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3393 // on the stack.
3394 case Memory:
3395
3396 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3397 // COMPLEX_X87, it is passed in memory.
3398 case X87:
3399 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003400 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003401 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003402 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003403
3404 case SSEUp:
3405 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003406 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003407
3408 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3409 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3410 // and %r9 is used.
3411 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003412 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003413
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003414 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003415 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003416
3417 // If we have a sign or zero extended integer, make sure to return Extend
3418 // so that the parameter gets the right LLVM IR attributes.
3419 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3420 // Treat an enum type as its underlying type.
3421 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3422 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003423
Chris Lattner1f3a0632010-07-29 21:42:50 +00003424 if (Ty->isIntegralOrEnumerationType() &&
3425 Ty->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003426 return ABIArgInfo::getExtend(Ty);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003427 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003428
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003429 break;
3430
3431 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3432 // available SSE register is used, the registers are taken in the
3433 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003434 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003435 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003436 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003437 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003438 break;
3439 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003440 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003441
Craig Topper8a13c412014-05-21 05:09:00 +00003442 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003443 switch (Hi) {
3444 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003445 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003446 // which is passed in memory.
3447 case Memory:
3448 case X87:
3449 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003450 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003451
3452 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003453
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003454 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003455 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003456 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003457 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003458
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003459 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3460 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003461 break;
3462
3463 // X87Up generally doesn't occur here (long double is passed in
3464 // memory), except in situations involving unions.
3465 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003466 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003467 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003468
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003469 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3470 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003471
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003472 ++neededSSE;
3473 break;
3474
3475 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3476 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003477 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003478 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003479 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003480 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003481 break;
3482 }
3483
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003484 // If a high part was specified, merge it together with the low part. It is
3485 // known to pass in the high eightbyte of the result. We do this by forming a
3486 // first class struct aggregate with the high and low part: {low, high}
3487 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003488 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003489
Chris Lattner1f3a0632010-07-29 21:42:50 +00003490 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003491}
3492
Erich Keane757d3172016-11-02 18:29:35 +00003493ABIArgInfo
3494X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3495 unsigned &NeededSSE) const {
3496 auto RT = Ty->getAs<RecordType>();
3497 assert(RT && "classifyRegCallStructType only valid with struct types");
3498
3499 if (RT->getDecl()->hasFlexibleArrayMember())
3500 return getIndirectReturnResult(Ty);
3501
3502 // Sum up bases
3503 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3504 if (CXXRD->isDynamicClass()) {
3505 NeededInt = NeededSSE = 0;
3506 return getIndirectReturnResult(Ty);
3507 }
3508
3509 for (const auto &I : CXXRD->bases())
3510 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3511 .isIndirect()) {
3512 NeededInt = NeededSSE = 0;
3513 return getIndirectReturnResult(Ty);
3514 }
3515 }
3516
3517 // Sum up members
3518 for (const auto *FD : RT->getDecl()->fields()) {
3519 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3520 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3521 .isIndirect()) {
3522 NeededInt = NeededSSE = 0;
3523 return getIndirectReturnResult(Ty);
3524 }
3525 } else {
3526 unsigned LocalNeededInt, LocalNeededSSE;
3527 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3528 LocalNeededSSE, true)
3529 .isIndirect()) {
3530 NeededInt = NeededSSE = 0;
3531 return getIndirectReturnResult(Ty);
3532 }
3533 NeededInt += LocalNeededInt;
3534 NeededSSE += LocalNeededSSE;
3535 }
3536 }
3537
3538 return ABIArgInfo::getDirect();
3539}
3540
3541ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3542 unsigned &NeededInt,
3543 unsigned &NeededSSE) const {
3544
3545 NeededInt = 0;
3546 NeededSSE = 0;
3547
3548 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3549}
3550
Chris Lattner22326a12010-07-29 02:31:05 +00003551void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003552
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003553 const unsigned CallingConv = FI.getCallingConvention();
3554 // It is possible to force Win64 calling convention on any x86_64 target by
3555 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3556 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3557 if (CallingConv == llvm::CallingConv::Win64) {
3558 WinX86_64ABIInfo Win64ABIInfo(CGT);
3559 Win64ABIInfo.computeInfo(FI);
3560 return;
3561 }
3562
3563 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003564
3565 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003566 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3567 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3568 unsigned NeededInt, NeededSSE;
3569
Akira Hatanakad791e922018-03-19 17:38:40 +00003570 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Erich Keanede1b2a92017-07-21 18:50:36 +00003571 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3572 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3573 FI.getReturnInfo() =
3574 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3575 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3576 FreeIntRegs -= NeededInt;
3577 FreeSSERegs -= NeededSSE;
3578 } else {
3579 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3580 }
3581 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3582 // Complex Long Double Type is passed in Memory when Regcall
3583 // calling convention is used.
3584 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3585 if (getContext().getCanonicalType(CT->getElementType()) ==
3586 getContext().LongDoubleTy)
3587 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3588 } else
3589 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3590 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003591
3592 // If the return value is indirect, then the hidden argument is consuming one
3593 // integer register.
3594 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003595 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003596
Peter Collingbournef7706832014-12-12 23:41:25 +00003597 // The chain argument effectively gives us another free register.
3598 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003599 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003600
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003601 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003602 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3603 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003604 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003605 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003606 it != ie; ++it, ++ArgNo) {
3607 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003608
Erich Keane757d3172016-11-02 18:29:35 +00003609 if (IsRegCall && it->type->isStructureOrClassType())
3610 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3611 else
3612 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3613 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003614
3615 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3616 // eightbyte of an argument, the whole argument is passed on the
3617 // stack. If registers have already been assigned for some
3618 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003619 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3620 FreeIntRegs -= NeededInt;
3621 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003622 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003623 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003624 }
3625 }
3626}
3627
John McCall7f416cc2015-09-08 08:05:57 +00003628static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3629 Address VAListAddr, QualType Ty) {
3630 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3631 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003632 llvm::Value *overflow_arg_area =
3633 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3634
3635 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3636 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003637 // It isn't stated explicitly in the standard, but in practice we use
3638 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003639 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3640 if (Align > CharUnits::fromQuantity(8)) {
3641 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3642 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003643 }
3644
3645 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003646 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003647 llvm::Value *Res =
3648 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003649 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003650
3651 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3652 // l->overflow_arg_area + sizeof(type).
3653 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3654 // an 8 byte boundary.
3655
3656 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003657 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003658 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003659 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3660 "overflow_arg_area.next");
3661 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3662
3663 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003664 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003665}
3666
John McCall7f416cc2015-09-08 08:05:57 +00003667Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3668 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003669 // Assume that va_list type is correct; should be pointer to LLVM type:
3670 // struct {
3671 // i32 gp_offset;
3672 // i32 fp_offset;
3673 // i8* overflow_arg_area;
3674 // i8* reg_save_area;
3675 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003676 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003677
John McCall7f416cc2015-09-08 08:05:57 +00003678 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003679 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003680 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003681
3682 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3683 // in the registers. If not go to step 7.
3684 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003685 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003686
3687 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3688 // general purpose registers needed to pass type and num_fp to hold
3689 // the number of floating point registers needed.
3690
3691 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3692 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3693 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3694 //
3695 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3696 // register save space).
3697
Craig Topper8a13c412014-05-21 05:09:00 +00003698 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003699 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3700 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003701 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003702 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003703 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3704 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003705 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003706 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3707 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003708 }
3709
3710 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003711 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003712 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3713 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003714 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3715 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003716 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3717 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003718 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3719 }
3720
3721 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3722 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3723 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3724 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3725
3726 // Emit code to load the value if it was passed in registers.
3727
3728 CGF.EmitBlock(InRegBlock);
3729
3730 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3731 // an offset of l->gp_offset and/or l->fp_offset. This may require
3732 // copying to a temporary location in case the parameter is passed
3733 // in different register classes or requires an alignment greater
3734 // than 8 for general purpose registers and 16 for XMM registers.
3735 //
3736 // FIXME: This really results in shameful code when we end up needing to
3737 // collect arguments from different places; often what should result in a
3738 // simple assembling of a structure from scattered addresses has many more
3739 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003740 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003741 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3742 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3743 "reg_save_area");
3744
3745 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003746 if (neededInt && neededSSE) {
3747 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003748 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003749 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003750 Address Tmp = CGF.CreateMemTemp(Ty);
3751 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003752 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003753 llvm::Type *TyLo = ST->getElementType(0);
3754 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003755 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003756 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003757 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3758 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003759 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3760 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003761 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3762 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003763
John McCall7f416cc2015-09-08 08:05:57 +00003764 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003765 // FIXME: Our choice of alignment here and below is probably pessimistic.
3766 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3767 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3768 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003769 CGF.Builder.CreateStore(V,
3770 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3771
3772 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003773 V = CGF.Builder.CreateAlignedLoad(
3774 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3775 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003776 CharUnits Offset = CharUnits::fromQuantity(
3777 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3778 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3779
3780 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003781 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003782 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3783 CharUnits::fromQuantity(8));
3784 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003785
3786 // Copy to a temporary if necessary to ensure the appropriate alignment.
3787 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003788 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003789 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003790 CharUnits TyAlign = SizeAlign.second;
3791
3792 // Copy into a temporary if the type is more aligned than the
3793 // register save area.
3794 if (TyAlign.getQuantity() > 8) {
3795 Address Tmp = CGF.CreateMemTemp(Ty);
3796 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003797 RegAddr = Tmp;
3798 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003799
Chris Lattner0cf24192010-06-28 20:05:43 +00003800 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003801 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3802 CharUnits::fromQuantity(16));
3803 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003804 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003805 assert(neededSSE == 2 && "Invalid number of needed registers!");
3806 // SSE registers are spaced 16 bytes apart in the register save
3807 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003808 // The ABI isn't explicit about this, but it seems reasonable
3809 // to assume that the slots are 16-byte aligned, since the stack is
3810 // naturally 16-byte aligned and the prologue is expected to store
3811 // all the SSE registers to the RSA.
3812 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3813 CharUnits::fromQuantity(16));
3814 Address RegAddrHi =
3815 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3816 CharUnits::fromQuantity(16));
Erich Keane24e68402018-02-02 15:53:35 +00003817 llvm::Type *ST = AI.canHaveCoerceToType()
3818 ? AI.getCoerceToType()
3819 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003820 llvm::Value *V;
3821 Address Tmp = CGF.CreateMemTemp(Ty);
3822 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Erich Keane24e68402018-02-02 15:53:35 +00003823 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3824 RegAddrLo, ST->getStructElementType(0)));
John McCall7f416cc2015-09-08 08:05:57 +00003825 CGF.Builder.CreateStore(V,
3826 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
Erich Keane24e68402018-02-02 15:53:35 +00003827 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3828 RegAddrHi, ST->getStructElementType(1)));
John McCall7f416cc2015-09-08 08:05:57 +00003829 CGF.Builder.CreateStore(V,
3830 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3831
3832 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003833 }
3834
3835 // AMD64-ABI 3.5.7p5: Step 5. Set:
3836 // l->gp_offset = l->gp_offset + num_gp * 8
3837 // l->fp_offset = l->fp_offset + num_fp * 16.
3838 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003839 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003840 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3841 gp_offset_p);
3842 }
3843 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003844 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003845 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3846 fp_offset_p);
3847 }
3848 CGF.EmitBranch(ContBlock);
3849
3850 // Emit code to load the value if it was passed in memory.
3851
3852 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003853 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003854
3855 // Return the appropriate result.
3856
3857 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003858 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3859 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003860 return ResAddr;
3861}
3862
Charles Davisc7d5c942015-09-17 20:55:33 +00003863Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3864 QualType Ty) const {
3865 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3866 CGF.getContext().getTypeInfoInChars(Ty),
3867 CharUnits::fromQuantity(8),
3868 /*allowHigherAlign*/ false);
3869}
3870
Erich Keane521ed962017-01-05 00:20:51 +00003871ABIArgInfo
3872WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3873 const ABIArgInfo &current) const {
3874 // Assumes vectorCall calling convention.
3875 const Type *Base = nullptr;
3876 uint64_t NumElts = 0;
3877
3878 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3879 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3880 FreeSSERegs -= NumElts;
3881 return getDirectX86Hva();
3882 }
3883 return current;
3884}
3885
Reid Kleckner80944df2014-10-31 22:00:51 +00003886ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003887 bool IsReturnType, bool IsVectorCall,
3888 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003889
3890 if (Ty->isVoidType())
3891 return ABIArgInfo::getIgnore();
3892
3893 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3894 Ty = EnumTy->getDecl()->getIntegerType();
3895
Reid Kleckner80944df2014-10-31 22:00:51 +00003896 TypeInfo Info = getContext().getTypeInfo(Ty);
3897 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003898 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003899
Reid Kleckner9005f412014-05-02 00:51:20 +00003900 const RecordType *RT = Ty->getAs<RecordType>();
3901 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003902 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003903 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003904 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003905 }
3906
3907 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003908 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003909
Reid Kleckner9005f412014-05-02 00:51:20 +00003910 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003911
Reid Kleckner80944df2014-10-31 22:00:51 +00003912 const Type *Base = nullptr;
3913 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003914 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3915 // other targets.
3916 if ((IsVectorCall || IsRegCall) &&
3917 isHomogeneousAggregate(Ty, Base, NumElts)) {
3918 if (IsRegCall) {
3919 if (FreeSSERegs >= NumElts) {
3920 FreeSSERegs -= NumElts;
3921 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3922 return ABIArgInfo::getDirect();
3923 return ABIArgInfo::getExpand();
3924 }
3925 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3926 } else if (IsVectorCall) {
3927 if (FreeSSERegs >= NumElts &&
3928 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3929 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003930 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003931 } else if (IsReturnType) {
3932 return ABIArgInfo::getExpand();
3933 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3934 // HVAs are delayed and reclassified in the 2nd step.
3935 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3936 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003937 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003938 }
3939
Reid Klecknerec87fec2014-05-02 01:17:12 +00003940 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003941 // If the member pointer is represented by an LLVM int or ptr, pass it
3942 // directly.
3943 llvm::Type *LLTy = CGT.ConvertType(Ty);
3944 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3945 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003946 }
3947
Michael Kuperstein4f818702015-02-24 09:35:58 +00003948 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003949 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3950 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003951 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003952 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003953
Reid Kleckner9005f412014-05-02 00:51:20 +00003954 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003955 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003956 }
3957
Reid Kleckner08f64e92018-10-31 17:43:55 +00003958 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3959 switch (BT->getKind()) {
3960 case BuiltinType::Bool:
3961 // Bool type is always extended to the ABI, other builtin types are not
3962 // extended.
3963 return ABIArgInfo::getExtend(Ty);
3964
3965 case BuiltinType::LongDouble:
3966 // Mingw64 GCC uses the old 80 bit extended precision floating point
3967 // unit. It passes them indirectly through memory.
3968 if (IsMingw64) {
3969 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3970 if (LDF == &llvm::APFloat::x87DoubleExtended())
3971 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3972 }
3973 break;
3974
3975 case BuiltinType::Int128:
3976 case BuiltinType::UInt128:
3977 // If it's a parameter type, the normal ABI rule is that arguments larger
3978 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
3979 // even though it isn't particularly efficient.
3980 if (!IsReturnType)
3981 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3982
3983 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
3984 // Clang matches them for compatibility.
3985 return ABIArgInfo::getDirect(
3986 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2));
3987
3988 default:
3989 break;
3990 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003991 }
3992
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003993 return ABIArgInfo::getDirect();
3994}
3995
Erich Keane521ed962017-01-05 00:20:51 +00003996void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3997 unsigned FreeSSERegs,
3998 bool IsVectorCall,
3999 bool IsRegCall) const {
4000 unsigned Count = 0;
4001 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004002 // Vectorcall in x64 only permits the first 6 arguments to be passed
4003 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00004004 if (Count < VectorcallMaxParamNumAsReg)
4005 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4006 else {
4007 // Since these cannot be passed in registers, pretend no registers
4008 // are left.
4009 unsigned ZeroSSERegsAvail = 0;
4010 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4011 IsVectorCall, IsRegCall);
4012 }
4013 ++Count;
4014 }
4015
Erich Keane521ed962017-01-05 00:20:51 +00004016 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004017 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00004018 }
4019}
4020
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004021void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00004022 bool IsVectorCall =
4023 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00004024 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00004025
Erich Keane757d3172016-11-02 18:29:35 +00004026 unsigned FreeSSERegs = 0;
4027 if (IsVectorCall) {
4028 // We can use up to 4 SSE return registers with vectorcall.
4029 FreeSSERegs = 4;
4030 } else if (IsRegCall) {
4031 // RegCall gives us 16 SSE registers.
4032 FreeSSERegs = 16;
4033 }
4034
Reid Kleckner80944df2014-10-31 22:00:51 +00004035 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00004036 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4037 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00004038
Erich Keane757d3172016-11-02 18:29:35 +00004039 if (IsVectorCall) {
4040 // We can use up to 6 SSE register parameters with vectorcall.
4041 FreeSSERegs = 6;
4042 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004043 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004044 FreeSSERegs = 16;
4045 }
4046
Erich Keane521ed962017-01-05 00:20:51 +00004047 if (IsVectorCall) {
4048 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4049 } else {
4050 for (auto &I : FI.arguments())
4051 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4052 }
4053
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004054}
4055
John McCall7f416cc2015-09-08 08:05:57 +00004056Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4057 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004058
4059 bool IsIndirect = false;
4060
4061 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4062 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4063 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4064 uint64_t Width = getContext().getTypeSize(Ty);
4065 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4066 }
4067
4068 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004069 CGF.getContext().getTypeInfoInChars(Ty),
4070 CharUnits::fromQuantity(8),
4071 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004072}
Chris Lattner0cf24192010-06-28 20:05:43 +00004073
John McCallea8d8bb2010-03-11 00:10:12 +00004074// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004075namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004076/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4077class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004078 bool IsSoftFloatABI;
4079
4080 CharUnits getParamTypeAlignment(QualType Ty) const;
4081
John McCallea8d8bb2010-03-11 00:10:12 +00004082public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004083 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4084 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004085
John McCall7f416cc2015-09-08 08:05:57 +00004086 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4087 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004088};
4089
4090class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4091public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004092 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4093 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004094
Craig Topper4f12f102014-03-12 06:41:41 +00004095 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004096 // This is recovered from gcc output.
4097 return 1; // r1 is the dedicated stack pointer
4098 }
4099
4100 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004101 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004102};
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004103}
John McCallea8d8bb2010-03-11 00:10:12 +00004104
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004105CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4106 // Complex types are passed just like their elements
4107 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4108 Ty = CTy->getElementType();
4109
4110 if (Ty->isVectorType())
4111 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4112 : 4);
4113
4114 // For single-element float/vector structs, we consider the whole type
4115 // to have the same alignment requirements as its single element.
4116 const Type *AlignTy = nullptr;
4117 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4118 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4119 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4120 (BT && BT->isFloatingPoint()))
4121 AlignTy = EltType;
4122 }
4123
4124 if (AlignTy)
4125 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4126 return CharUnits::fromQuantity(4);
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004127}
John McCallea8d8bb2010-03-11 00:10:12 +00004128
James Y Knight29b5f082016-02-24 02:59:33 +00004129// TODO: this implementation is now likely redundant with
4130// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004131Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4132 QualType Ty) const {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004133 if (getTarget().getTriple().isOSDarwin()) {
4134 auto TI = getContext().getTypeInfoInChars(Ty);
4135 TI.second = getParamTypeAlignment(Ty);
4136
4137 CharUnits SlotSize = CharUnits::fromQuantity(4);
4138 return emitVoidPtrVAArg(CGF, VAList, Ty,
4139 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4140 /*AllowHigherAlign=*/true);
4141 }
4142
Roman Divacky039b9702016-02-20 08:31:24 +00004143 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004144 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4145 // TODO: Implement this. For now ignore.
4146 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004147 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004148 }
4149
John McCall7f416cc2015-09-08 08:05:57 +00004150 // struct __va_list_tag {
4151 // unsigned char gpr;
4152 // unsigned char fpr;
4153 // unsigned short reserved;
4154 // void *overflow_arg_area;
4155 // void *reg_save_area;
4156 // };
4157
Roman Divacky8a12d842014-11-03 18:32:54 +00004158 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004159 bool isInt =
4160 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004161 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004162
4163 // All aggregates are passed indirectly? That doesn't seem consistent
4164 // with the argument-lowering code.
4165 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004166
4167 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004168
4169 // The calling convention either uses 1-2 GPRs or 1 FPR.
4170 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004171 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004172 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4173 } else {
4174 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004175 }
John McCall7f416cc2015-09-08 08:05:57 +00004176
4177 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4178
4179 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004180 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004181 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4182 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4183 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004184
Eric Christopher7565e0d2015-05-29 23:09:49 +00004185 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004186 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004187
4188 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4189 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4190 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4191
4192 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4193
John McCall7f416cc2015-09-08 08:05:57 +00004194 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4195 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004196
John McCall7f416cc2015-09-08 08:05:57 +00004197 // Case 1: consume registers.
4198 Address RegAddr = Address::invalid();
4199 {
4200 CGF.EmitBlock(UsingRegs);
4201
4202 Address RegSaveAreaPtr =
4203 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4204 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4205 CharUnits::fromQuantity(8));
4206 assert(RegAddr.getElementType() == CGF.Int8Ty);
4207
4208 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004209 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004210 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4211 CharUnits::fromQuantity(32));
4212 }
4213
4214 // Get the address of the saved value by scaling the number of
Fangrui Song6907ce22018-07-30 19:24:48 +00004215 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004216 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004217 llvm::Value *RegOffset =
4218 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4219 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4220 RegAddr.getPointer(), RegOffset),
4221 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4222 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4223
4224 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004225 NumRegs =
Fangrui Song6907ce22018-07-30 19:24:48 +00004226 Builder.CreateAdd(NumRegs,
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004227 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004228 Builder.CreateStore(NumRegs, NumRegsAddr);
4229
4230 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004231 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004232
John McCall7f416cc2015-09-08 08:05:57 +00004233 // Case 2: consume space in the overflow area.
4234 Address MemAddr = Address::invalid();
4235 {
4236 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004237
Roman Divacky039b9702016-02-20 08:31:24 +00004238 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4239
John McCall7f416cc2015-09-08 08:05:57 +00004240 // Everything in the overflow area is rounded up to a size of at least 4.
4241 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4242
4243 CharUnits Size;
4244 if (!isIndirect) {
4245 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004246 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004247 } else {
4248 Size = CGF.getPointerSize();
4249 }
4250
4251 Address OverflowAreaAddr =
4252 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004253 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004254 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004255 // Round up address of argument to alignment
4256 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4257 if (Align > OverflowAreaAlign) {
4258 llvm::Value *Ptr = OverflowArea.getPointer();
4259 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4260 Align);
4261 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004262
John McCall7f416cc2015-09-08 08:05:57 +00004263 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4264
4265 // Increase the overflow area.
4266 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4267 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4268 CGF.EmitBranch(Cont);
4269 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004270
4271 CGF.EmitBlock(Cont);
4272
John McCall7f416cc2015-09-08 08:05:57 +00004273 // Merge the cases with a phi.
4274 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4275 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004276
John McCall7f416cc2015-09-08 08:05:57 +00004277 // Load the pointer if the argument was passed indirectly.
4278 if (isIndirect) {
4279 Result = Address(Builder.CreateLoad(Result, "aggr"),
4280 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004281 }
4282
4283 return Result;
4284}
4285
John McCallea8d8bb2010-03-11 00:10:12 +00004286bool
4287PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4288 llvm::Value *Address) const {
4289 // This is calculated from the LLVM and GCC tables and verified
4290 // against gcc output. AFAIK all ABIs use the same encoding.
4291
4292 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004293
Chris Lattnerece04092012-02-07 00:39:47 +00004294 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004295 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4296 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4297 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4298
4299 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004300 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004301
4302 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004303 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004304
4305 // 64-76 are various 4-byte special-purpose registers:
4306 // 64: mq
4307 // 65: lr
4308 // 66: ctr
4309 // 67: ap
4310 // 68-75 cr0-7
4311 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004312 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004313
4314 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004315 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004316
4317 // 109: vrsave
4318 // 110: vscr
4319 // 111: spe_acc
4320 // 112: spefscr
4321 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004322 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004323
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004324 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004325}
4326
Roman Divackyd966e722012-05-09 18:22:46 +00004327// PowerPC-64
4328
4329namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004330/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004331class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004332public:
4333 enum ABIKind {
4334 ELFv1 = 0,
4335 ELFv2
4336 };
4337
4338private:
4339 static const unsigned GPRBits = 64;
4340 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004341 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004342 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004343
4344 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4345 // will be passed in a QPX register.
4346 bool IsQPXVectorTy(const Type *Ty) const {
4347 if (!HasQPX)
4348 return false;
4349
4350 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4351 unsigned NumElements = VT->getNumElements();
4352 if (NumElements == 1)
4353 return false;
4354
4355 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4356 if (getContext().getTypeSize(Ty) <= 256)
4357 return true;
4358 } else if (VT->getElementType()->
4359 isSpecificBuiltinType(BuiltinType::Float)) {
4360 if (getContext().getTypeSize(Ty) <= 128)
4361 return true;
4362 }
4363 }
4364
4365 return false;
4366 }
4367
4368 bool IsQPXVectorTy(QualType Ty) const {
4369 return IsQPXVectorTy(Ty.getTypePtr());
4370 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004371
4372public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004373 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4374 bool SoftFloatABI)
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004375 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
Hal Finkel415c2a32016-10-02 02:10:45 +00004376 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004377
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004378 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004379 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004380
4381 ABIArgInfo classifyReturnType(QualType RetTy) const;
4382 ABIArgInfo classifyArgumentType(QualType Ty) const;
4383
Reid Klecknere9f6a712014-10-31 17:10:41 +00004384 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4385 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4386 uint64_t Members) const override;
4387
Bill Schmidt84d37792012-10-12 19:26:17 +00004388 // TODO: We can add more logic to computeInfo to improve performance.
4389 // Example: For aggregate arguments that fit in a register, we could
4390 // use getDirectInReg (as is done below for structs containing a single
4391 // floating-point value) to avoid pushing them to memory on function
4392 // entry. This would require changing the logic in PPCISelLowering
4393 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004394 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004395 if (!getCXXABI().classifyReturnType(FI))
4396 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004397 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004398 // We rely on the default argument classification for the most part.
4399 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004400 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004401 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004402 if (T) {
4403 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004404 if (IsQPXVectorTy(T) ||
4405 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004406 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004407 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004408 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004409 continue;
4410 }
4411 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004412 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004413 }
4414 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004415
John McCall7f416cc2015-09-08 08:05:57 +00004416 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4417 QualType Ty) const override;
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004418
4419 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4420 bool asReturnValue) const override {
4421 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4422 }
4423
4424 bool isSwiftErrorInRegister() const override {
4425 return false;
4426 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004427};
4428
4429class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004430
Bill Schmidt25cb3492012-10-03 19:18:57 +00004431public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004432 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004433 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4434 bool SoftFloatABI)
4435 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4436 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004437
Craig Topper4f12f102014-03-12 06:41:41 +00004438 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004439 // This is recovered from gcc output.
4440 return 1; // r1 is the dedicated stack pointer
4441 }
4442
4443 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004444 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004445};
4446
Roman Divackyd966e722012-05-09 18:22:46 +00004447class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4448public:
4449 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4450
Craig Topper4f12f102014-03-12 06:41:41 +00004451 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004452 // This is recovered from gcc output.
4453 return 1; // r1 is the dedicated stack pointer
4454 }
4455
4456 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004457 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004458};
4459
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004460}
Roman Divackyd966e722012-05-09 18:22:46 +00004461
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004462// Return true if the ABI requires Ty to be passed sign- or zero-
4463// extended to 64 bits.
4464bool
4465PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4466 // Treat an enum type as its underlying type.
4467 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4468 Ty = EnumTy->getDecl()->getIntegerType();
4469
4470 // Promotable integer types are required to be promoted by the ABI.
4471 if (Ty->isPromotableIntegerType())
4472 return true;
4473
4474 // In addition to the usual promotable integer types, we also need to
4475 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4476 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4477 switch (BT->getKind()) {
4478 case BuiltinType::Int:
4479 case BuiltinType::UInt:
4480 return true;
4481 default:
4482 break;
4483 }
4484
4485 return false;
4486}
4487
John McCall7f416cc2015-09-08 08:05:57 +00004488/// isAlignedParamType - Determine whether a type requires 16-byte or
4489/// higher alignment in the parameter area. Always returns at least 8.
4490CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004491 // Complex types are passed just like their elements.
4492 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4493 Ty = CTy->getElementType();
4494
4495 // Only vector types of size 16 bytes need alignment (larger types are
4496 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004497 if (IsQPXVectorTy(Ty)) {
4498 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004499 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004500
John McCall7f416cc2015-09-08 08:05:57 +00004501 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004502 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004503 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004504 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004505
4506 // For single-element float/vector structs, we consider the whole type
4507 // to have the same alignment requirements as its single element.
4508 const Type *AlignAsType = nullptr;
4509 const Type *EltType = isSingleElementStruct(Ty, getContext());
4510 if (EltType) {
4511 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004512 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004513 getContext().getTypeSize(EltType) == 128) ||
4514 (BT && BT->isFloatingPoint()))
4515 AlignAsType = EltType;
4516 }
4517
Ulrich Weigandb7122372014-07-21 00:48:09 +00004518 // Likewise for ELFv2 homogeneous aggregates.
4519 const Type *Base = nullptr;
4520 uint64_t Members = 0;
4521 if (!AlignAsType && Kind == ELFv2 &&
4522 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4523 AlignAsType = Base;
4524
Ulrich Weigand581badc2014-07-10 17:20:07 +00004525 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004526 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4527 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004528 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004529
John McCall7f416cc2015-09-08 08:05:57 +00004530 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004531 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004532 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004533 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004534
4535 // Otherwise, we only need alignment for any aggregate type that
4536 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004537 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4538 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004539 return CharUnits::fromQuantity(32);
4540 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004541 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004542
John McCall7f416cc2015-09-08 08:05:57 +00004543 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004544}
4545
Ulrich Weigandb7122372014-07-21 00:48:09 +00004546/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4547/// aggregate. Base is set to the base element type, and Members is set
4548/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004549bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4550 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004551 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4552 uint64_t NElements = AT->getSize().getZExtValue();
4553 if (NElements == 0)
4554 return false;
4555 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4556 return false;
4557 Members *= NElements;
4558 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4559 const RecordDecl *RD = RT->getDecl();
4560 if (RD->hasFlexibleArrayMember())
4561 return false;
4562
4563 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004564
4565 // If this is a C++ record, check the bases first.
4566 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4567 for (const auto &I : CXXRD->bases()) {
4568 // Ignore empty records.
4569 if (isEmptyRecord(getContext(), I.getType(), true))
4570 continue;
4571
4572 uint64_t FldMembers;
4573 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4574 return false;
4575
4576 Members += FldMembers;
4577 }
4578 }
4579
Ulrich Weigandb7122372014-07-21 00:48:09 +00004580 for (const auto *FD : RD->fields()) {
4581 // Ignore (non-zero arrays of) empty records.
4582 QualType FT = FD->getType();
4583 while (const ConstantArrayType *AT =
4584 getContext().getAsConstantArrayType(FT)) {
4585 if (AT->getSize().getZExtValue() == 0)
4586 return false;
4587 FT = AT->getElementType();
4588 }
4589 if (isEmptyRecord(getContext(), FT, true))
4590 continue;
4591
4592 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4593 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00004594 FD->isZeroLengthBitField(getContext()))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004595 continue;
4596
4597 uint64_t FldMembers;
4598 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4599 return false;
4600
4601 Members = (RD->isUnion() ?
4602 std::max(Members, FldMembers) : Members + FldMembers);
4603 }
4604
4605 if (!Base)
4606 return false;
4607
4608 // Ensure there is no padding.
4609 if (getContext().getTypeSize(Base) * Members !=
4610 getContext().getTypeSize(Ty))
4611 return false;
4612 } else {
4613 Members = 1;
4614 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4615 Members = 2;
4616 Ty = CT->getElementType();
4617 }
4618
Reid Klecknere9f6a712014-10-31 17:10:41 +00004619 // Most ABIs only support float, double, and some vector type widths.
4620 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004621 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004622
4623 // The base type must be the same for all members. Types that
4624 // agree in both total size and mode (float vs. vector) are
4625 // treated as being equivalent here.
4626 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004627 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004628 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004629 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4630 // so make sure to widen it explicitly.
4631 if (const VectorType *VT = Base->getAs<VectorType>()) {
4632 QualType EltTy = VT->getElementType();
4633 unsigned NumElements =
4634 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4635 Base = getContext()
4636 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4637 .getTypePtr();
4638 }
4639 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004640
4641 if (Base->isVectorType() != TyPtr->isVectorType() ||
4642 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4643 return false;
4644 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004645 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4646}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004647
Reid Klecknere9f6a712014-10-31 17:10:41 +00004648bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4649 // Homogeneous aggregates for ELFv2 must have base types of float,
4650 // double, long double, or 128-bit vectors.
4651 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4652 if (BT->getKind() == BuiltinType::Float ||
4653 BT->getKind() == BuiltinType::Double ||
Lei Huang449252d2018-07-05 04:32:01 +00004654 BT->getKind() == BuiltinType::LongDouble ||
4655 (getContext().getTargetInfo().hasFloat128Type() &&
4656 (BT->getKind() == BuiltinType::Float128))) {
Hal Finkel415c2a32016-10-02 02:10:45 +00004657 if (IsSoftFloatABI)
4658 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004659 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004660 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004661 }
4662 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004663 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004664 return true;
4665 }
4666 return false;
4667}
4668
4669bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4670 const Type *Base, uint64_t Members) const {
Lei Huang449252d2018-07-05 04:32:01 +00004671 // Vector and fp128 types require one register, other floating point types
4672 // require one or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004673 uint32_t NumRegs =
Lei Huang449252d2018-07-05 04:32:01 +00004674 ((getContext().getTargetInfo().hasFloat128Type() &&
4675 Base->isFloat128Type()) ||
4676 Base->isVectorType()) ? 1
4677 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004678
4679 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004680 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004681}
4682
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004683ABIArgInfo
4684PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004685 Ty = useFirstFieldIfTransparentUnion(Ty);
4686
Bill Schmidt90b22c92012-11-27 02:46:43 +00004687 if (Ty->isAnyComplexType())
4688 return ABIArgInfo::getDirect();
4689
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004690 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4691 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004692 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004693 uint64_t Size = getContext().getTypeSize(Ty);
4694 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004695 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004696 else if (Size < 128) {
4697 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4698 return ABIArgInfo::getDirect(CoerceTy);
4699 }
4700 }
4701
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004702 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004703 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004704 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004705
John McCall7f416cc2015-09-08 08:05:57 +00004706 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4707 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004708
4709 // ELFv2 homogeneous aggregates are passed as array types.
4710 const Type *Base = nullptr;
4711 uint64_t Members = 0;
4712 if (Kind == ELFv2 &&
4713 isHomogeneousAggregate(Ty, Base, Members)) {
4714 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4715 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4716 return ABIArgInfo::getDirect(CoerceTy);
4717 }
4718
Ulrich Weigand601957f2014-07-21 00:56:36 +00004719 // If an aggregate may end up fully in registers, we do not
4720 // use the ByVal method, but pass the aggregate as array.
4721 // This is usually beneficial since we avoid forcing the
4722 // back-end to store the argument to memory.
4723 uint64_t Bits = getContext().getTypeSize(Ty);
4724 if (Bits > 0 && Bits <= 8 * GPRBits) {
4725 llvm::Type *CoerceTy;
4726
4727 // Types up to 8 bytes are passed as integer type (which will be
4728 // properly aligned in the argument save area doubleword).
4729 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004730 CoerceTy =
4731 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004732 // Larger types are passed as arrays, with the base type selected
4733 // according to the required alignment in the save area.
4734 else {
4735 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004736 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004737 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4738 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4739 }
4740
4741 return ABIArgInfo::getDirect(CoerceTy);
4742 }
4743
Ulrich Weigandb7122372014-07-21 00:48:09 +00004744 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004745 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4746 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004747 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004748 }
4749
Alex Bradburye41a5e22018-01-12 20:08:16 +00004750 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4751 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004752}
4753
4754ABIArgInfo
4755PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4756 if (RetTy->isVoidType())
4757 return ABIArgInfo::getIgnore();
4758
Bill Schmidta3d121c2012-12-17 04:20:17 +00004759 if (RetTy->isAnyComplexType())
4760 return ABIArgInfo::getDirect();
4761
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004762 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4763 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004764 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004765 uint64_t Size = getContext().getTypeSize(RetTy);
4766 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004767 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004768 else if (Size < 128) {
4769 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4770 return ABIArgInfo::getDirect(CoerceTy);
4771 }
4772 }
4773
Ulrich Weigandb7122372014-07-21 00:48:09 +00004774 if (isAggregateTypeForABI(RetTy)) {
4775 // ELFv2 homogeneous aggregates are returned as array types.
4776 const Type *Base = nullptr;
4777 uint64_t Members = 0;
4778 if (Kind == ELFv2 &&
4779 isHomogeneousAggregate(RetTy, Base, Members)) {
4780 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4781 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4782 return ABIArgInfo::getDirect(CoerceTy);
4783 }
4784
4785 // ELFv2 small aggregates are returned in up to two registers.
4786 uint64_t Bits = getContext().getTypeSize(RetTy);
4787 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4788 if (Bits == 0)
4789 return ABIArgInfo::getIgnore();
4790
4791 llvm::Type *CoerceTy;
4792 if (Bits > GPRBits) {
4793 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004794 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004795 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004796 CoerceTy =
4797 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004798 return ABIArgInfo::getDirect(CoerceTy);
4799 }
4800
4801 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004802 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004803 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004804
Alex Bradburye41a5e22018-01-12 20:08:16 +00004805 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4806 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004807}
4808
Bill Schmidt25cb3492012-10-03 19:18:57 +00004809// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004810Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4811 QualType Ty) const {
4812 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4813 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004814
John McCall7f416cc2015-09-08 08:05:57 +00004815 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004816
Bill Schmidt924c4782013-01-14 17:45:36 +00004817 // If we have a complex type and the base type is smaller than 8 bytes,
4818 // the ABI calls for the real and imaginary parts to be right-adjusted
4819 // in separate doublewords. However, Clang expects us to produce a
4820 // pointer to a structure with the two parts packed tightly. So generate
4821 // loads of the real and imaginary parts relative to the va_list pointer,
4822 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004823 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4824 CharUnits EltSize = TypeInfo.first / 2;
4825 if (EltSize < SlotSize) {
4826 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4827 SlotSize * 2, SlotSize,
4828 SlotSize, /*AllowHigher*/ true);
4829
4830 Address RealAddr = Addr;
4831 Address ImagAddr = RealAddr;
4832 if (CGF.CGM.getDataLayout().isBigEndian()) {
4833 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4834 SlotSize - EltSize);
4835 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4836 2 * SlotSize - EltSize);
4837 } else {
4838 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4839 }
4840
4841 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4842 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4843 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4844 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4845 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4846
4847 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4848 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4849 /*init*/ true);
4850 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004851 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004852 }
4853
John McCall7f416cc2015-09-08 08:05:57 +00004854 // Otherwise, just use the general rule.
4855 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4856 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004857}
4858
4859static bool
4860PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4861 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004862 // This is calculated from the LLVM and GCC tables and verified
4863 // against gcc output. AFAIK all ABIs use the same encoding.
4864
4865 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4866
4867 llvm::IntegerType *i8 = CGF.Int8Ty;
4868 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4869 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4870 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4871
4872 // 0-31: r0-31, the 8-byte general-purpose registers
4873 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4874
4875 // 32-63: fp0-31, the 8-byte floating-point registers
4876 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4877
Hal Finkel84832a72016-08-30 02:38:34 +00004878 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004879 // 64: mq
4880 // 65: lr
4881 // 66: ctr
4882 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004883 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4884
4885 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004886 // 68-75 cr0-7
4887 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004888 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004889
4890 // 77-108: v0-31, the 16-byte vector registers
4891 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4892
4893 // 109: vrsave
4894 // 110: vscr
4895 // 111: spe_acc
4896 // 112: spefscr
4897 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004898 // 114: tfhar
4899 // 115: tfiar
4900 // 116: texasr
4901 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004902
4903 return false;
4904}
John McCallea8d8bb2010-03-11 00:10:12 +00004905
Bill Schmidt25cb3492012-10-03 19:18:57 +00004906bool
4907PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4908 CodeGen::CodeGenFunction &CGF,
4909 llvm::Value *Address) const {
4910
4911 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4912}
4913
4914bool
4915PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4916 llvm::Value *Address) const {
4917
4918 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4919}
4920
Chris Lattner0cf24192010-06-28 20:05:43 +00004921//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004922// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004923//===----------------------------------------------------------------------===//
4924
4925namespace {
4926
John McCall12f23522016-04-04 18:33:08 +00004927class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004928public:
4929 enum ABIKind {
4930 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004931 DarwinPCS,
4932 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004933 };
4934
4935private:
4936 ABIKind Kind;
4937
4938public:
John McCall12f23522016-04-04 18:33:08 +00004939 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4940 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004941
4942private:
4943 ABIKind getABIKind() const { return Kind; }
4944 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4945
4946 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004947 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004948 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4949 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4950 uint64_t Members) const override;
4951
Tim Northovera2ee4332014-03-29 15:09:45 +00004952 bool isIllegalVectorType(QualType Ty) const;
4953
David Blaikie1cbb9712014-11-14 19:09:44 +00004954 void computeInfo(CGFunctionInfo &FI) const override {
Akira Hatanakad791e922018-03-19 17:38:40 +00004955 if (!::classifyReturnType(getCXXABI(), FI, *this))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004956 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004957
Tim Northoverb047bfa2014-11-27 21:02:49 +00004958 for (auto &it : FI.arguments())
4959 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004960 }
4961
John McCall7f416cc2015-09-08 08:05:57 +00004962 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4963 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004964
John McCall7f416cc2015-09-08 08:05:57 +00004965 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4966 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004967
John McCall7f416cc2015-09-08 08:05:57 +00004968 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4969 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004970 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4971 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4972 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004973 }
John McCall12f23522016-04-04 18:33:08 +00004974
Martin Storsjo502de222017-07-13 17:59:14 +00004975 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4976 QualType Ty) const override;
4977
John McCall56331e22018-01-07 06:28:49 +00004978 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00004979 bool asReturnValue) const override {
4980 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4981 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004982 bool isSwiftErrorInRegister() const override {
4983 return true;
4984 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004985
4986 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4987 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004988};
4989
Tim Northover573cbee2014-05-24 12:52:07 +00004990class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004991public:
Tim Northover573cbee2014-05-24 12:52:07 +00004992 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4993 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004994
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004995 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00004996 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004997 }
4998
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004999 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5000 return 31;
5001 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005002
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005003 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005004
5005 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5006 CodeGen::CodeGenModule &CGM) const override {
5007 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5008 if (!FD)
5009 return;
5010 llvm::Function *Fn = cast<llvm::Function>(GV);
5011
5012 auto Kind = CGM.getCodeGenOpts().getSignReturnAddress();
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005013 if (Kind != CodeGenOptions::SignReturnAddressScope::None) {
5014 Fn->addFnAttr("sign-return-address",
5015 Kind == CodeGenOptions::SignReturnAddressScope::All
5016 ? "all"
5017 : "non-leaf");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005018
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005019 auto Key = CGM.getCodeGenOpts().getSignReturnAddressKey();
5020 Fn->addFnAttr("sign-return-address-key",
5021 Key == CodeGenOptions::SignReturnAddressKeyValue::AKey
5022 ? "a_key"
5023 : "b_key");
5024 }
5025
5026 if (CGM.getCodeGenOpts().BranchTargetEnforcement)
5027 Fn->addFnAttr("branch-target-enforcement");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005028 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005029};
Martin Storsjo1c8af272017-07-20 05:47:06 +00005030
5031class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5032public:
5033 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5034 : AArch64TargetCodeGenInfo(CGT, K) {}
5035
Eli Friedman540be6d2018-10-26 01:31:57 +00005036 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5037 CodeGen::CodeGenModule &CGM) const override;
5038
Martin Storsjo1c8af272017-07-20 05:47:06 +00005039 void getDependentLibraryOption(llvm::StringRef Lib,
5040 llvm::SmallString<24> &Opt) const override {
5041 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5042 }
5043
5044 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5045 llvm::SmallString<32> &Opt) const override {
5046 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5047 }
5048};
Eli Friedman540be6d2018-10-26 01:31:57 +00005049
5050void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5051 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5052 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5053 if (GV->isDeclaration())
5054 return;
5055 addStackProbeTargetAttributes(D, GV, CGM);
5056}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005057}
Tim Northovera2ee4332014-03-29 15:09:45 +00005058
Tim Northoverb047bfa2014-11-27 21:02:49 +00005059ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00005060 Ty = useFirstFieldIfTransparentUnion(Ty);
5061
Tim Northovera2ee4332014-03-29 15:09:45 +00005062 // Handle illegal vector types here.
5063 if (isIllegalVectorType(Ty)) {
5064 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005065 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00005066 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005067 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5068 return ABIArgInfo::getDirect(ResType);
5069 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005070 if (Size <= 32) {
5071 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00005072 return ABIArgInfo::getDirect(ResType);
5073 }
5074 if (Size == 64) {
5075 llvm::Type *ResType =
5076 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00005077 return ABIArgInfo::getDirect(ResType);
5078 }
5079 if (Size == 128) {
5080 llvm::Type *ResType =
5081 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00005082 return ABIArgInfo::getDirect(ResType);
5083 }
John McCall7f416cc2015-09-08 08:05:57 +00005084 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005085 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005086
5087 if (!isAggregateTypeForABI(Ty)) {
5088 // Treat an enum type as its underlying type.
5089 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5090 Ty = EnumTy->getDecl()->getIntegerType();
5091
Tim Northovera2ee4332014-03-29 15:09:45 +00005092 return (Ty->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005093 ? ABIArgInfo::getExtend(Ty)
Tim Northovera2ee4332014-03-29 15:09:45 +00005094 : ABIArgInfo::getDirect());
5095 }
5096
5097 // Structures with either a non-trivial destructor or a non-trivial
5098 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00005099 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005100 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5101 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00005102 }
5103
5104 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5105 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00005106 uint64_t Size = getContext().getTypeSize(Ty);
5107 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5108 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005109 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5110 return ABIArgInfo::getIgnore();
5111
Tim Northover23bcad22017-05-05 22:36:06 +00005112 // GNU C mode. The only argument that gets ignored is an empty one with size
5113 // 0.
5114 if (IsEmpty && Size == 0)
5115 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00005116 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5117 }
5118
5119 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005120 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005121 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005122 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005123 return ABIArgInfo::getDirect(
5124 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005125 }
5126
5127 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005128 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005129 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5130 // same size and alignment.
5131 if (getTarget().isRenderScriptTarget()) {
5132 return coerceToIntArray(Ty, getContext(), getVMContext());
5133 }
Momchil Velikov20208cc2018-07-30 17:48:23 +00005134 unsigned Alignment;
5135 if (Kind == AArch64ABIInfo::AAPCS) {
5136 Alignment = getContext().getTypeUnadjustedAlign(Ty);
5137 Alignment = Alignment < 128 ? 64 : 128;
5138 } else {
5139 Alignment = getContext().getTypeAlign(Ty);
5140 }
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005141 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005142
Tim Northovera2ee4332014-03-29 15:09:45 +00005143 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5144 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005145 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005146 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5147 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5148 }
5149 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5150 }
5151
John McCall7f416cc2015-09-08 08:05:57 +00005152 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005153}
5154
Tim Northover573cbee2014-05-24 12:52:07 +00005155ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005156 if (RetTy->isVoidType())
5157 return ABIArgInfo::getIgnore();
5158
5159 // Large vector types should be returned via memory.
5160 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005161 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005162
5163 if (!isAggregateTypeForABI(RetTy)) {
5164 // Treat an enum type as its underlying type.
5165 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5166 RetTy = EnumTy->getDecl()->getIntegerType();
5167
Tim Northover4dab6982014-04-18 13:46:08 +00005168 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005169 ? ABIArgInfo::getExtend(RetTy)
Tim Northover4dab6982014-04-18 13:46:08 +00005170 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005171 }
5172
Tim Northover23bcad22017-05-05 22:36:06 +00005173 uint64_t Size = getContext().getTypeSize(RetTy);
5174 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005175 return ABIArgInfo::getIgnore();
5176
Craig Topper8a13c412014-05-21 05:09:00 +00005177 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005178 uint64_t Members = 0;
5179 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005180 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5181 return ABIArgInfo::getDirect();
5182
5183 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005184 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005185 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5186 // same size and alignment.
5187 if (getTarget().isRenderScriptTarget()) {
5188 return coerceToIntArray(RetTy, getContext(), getVMContext());
5189 }
Pete Cooper635b5092015-04-17 22:16:24 +00005190 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005191 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005192
5193 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5194 // For aggregates with 16-byte alignment, we use i128.
5195 if (Alignment < 128 && Size == 128) {
5196 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5197 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5198 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005199 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5200 }
5201
John McCall7f416cc2015-09-08 08:05:57 +00005202 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005203}
5204
Tim Northover573cbee2014-05-24 12:52:07 +00005205/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5206bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005207 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5208 // Check whether VT is legal.
5209 unsigned NumElements = VT->getNumElements();
5210 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005211 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005212 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005213 return true;
5214 return Size != 64 && (Size != 128 || NumElements == 1);
5215 }
5216 return false;
5217}
5218
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005219bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5220 llvm::Type *eltTy,
5221 unsigned elts) const {
5222 if (!llvm::isPowerOf2_32(elts))
5223 return false;
5224 if (totalSize.getQuantity() != 8 &&
5225 (totalSize.getQuantity() != 16 || elts == 1))
5226 return false;
5227 return true;
5228}
5229
Reid Klecknere9f6a712014-10-31 17:10:41 +00005230bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5231 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5232 // point type or a short-vector type. This is the same as the 32-bit ABI,
5233 // but with the difference that any floating-point type is allowed,
5234 // including __fp16.
5235 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5236 if (BT->isFloatingPoint())
5237 return true;
5238 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5239 unsigned VecSize = getContext().getTypeSize(VT);
5240 if (VecSize == 64 || VecSize == 128)
5241 return true;
5242 }
5243 return false;
5244}
5245
5246bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5247 uint64_t Members) const {
5248 return Members <= 4;
5249}
5250
John McCall7f416cc2015-09-08 08:05:57 +00005251Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005252 QualType Ty,
5253 CodeGenFunction &CGF) const {
5254 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005255 bool IsIndirect = AI.isIndirect();
5256
Tim Northoverb047bfa2014-11-27 21:02:49 +00005257 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5258 if (IsIndirect)
5259 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5260 else if (AI.getCoerceToType())
5261 BaseTy = AI.getCoerceToType();
5262
5263 unsigned NumRegs = 1;
5264 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5265 BaseTy = ArrTy->getElementType();
5266 NumRegs = ArrTy->getNumElements();
5267 }
5268 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5269
Tim Northovera2ee4332014-03-29 15:09:45 +00005270 // The AArch64 va_list type and handling is specified in the Procedure Call
5271 // Standard, section B.4:
5272 //
5273 // struct {
5274 // void *__stack;
5275 // void *__gr_top;
5276 // void *__vr_top;
5277 // int __gr_offs;
5278 // int __vr_offs;
5279 // };
5280
5281 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5282 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5283 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5284 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005285
John McCall7f416cc2015-09-08 08:05:57 +00005286 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5287 CharUnits TyAlign = TyInfo.second;
5288
5289 Address reg_offs_p = Address::invalid();
5290 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005291 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005292 CharUnits reg_top_offset;
5293 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005294 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005295 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005296 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005297 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5298 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005299 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5300 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005301 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005302 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005303 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005304 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005305 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005306 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5307 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005308 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5309 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005310 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005311 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005312 }
5313
5314 //=======================================
5315 // Find out where argument was passed
5316 //=======================================
5317
5318 // If reg_offs >= 0 we're already using the stack for this type of
5319 // argument. We don't want to keep updating reg_offs (in case it overflows,
5320 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5321 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005322 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005323 UsingStack = CGF.Builder.CreateICmpSGE(
5324 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5325
5326 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5327
5328 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005329 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005330 CGF.EmitBlock(MaybeRegBlock);
5331
5332 // Integer arguments may need to correct register alignment (for example a
5333 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5334 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005335 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5336 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005337
5338 reg_offs = CGF.Builder.CreateAdd(
5339 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5340 "align_regoffs");
5341 reg_offs = CGF.Builder.CreateAnd(
5342 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5343 "aligned_regoffs");
5344 }
5345
5346 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005347 // The fact that this is done unconditionally reflects the fact that
5348 // allocating an argument to the stack also uses up all the remaining
5349 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005350 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005351 NewOffset = CGF.Builder.CreateAdd(
5352 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5353 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5354
5355 // Now we're in a position to decide whether this argument really was in
5356 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005357 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005358 InRegs = CGF.Builder.CreateICmpSLE(
5359 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5360
5361 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5362
5363 //=======================================
5364 // Argument was in registers
5365 //=======================================
5366
5367 // Now we emit the code for if the argument was originally passed in
5368 // registers. First start the appropriate block:
5369 CGF.EmitBlock(InRegBlock);
5370
John McCall7f416cc2015-09-08 08:05:57 +00005371 llvm::Value *reg_top = nullptr;
5372 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5373 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005374 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005375 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5376 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5377 Address RegAddr = Address::invalid();
5378 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005379
5380 if (IsIndirect) {
5381 // If it's been passed indirectly (actually a struct), whatever we find from
5382 // stored registers or on the stack will actually be a struct **.
5383 MemTy = llvm::PointerType::getUnqual(MemTy);
5384 }
5385
Craig Topper8a13c412014-05-21 05:09:00 +00005386 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005387 uint64_t NumMembers = 0;
5388 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005389 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005390 // Homogeneous aggregates passed in registers will have their elements split
5391 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5392 // qN+1, ...). We reload and store into a temporary local variable
5393 // contiguously.
5394 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005395 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005396 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5397 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005398 Address Tmp = CGF.CreateTempAlloca(HFATy,
5399 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005400
John McCall7f416cc2015-09-08 08:05:57 +00005401 // On big-endian platforms, the value will be right-aligned in its slot.
5402 int Offset = 0;
5403 if (CGF.CGM.getDataLayout().isBigEndian() &&
5404 BaseTyInfo.first.getQuantity() < 16)
5405 Offset = 16 - BaseTyInfo.first.getQuantity();
5406
Tim Northovera2ee4332014-03-29 15:09:45 +00005407 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005408 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5409 Address LoadAddr =
5410 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5411 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5412
5413 Address StoreAddr =
5414 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005415
5416 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5417 CGF.Builder.CreateStore(Elem, StoreAddr);
5418 }
5419
John McCall7f416cc2015-09-08 08:05:57 +00005420 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005421 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005422 // Otherwise the object is contiguous in memory.
5423
5424 // It might be right-aligned in its slot.
5425 CharUnits SlotSize = BaseAddr.getAlignment();
5426 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005427 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005428 TyInfo.first < SlotSize) {
5429 CharUnits Offset = SlotSize - TyInfo.first;
5430 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005431 }
5432
John McCall7f416cc2015-09-08 08:05:57 +00005433 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005434 }
5435
5436 CGF.EmitBranch(ContBlock);
5437
5438 //=======================================
5439 // Argument was on the stack
5440 //=======================================
5441 CGF.EmitBlock(OnStackBlock);
5442
John McCall7f416cc2015-09-08 08:05:57 +00005443 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5444 CharUnits::Zero(), "stack_p");
5445 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005446
John McCall7f416cc2015-09-08 08:05:57 +00005447 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005448 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005449 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5450 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005451
John McCall7f416cc2015-09-08 08:05:57 +00005452 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005453
John McCall7f416cc2015-09-08 08:05:57 +00005454 OnStackPtr = CGF.Builder.CreateAdd(
5455 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005456 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005457 OnStackPtr = CGF.Builder.CreateAnd(
5458 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005459 "align_stack");
5460
John McCall7f416cc2015-09-08 08:05:57 +00005461 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005462 }
John McCall7f416cc2015-09-08 08:05:57 +00005463 Address OnStackAddr(OnStackPtr,
5464 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005465
John McCall7f416cc2015-09-08 08:05:57 +00005466 // All stack slots are multiples of 8 bytes.
5467 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5468 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005469 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005470 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005471 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005472 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005473
John McCall7f416cc2015-09-08 08:05:57 +00005474 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005475 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005476 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005477
5478 // Write the new value of __stack for the next call to va_arg
5479 CGF.Builder.CreateStore(NewStack, stack_p);
5480
5481 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005482 TyInfo.first < StackSlotSize) {
5483 CharUnits Offset = StackSlotSize - TyInfo.first;
5484 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005485 }
5486
John McCall7f416cc2015-09-08 08:05:57 +00005487 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005488
5489 CGF.EmitBranch(ContBlock);
5490
5491 //=======================================
5492 // Tidy up
5493 //=======================================
5494 CGF.EmitBlock(ContBlock);
5495
John McCall7f416cc2015-09-08 08:05:57 +00005496 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5497 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005498
5499 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005500 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5501 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005502
5503 return ResAddr;
5504}
5505
John McCall7f416cc2015-09-08 08:05:57 +00005506Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5507 CodeGenFunction &CGF) const {
5508 // The backend's lowering doesn't support va_arg for aggregates or
5509 // illegal vector types. Lower VAArg here for these cases and use
5510 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005511 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005512 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005513
John McCall7f416cc2015-09-08 08:05:57 +00005514 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005515
John McCall7f416cc2015-09-08 08:05:57 +00005516 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005517 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005518 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5519 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5520 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005521 }
5522
John McCall7f416cc2015-09-08 08:05:57 +00005523 // The size of the actual thing passed, which might end up just
5524 // being a pointer for indirect types.
5525 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5526
5527 // Arguments bigger than 16 bytes which aren't homogeneous
5528 // aggregates should be passed indirectly.
5529 bool IsIndirect = false;
5530 if (TyInfo.first.getQuantity() > 16) {
5531 const Type *Base = nullptr;
5532 uint64_t Members = 0;
5533 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005534 }
5535
John McCall7f416cc2015-09-08 08:05:57 +00005536 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5537 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005538}
5539
Martin Storsjo502de222017-07-13 17:59:14 +00005540Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5541 QualType Ty) const {
5542 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5543 CGF.getContext().getTypeInfoInChars(Ty),
5544 CharUnits::fromQuantity(8),
5545 /*allowHigherAlign*/ false);
5546}
5547
Tim Northovera2ee4332014-03-29 15:09:45 +00005548//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005549// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005550//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005551
5552namespace {
5553
John McCall12f23522016-04-04 18:33:08 +00005554class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005555public:
5556 enum ABIKind {
5557 APCS = 0,
5558 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005559 AAPCS_VFP = 2,
5560 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005561 };
5562
5563private:
5564 ABIKind Kind;
5565
5566public:
John McCall12f23522016-04-04 18:33:08 +00005567 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5568 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005569 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005570 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005571
John McCall3480ef22011-08-30 01:42:09 +00005572 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005573 switch (getTarget().getTriple().getEnvironment()) {
5574 case llvm::Triple::Android:
5575 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005576 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005577 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005578 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005579 case llvm::Triple::MuslEABI:
5580 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005581 return true;
5582 default:
5583 return false;
5584 }
John McCall3480ef22011-08-30 01:42:09 +00005585 }
5586
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005587 bool isEABIHF() const {
5588 switch (getTarget().getTriple().getEnvironment()) {
5589 case llvm::Triple::EABIHF:
5590 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005591 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005592 return true;
5593 default:
5594 return false;
5595 }
5596 }
5597
Daniel Dunbar020daa92009-09-12 01:00:39 +00005598 ABIKind getABIKind() const { return Kind; }
5599
Tim Northovera484bc02013-10-01 14:34:25 +00005600private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005601 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005602 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005603 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
5604 uint64_t Members) const;
5605 ABIArgInfo coerceIllegalVector(QualType Ty) const;
Manman Renfef9e312012-10-16 19:18:39 +00005606 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005607
Reid Klecknere9f6a712014-10-31 17:10:41 +00005608 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5609 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5610 uint64_t Members) const override;
5611
Craig Topper4f12f102014-03-12 06:41:41 +00005612 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005613
John McCall7f416cc2015-09-08 08:05:57 +00005614 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5615 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005616
5617 llvm::CallingConv::ID getLLVMDefaultCC() const;
5618 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005619 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005620
John McCall56331e22018-01-07 06:28:49 +00005621 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005622 bool asReturnValue) const override {
5623 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5624 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005625 bool isSwiftErrorInRegister() const override {
5626 return true;
5627 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005628 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5629 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005630};
5631
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005632class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5633public:
Chris Lattner2b037972010-07-29 02:01:43 +00005634 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5635 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005636
John McCall3480ef22011-08-30 01:42:09 +00005637 const ARMABIInfo &getABIInfo() const {
5638 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5639 }
5640
Craig Topper4f12f102014-03-12 06:41:41 +00005641 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005642 return 13;
5643 }
Roman Divackyc1617352011-05-18 19:36:54 +00005644
Craig Topper4f12f102014-03-12 06:41:41 +00005645 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005646 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005647 }
5648
Roman Divackyc1617352011-05-18 19:36:54 +00005649 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005650 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005651 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005652
5653 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005654 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005655 return false;
5656 }
John McCall3480ef22011-08-30 01:42:09 +00005657
Craig Topper4f12f102014-03-12 06:41:41 +00005658 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005659 if (getABIInfo().isEABI()) return 88;
5660 return TargetCodeGenInfo::getSizeOfUnwindException();
5661 }
Tim Northovera484bc02013-10-01 14:34:25 +00005662
Eric Christopher162c91c2015-06-05 22:03:00 +00005663 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005664 CodeGen::CodeGenModule &CGM) const override {
5665 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005666 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005667 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005668 if (!FD)
5669 return;
5670
5671 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5672 if (!Attr)
5673 return;
5674
5675 const char *Kind;
5676 switch (Attr->getInterrupt()) {
5677 case ARMInterruptAttr::Generic: Kind = ""; break;
5678 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5679 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5680 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5681 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5682 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5683 }
5684
5685 llvm::Function *Fn = cast<llvm::Function>(GV);
5686
5687 Fn->addFnAttr("interrupt", Kind);
5688
Tim Northover5627d392015-10-30 16:30:45 +00005689 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5690 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005691 return;
5692
5693 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5694 // however this is not necessarily true on taking any interrupt. Instruct
5695 // the backend to perform a realignment as part of the function prologue.
5696 llvm::AttrBuilder B;
5697 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005698 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005699 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005700};
5701
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005702class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005703public:
5704 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5705 : ARMTargetCodeGenInfo(CGT, K) {}
5706
Eric Christopher162c91c2015-06-05 22:03:00 +00005707 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005708 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005709
5710 void getDependentLibraryOption(llvm::StringRef Lib,
5711 llvm::SmallString<24> &Opt) const override {
5712 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5713 }
5714
5715 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5716 llvm::SmallString<32> &Opt) const override {
5717 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5718 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005719};
5720
Eric Christopher162c91c2015-06-05 22:03:00 +00005721void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005722 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5723 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5724 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005725 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00005726 addStackProbeTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005727}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005728}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005729
Chris Lattner22326a12010-07-29 02:31:05 +00005730void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakad791e922018-03-19 17:38:40 +00005731 if (!::classifyReturnType(getCXXABI(), FI, *this))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005732 FI.getReturnInfo() =
5733 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005734
Tim Northoverbc784d12015-02-24 17:22:40 +00005735 for (auto &I : FI.arguments())
5736 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005737
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005738 // Always honor user-specified calling convention.
5739 if (FI.getCallingConvention() != llvm::CallingConv::C)
5740 return;
5741
John McCall882987f2013-02-28 19:01:20 +00005742 llvm::CallingConv::ID cc = getRuntimeCC();
5743 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005744 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005745}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005746
John McCall882987f2013-02-28 19:01:20 +00005747/// Return the default calling convention that LLVM will use.
5748llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5749 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005750 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005751 return llvm::CallingConv::ARM_AAPCS_VFP;
5752 else if (isEABI())
5753 return llvm::CallingConv::ARM_AAPCS;
5754 else
5755 return llvm::CallingConv::ARM_APCS;
5756}
5757
5758/// Return the calling convention that our ABI would like us to use
5759/// as the C calling convention.
5760llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005761 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005762 case APCS: return llvm::CallingConv::ARM_APCS;
5763 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5764 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005765 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005766 }
John McCall882987f2013-02-28 19:01:20 +00005767 llvm_unreachable("bad ABI kind");
5768}
5769
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005770void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005771 assert(getRuntimeCC() == llvm::CallingConv::C);
5772
5773 // Don't muddy up the IR with a ton of explicit annotations if
5774 // they'd just match what LLVM will infer from the triple.
5775 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5776 if (abiCC != getLLVMDefaultCC())
5777 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005778}
5779
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005780ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
5781 uint64_t Size = getContext().getTypeSize(Ty);
5782 if (Size <= 32) {
5783 llvm::Type *ResType =
5784 llvm::Type::getInt32Ty(getVMContext());
5785 return ABIArgInfo::getDirect(ResType);
5786 }
5787 if (Size == 64 || Size == 128) {
5788 llvm::Type *ResType = llvm::VectorType::get(
5789 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5790 return ABIArgInfo::getDirect(ResType);
5791 }
5792 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5793}
5794
5795ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
5796 const Type *Base,
5797 uint64_t Members) const {
5798 assert(Base && "Base class should be set for homogeneous aggregate");
5799 // Base can be a floating-point or a vector.
5800 if (const VectorType *VT = Base->getAs<VectorType>()) {
5801 // FP16 vectors should be converted to integer vectors
5802 if (!getTarget().hasLegalHalfType() &&
5803 (VT->getElementType()->isFloat16Type() ||
5804 VT->getElementType()->isHalfType())) {
5805 uint64_t Size = getContext().getTypeSize(VT);
5806 llvm::Type *NewVecTy = llvm::VectorType::get(
5807 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5808 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
5809 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5810 }
5811 }
5812 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5813}
5814
Tim Northoverbc784d12015-02-24 17:22:40 +00005815ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5816 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005817 // 6.1.2.1 The following argument types are VFP CPRCs:
5818 // A single-precision floating-point type (including promoted
5819 // half-precision types); A double-precision floating-point type;
5820 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5821 // with a Base Type of a single- or double-precision floating-point type,
5822 // 64-bit containerized vectors or 128-bit containerized vectors with one
5823 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005824 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005825
Reid Klecknerb1be6832014-11-15 01:41:41 +00005826 Ty = useFirstFieldIfTransparentUnion(Ty);
5827
Manman Renfef9e312012-10-16 19:18:39 +00005828 // Handle illegal vector types here.
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005829 if (isIllegalVectorType(Ty))
5830 return coerceIllegalVector(Ty);
Manman Renfef9e312012-10-16 19:18:39 +00005831
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005832 // _Float16 and __fp16 get passed as if it were an int or float, but with
5833 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5834 // half type natively, and does not need to interwork with AAPCS code.
5835 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5836 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005837 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5838 llvm::Type::getFloatTy(getVMContext()) :
5839 llvm::Type::getInt32Ty(getVMContext());
5840 return ABIArgInfo::getDirect(ResType);
5841 }
5842
John McCalla1dee5302010-08-22 10:59:02 +00005843 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005844 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005845 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005846 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005847 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005848
Alex Bradburye41a5e22018-01-12 20:08:16 +00005849 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
Tim Northover5a1558e2014-11-07 22:30:50 +00005850 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005851 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005852
Oliver Stannard405bded2014-02-11 09:25:50 +00005853 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005854 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005855 }
Tim Northover1060eae2013-06-21 22:49:34 +00005856
Daniel Dunbar09d33622009-09-14 21:54:03 +00005857 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005858 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005859 return ABIArgInfo::getIgnore();
5860
Tim Northover5a1558e2014-11-07 22:30:50 +00005861 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005862 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5863 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005864 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005865 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005866 if (isHomogeneousAggregate(Ty, Base, Members))
5867 return classifyHomogeneousAggregate(Ty, Base, Members);
Tim Northover5627d392015-10-30 16:30:45 +00005868 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5869 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5870 // this convention even for a variadic function: the backend will use GPRs
5871 // if needed.
5872 const Type *Base = nullptr;
5873 uint64_t Members = 0;
5874 if (isHomogeneousAggregate(Ty, Base, Members)) {
5875 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5876 llvm::Type *Ty =
5877 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5878 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5879 }
5880 }
5881
5882 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5883 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5884 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5885 // bigger than 128-bits, they get placed in space allocated by the caller,
5886 // and a pointer is passed.
5887 return ABIArgInfo::getIndirect(
5888 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005889 }
5890
Manman Ren6c30e132012-08-13 21:23:55 +00005891 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005892 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5893 // most 8-byte. We realign the indirect argument if type alignment is bigger
5894 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005895 uint64_t ABIAlign = 4;
Momchil Velikov20208cc2018-07-30 17:48:23 +00005896 uint64_t TyAlign;
Manman Ren505d68f2012-11-05 22:42:46 +00005897 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Momchil Velikov20208cc2018-07-30 17:48:23 +00005898 getABIKind() == ARMABIInfo::AAPCS) {
5899 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
Manman Ren505d68f2012-11-05 22:42:46 +00005900 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Momchil Velikov20208cc2018-07-30 17:48:23 +00005901 } else {
5902 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5903 }
Manman Ren8cd99812012-11-06 04:58:01 +00005904 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005905 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005906 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5907 /*ByVal=*/true,
5908 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005909 }
5910
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005911 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5912 // same size and alignment.
5913 if (getTarget().isRenderScriptTarget()) {
5914 return coerceToIntArray(Ty, getContext(), getVMContext());
5915 }
5916
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005917 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005918 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005919 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005920 // FIXME: Try to match the types of the arguments more accurately where
5921 // we can.
Momchil Velikov20208cc2018-07-30 17:48:23 +00005922 if (TyAlign <= 4) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005923 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5924 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005925 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005926 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5927 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005928 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005929
Tim Northover5a1558e2014-11-07 22:30:50 +00005930 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005931}
5932
Chris Lattner458b2aa2010-07-29 02:16:43 +00005933static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005934 llvm::LLVMContext &VMContext) {
5935 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5936 // is called integer-like if its size is less than or equal to one word, and
5937 // the offset of each of its addressable sub-fields is zero.
5938
5939 uint64_t Size = Context.getTypeSize(Ty);
5940
5941 // Check that the type fits in a word.
5942 if (Size > 32)
5943 return false;
5944
5945 // FIXME: Handle vector types!
5946 if (Ty->isVectorType())
5947 return false;
5948
Daniel Dunbard53bac72009-09-14 02:20:34 +00005949 // Float types are never treated as "integer like".
5950 if (Ty->isRealFloatingType())
5951 return false;
5952
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005953 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005954 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005955 return true;
5956
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005957 // Small complex integer types are "integer like".
5958 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5959 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005960
5961 // Single element and zero sized arrays should be allowed, by the definition
5962 // above, but they are not.
5963
5964 // Otherwise, it must be a record type.
5965 const RecordType *RT = Ty->getAs<RecordType>();
5966 if (!RT) return false;
5967
5968 // Ignore records with flexible arrays.
5969 const RecordDecl *RD = RT->getDecl();
5970 if (RD->hasFlexibleArrayMember())
5971 return false;
5972
5973 // Check that all sub-fields are at offset 0, and are themselves "integer
5974 // like".
5975 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5976
5977 bool HadField = false;
5978 unsigned idx = 0;
5979 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5980 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005981 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005982
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005983 // Bit-fields are not addressable, we only need to verify they are "integer
5984 // like". We still have to disallow a subsequent non-bitfield, for example:
5985 // struct { int : 0; int x }
5986 // is non-integer like according to gcc.
5987 if (FD->isBitField()) {
5988 if (!RD->isUnion())
5989 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005990
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005991 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5992 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005993
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005994 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005995 }
5996
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005997 // Check if this field is at offset 0.
5998 if (Layout.getFieldOffset(idx) != 0)
5999 return false;
6000
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006001 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6002 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00006003
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006004 // Only allow at most one field in a structure. This doesn't match the
6005 // wording above, but follows gcc in situations with a field following an
6006 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006007 if (!RD->isUnion()) {
6008 if (HadField)
6009 return false;
6010
6011 HadField = true;
6012 }
6013 }
6014
6015 return true;
6016}
6017
Oliver Stannard405bded2014-02-11 09:25:50 +00006018ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
6019 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00006020 bool IsEffectivelyAAPCS_VFP =
6021 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006022
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006023 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006024 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006025
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006026 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6027 // Large vector types should be returned via memory.
6028 if (getContext().getTypeSize(RetTy) > 128)
6029 return getNaturalAlignIndirect(RetTy);
6030 // FP16 vectors should be converted to integer vectors
6031 if (!getTarget().hasLegalHalfType() &&
6032 (VT->getElementType()->isFloat16Type() ||
6033 VT->getElementType()->isHalfType()))
6034 return coerceIllegalVector(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00006035 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00006036
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00006037 // _Float16 and __fp16 get returned as if it were an int or float, but with
6038 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6039 // half type natively, and does not need to interwork with AAPCS code.
6040 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6041 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00006042 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
6043 llvm::Type::getFloatTy(getVMContext()) :
6044 llvm::Type::getInt32Ty(getVMContext());
6045 return ABIArgInfo::getDirect(ResType);
6046 }
6047
John McCalla1dee5302010-08-22 10:59:02 +00006048 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00006049 // Treat an enum type as its underlying type.
6050 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6051 RetTy = EnumTy->getDecl()->getIntegerType();
6052
Alex Bradburye41a5e22018-01-12 20:08:16 +00006053 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
Tim Northover5a1558e2014-11-07 22:30:50 +00006054 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00006055 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006056
6057 // Are we following APCS?
6058 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00006059 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006060 return ABIArgInfo::getIgnore();
6061
Daniel Dunbareedf1512010-02-01 23:31:19 +00006062 // Complex types are all returned as packed integers.
6063 //
6064 // FIXME: Consider using 2 x vector types if the back end handles them
6065 // correctly.
6066 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006067 return ABIArgInfo::getDirect(llvm::IntegerType::get(
6068 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00006069
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006070 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006071 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006072 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006073 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006074 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006075 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006076 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006077 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6078 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006079 }
6080
6081 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00006082 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006083 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006084
6085 // Otherwise this is an AAPCS variant.
6086
Chris Lattner458b2aa2010-07-29 02:16:43 +00006087 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006088 return ABIArgInfo::getIgnore();
6089
Bob Wilson1d9269a2011-11-02 04:51:36 +00006090 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00006091 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00006092 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00006093 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006094 if (isHomogeneousAggregate(RetTy, Base, Members))
6095 return classifyHomogeneousAggregate(RetTy, Base, Members);
Bob Wilson1d9269a2011-11-02 04:51:36 +00006096 }
6097
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006098 // Aggregates <= 4 bytes are returned in r0; other aggregates
6099 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006100 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006101 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00006102 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6103 // same size and alignment.
6104 if (getTarget().isRenderScriptTarget()) {
6105 return coerceToIntArray(RetTy, getContext(), getVMContext());
6106 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00006107 if (getDataLayout().isBigEndian())
6108 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00006109 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00006110
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006111 // Return in the smallest viable integer type.
6112 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00006113 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006114 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00006115 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6116 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00006117 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6118 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6119 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00006120 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00006121 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006122 }
6123
John McCall7f416cc2015-09-08 08:05:57 +00006124 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006125}
6126
Manman Renfef9e312012-10-16 19:18:39 +00006127/// isIllegalVector - check whether Ty is an illegal vector type.
6128bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00006129 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006130 // On targets that don't support FP16, FP16 is expanded into float, and we
6131 // don't want the ABI to depend on whether or not FP16 is supported in
6132 // hardware. Thus return false to coerce FP16 vectors into integer vectors.
6133 if (!getTarget().hasLegalHalfType() &&
6134 (VT->getElementType()->isFloat16Type() ||
6135 VT->getElementType()->isHalfType()))
6136 return true;
Stephen Hines8267e7d2015-12-04 01:39:30 +00006137 if (isAndroid()) {
6138 // Android shipped using Clang 3.1, which supported a slightly different
6139 // vector ABI. The primary differences were that 3-element vector types
6140 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6141 // accepts that legacy behavior for Android only.
6142 // Check whether VT is legal.
6143 unsigned NumElements = VT->getNumElements();
6144 // NumElements should be power of 2 or equal to 3.
6145 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6146 return true;
6147 } else {
6148 // Check whether VT is legal.
6149 unsigned NumElements = VT->getNumElements();
6150 uint64_t Size = getContext().getTypeSize(VT);
6151 // NumElements should be power of 2.
6152 if (!llvm::isPowerOf2_32(NumElements))
6153 return true;
6154 // Size should be greater than 32 bits.
6155 return Size <= 32;
6156 }
Manman Renfef9e312012-10-16 19:18:39 +00006157 }
6158 return false;
6159}
6160
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006161bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6162 llvm::Type *eltTy,
6163 unsigned numElts) const {
6164 if (!llvm::isPowerOf2_32(numElts))
6165 return false;
6166 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6167 if (size > 64)
6168 return false;
6169 if (vectorSize.getQuantity() != 8 &&
6170 (vectorSize.getQuantity() != 16 || numElts == 1))
6171 return false;
6172 return true;
6173}
6174
Reid Klecknere9f6a712014-10-31 17:10:41 +00006175bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6176 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6177 // double, or 64-bit or 128-bit vectors.
6178 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6179 if (BT->getKind() == BuiltinType::Float ||
6180 BT->getKind() == BuiltinType::Double ||
6181 BT->getKind() == BuiltinType::LongDouble)
6182 return true;
6183 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6184 unsigned VecSize = getContext().getTypeSize(VT);
6185 if (VecSize == 64 || VecSize == 128)
6186 return true;
6187 }
6188 return false;
6189}
6190
6191bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6192 uint64_t Members) const {
6193 return Members <= 4;
6194}
6195
John McCall7f416cc2015-09-08 08:05:57 +00006196Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6197 QualType Ty) const {
6198 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006199
John McCall7f416cc2015-09-08 08:05:57 +00006200 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006201 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006202 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6203 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6204 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006205 }
6206
John McCall7f416cc2015-09-08 08:05:57 +00006207 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6208 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006209
John McCall7f416cc2015-09-08 08:05:57 +00006210 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6211 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006212 const Type *Base = nullptr;
6213 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006214 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6215 IsIndirect = true;
6216
Tim Northover5627d392015-10-30 16:30:45 +00006217 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6218 // allocated by the caller.
6219 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6220 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6221 !isHomogeneousAggregate(Ty, Base, Members)) {
6222 IsIndirect = true;
6223
John McCall7f416cc2015-09-08 08:05:57 +00006224 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006225 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6226 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006227 // Our callers should be prepared to handle an under-aligned address.
6228 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6229 getABIKind() == ARMABIInfo::AAPCS) {
6230 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6231 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006232 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6233 // ARMv7k allows type alignment up to 16 bytes.
6234 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6235 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006236 } else {
6237 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006238 }
John McCall7f416cc2015-09-08 08:05:57 +00006239 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006240
John McCall7f416cc2015-09-08 08:05:57 +00006241 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6242 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006243}
6244
Chris Lattner0cf24192010-06-28 20:05:43 +00006245//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006246// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006247//===----------------------------------------------------------------------===//
6248
6249namespace {
6250
Justin Holewinski83e96682012-05-24 17:43:12 +00006251class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006252public:
Justin Holewinski36837432013-03-30 14:38:24 +00006253 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006254
6255 ABIArgInfo classifyReturnType(QualType RetTy) const;
6256 ABIArgInfo classifyArgumentType(QualType Ty) const;
6257
Craig Topper4f12f102014-03-12 06:41:41 +00006258 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006259 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6260 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006261};
6262
Justin Holewinski83e96682012-05-24 17:43:12 +00006263class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006264public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006265 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6266 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006267
Eric Christopher162c91c2015-06-05 22:03:00 +00006268 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006269 CodeGen::CodeGenModule &M) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00006270 bool shouldEmitStaticExternCAliases() const override;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006271
Justin Holewinski36837432013-03-30 14:38:24 +00006272private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006273 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6274 // resulting MDNode to the nvvm.annotations MDNode.
6275 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006276};
6277
Justin Holewinski83e96682012-05-24 17:43:12 +00006278ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006279 if (RetTy->isVoidType())
6280 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006281
6282 // note: this is different from default ABI
6283 if (!RetTy->isScalarType())
6284 return ABIArgInfo::getDirect();
6285
6286 // Treat an enum type as its underlying type.
6287 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6288 RetTy = EnumTy->getDecl()->getIntegerType();
6289
Alex Bradburye41a5e22018-01-12 20:08:16 +00006290 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6291 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006292}
6293
Justin Holewinski83e96682012-05-24 17:43:12 +00006294ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006295 // Treat an enum type as its underlying type.
6296 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6297 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006298
Eli Bendersky95338a02014-10-29 13:43:21 +00006299 // Return aggregates type as indirect by value
6300 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006301 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006302
Alex Bradburye41a5e22018-01-12 20:08:16 +00006303 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6304 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006305}
6306
Justin Holewinski83e96682012-05-24 17:43:12 +00006307void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006308 if (!getCXXABI().classifyReturnType(FI))
6309 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006310 for (auto &I : FI.arguments())
6311 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006312
6313 // Always honor user-specified calling convention.
6314 if (FI.getCallingConvention() != llvm::CallingConv::C)
6315 return;
6316
John McCall882987f2013-02-28 19:01:20 +00006317 FI.setEffectiveCallingConvention(getRuntimeCC());
6318}
6319
John McCall7f416cc2015-09-08 08:05:57 +00006320Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6321 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006322 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006323}
6324
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006325void NVPTXTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006326 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6327 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006328 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006329 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006330 if (!FD) return;
6331
6332 llvm::Function *F = cast<llvm::Function>(GV);
6333
6334 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006335 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006336 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006337 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006338 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006339 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006340 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6341 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006342 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006343 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006344 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006345 }
Justin Holewinski38031972011-10-05 17:58:44 +00006346
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006347 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006348 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006349 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006350 // __global__ functions cannot be called from the device, we do not
6351 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006352 if (FD->hasAttr<CUDAGlobalAttr>()) {
6353 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6354 addNVVMMetadata(F, "kernel", 1);
6355 }
Artem Belevich7093e402015-04-21 22:55:54 +00006356 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006357 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006358 llvm::APSInt MaxThreads(32);
6359 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6360 if (MaxThreads > 0)
6361 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6362
6363 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6364 // not specified in __launch_bounds__ or if the user specified a 0 value,
6365 // we don't have to add a PTX directive.
6366 if (Attr->getMinBlocks()) {
6367 llvm::APSInt MinBlocks(32);
6368 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6369 if (MinBlocks > 0)
6370 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6371 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006372 }
6373 }
Justin Holewinski38031972011-10-05 17:58:44 +00006374 }
6375}
6376
Eli Benderskye06a2c42014-04-15 16:57:05 +00006377void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6378 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006379 llvm::Module *M = F->getParent();
6380 llvm::LLVMContext &Ctx = M->getContext();
6381
6382 // Get "nvvm.annotations" metadata node
6383 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6384
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006385 llvm::Metadata *MDVals[] = {
6386 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6387 llvm::ConstantAsMetadata::get(
6388 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006389 // Append metadata to nvvm.annotations
6390 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6391}
Yaxun Liub0eee292018-03-29 14:50:00 +00006392
6393bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6394 return false;
6395}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006396}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006397
6398//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006399// SystemZ ABI Implementation
6400//===----------------------------------------------------------------------===//
6401
6402namespace {
6403
Bryan Chane3f1ed52016-04-28 13:56:43 +00006404class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006405 bool HasVector;
6406
Ulrich Weigand47445072013-05-06 16:26:41 +00006407public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006408 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006409 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006410
6411 bool isPromotableIntegerType(QualType Ty) const;
6412 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006413 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006414 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006415 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006416
6417 ABIArgInfo classifyReturnType(QualType RetTy) const;
6418 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6419
Craig Topper4f12f102014-03-12 06:41:41 +00006420 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006421 if (!getCXXABI().classifyReturnType(FI))
6422 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006423 for (auto &I : FI.arguments())
6424 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006425 }
6426
John McCall7f416cc2015-09-08 08:05:57 +00006427 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6428 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006429
John McCall56331e22018-01-07 06:28:49 +00006430 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
Bryan Chane3f1ed52016-04-28 13:56:43 +00006431 bool asReturnValue) const override {
6432 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6433 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006434 bool isSwiftErrorInRegister() const override {
Arnold Schwaighofer612d6932017-11-07 16:40:51 +00006435 return false;
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006436 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006437};
6438
6439class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6440public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006441 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6442 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006443};
6444
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006445}
Ulrich Weigand47445072013-05-06 16:26:41 +00006446
6447bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6448 // Treat an enum type as its underlying type.
6449 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6450 Ty = EnumTy->getDecl()->getIntegerType();
6451
6452 // Promotable integer types are required to be promoted by the ABI.
6453 if (Ty->isPromotableIntegerType())
6454 return true;
6455
6456 // 32-bit values must also be promoted.
6457 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6458 switch (BT->getKind()) {
6459 case BuiltinType::Int:
6460 case BuiltinType::UInt:
6461 return true;
6462 default:
6463 return false;
6464 }
6465 return false;
6466}
6467
6468bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006469 return (Ty->isAnyComplexType() ||
6470 Ty->isVectorType() ||
6471 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006472}
6473
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006474bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6475 return (HasVector &&
6476 Ty->isVectorType() &&
6477 getContext().getTypeSize(Ty) <= 128);
6478}
6479
Ulrich Weigand47445072013-05-06 16:26:41 +00006480bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6481 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6482 switch (BT->getKind()) {
6483 case BuiltinType::Float:
6484 case BuiltinType::Double:
6485 return true;
6486 default:
6487 return false;
6488 }
6489
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006490 return false;
6491}
6492
6493QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006494 if (const RecordType *RT = Ty->getAsStructureType()) {
6495 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006496 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006497
6498 // If this is a C++ record, check the bases first.
6499 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006500 for (const auto &I : CXXRD->bases()) {
6501 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006502
6503 // Empty bases don't affect things either way.
6504 if (isEmptyRecord(getContext(), Base, true))
6505 continue;
6506
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006507 if (!Found.isNull())
6508 return Ty;
6509 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006510 }
6511
6512 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006513 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006514 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006515 // Unlike isSingleElementStruct(), empty structure and array fields
6516 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006517 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00006518 FD->isZeroLengthBitField(getContext()))
Ulrich Weigand759449c2015-03-30 13:49:01 +00006519 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006520
6521 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006522 // Nested structures still do though.
6523 if (!Found.isNull())
6524 return Ty;
6525 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006526 }
6527
6528 // Unlike isSingleElementStruct(), trailing padding is allowed.
6529 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006530 if (!Found.isNull())
6531 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006532 }
6533
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006534 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006535}
6536
John McCall7f416cc2015-09-08 08:05:57 +00006537Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6538 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006539 // Assume that va_list type is correct; should be pointer to LLVM type:
6540 // struct {
6541 // i64 __gpr;
6542 // i64 __fpr;
6543 // i8 *__overflow_arg_area;
6544 // i8 *__reg_save_area;
6545 // };
6546
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006547 // Every non-vector argument occupies 8 bytes and is passed by preference
6548 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6549 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006550 Ty = getContext().getCanonicalType(Ty);
6551 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006552 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006553 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006554 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006555 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006556 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006557 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006558 CharUnits UnpaddedSize;
6559 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006560 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006561 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6562 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006563 } else {
6564 if (AI.getCoerceToType())
6565 ArgTy = AI.getCoerceToType();
6566 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006567 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006568 UnpaddedSize = TyInfo.first;
6569 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006570 }
John McCall7f416cc2015-09-08 08:05:57 +00006571 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6572 if (IsVector && UnpaddedSize > PaddedSize)
6573 PaddedSize = CharUnits::fromQuantity(16);
6574 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006575
John McCall7f416cc2015-09-08 08:05:57 +00006576 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006577
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006578 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006579 llvm::Value *PaddedSizeV =
6580 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006581
6582 if (IsVector) {
6583 // Work out the address of a vector argument on the stack.
6584 // Vector arguments are always passed in the high bits of a
6585 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006586 Address OverflowArgAreaPtr =
6587 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006588 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006589 Address OverflowArgArea =
6590 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6591 TyInfo.second);
6592 Address MemAddr =
6593 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006594
6595 // Update overflow_arg_area_ptr pointer
6596 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006597 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6598 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006599 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6600
6601 return MemAddr;
6602 }
6603
John McCall7f416cc2015-09-08 08:05:57 +00006604 assert(PaddedSize.getQuantity() == 8);
6605
6606 unsigned MaxRegs, RegCountField, RegSaveIndex;
6607 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006608 if (InFPRs) {
6609 MaxRegs = 4; // Maximum of 4 FPR arguments
6610 RegCountField = 1; // __fpr
6611 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006612 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006613 } else {
6614 MaxRegs = 5; // Maximum of 5 GPR arguments
6615 RegCountField = 0; // __gpr
6616 RegSaveIndex = 2; // save offset for r2
6617 RegPadding = Padding; // values are passed in the low bits of a GPR
6618 }
6619
John McCall7f416cc2015-09-08 08:05:57 +00006620 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6621 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6622 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006623 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006624 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6625 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006626 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006627
6628 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6629 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6630 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6631 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6632
6633 // Emit code to load the value if it was passed in registers.
6634 CGF.EmitBlock(InRegBlock);
6635
6636 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006637 llvm::Value *ScaledRegCount =
6638 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6639 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006640 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6641 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006642 llvm::Value *RegOffset =
6643 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006644 Address RegSaveAreaPtr =
6645 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6646 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006647 llvm::Value *RegSaveArea =
6648 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006649 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6650 "raw_reg_addr"),
6651 PaddedSize);
6652 Address RegAddr =
6653 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006654
6655 // Update the register count
6656 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6657 llvm::Value *NewRegCount =
6658 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6659 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6660 CGF.EmitBranch(ContBlock);
6661
6662 // Emit code to load the value if it was passed in memory.
6663 CGF.EmitBlock(InMemBlock);
6664
6665 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006666 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6667 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6668 Address OverflowArgArea =
6669 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6670 PaddedSize);
6671 Address RawMemAddr =
6672 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6673 Address MemAddr =
6674 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006675
6676 // Update overflow_arg_area_ptr pointer
6677 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006678 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6679 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006680 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6681 CGF.EmitBranch(ContBlock);
6682
6683 // Return the appropriate result.
6684 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006685 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6686 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006687
6688 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006689 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6690 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006691
6692 return ResAddr;
6693}
6694
Ulrich Weigand47445072013-05-06 16:26:41 +00006695ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6696 if (RetTy->isVoidType())
6697 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006698 if (isVectorArgumentType(RetTy))
6699 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006700 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006701 return getNaturalAlignIndirect(RetTy);
Alex Bradburye41a5e22018-01-12 20:08:16 +00006702 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6703 : ABIArgInfo::getDirect());
Ulrich Weigand47445072013-05-06 16:26:41 +00006704}
6705
6706ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6707 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006708 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006709 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006710
6711 // Integers and enums are extended to full register width.
6712 if (isPromotableIntegerType(Ty))
Alex Bradburye41a5e22018-01-12 20:08:16 +00006713 return ABIArgInfo::getExtend(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006714
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006715 // Handle vector types and vector-like structure types. Note that
6716 // as opposed to float-like structure types, we do not allow any
6717 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006718 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006719 QualType SingleElementTy = GetSingleElementType(Ty);
6720 if (isVectorArgumentType(SingleElementTy) &&
6721 getContext().getTypeSize(SingleElementTy) == Size)
6722 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6723
6724 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006725 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006726 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006727
6728 // Handle small structures.
6729 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6730 // Structures with flexible arrays have variable length, so really
6731 // fail the size test above.
6732 const RecordDecl *RD = RT->getDecl();
6733 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006734 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006735
6736 // The structure is passed as an unextended integer, a float, or a double.
6737 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006738 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006739 assert(Size == 32 || Size == 64);
6740 if (Size == 32)
6741 PassTy = llvm::Type::getFloatTy(getVMContext());
6742 else
6743 PassTy = llvm::Type::getDoubleTy(getVMContext());
6744 } else
6745 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6746 return ABIArgInfo::getDirect(PassTy);
6747 }
6748
6749 // Non-structure compounds are passed indirectly.
6750 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006751 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006752
Craig Topper8a13c412014-05-21 05:09:00 +00006753 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006754}
6755
6756//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006757// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006758//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006759
6760namespace {
6761
6762class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6763public:
Chris Lattner2b037972010-07-29 02:01:43 +00006764 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6765 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006766 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006767 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006768};
6769
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006770}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006771
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006772void MSP430TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006773 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6774 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006775 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006776 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006777 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6778 // Handle 'interrupt' attribute:
6779 llvm::Function *F = cast<llvm::Function>(GV);
6780
6781 // Step 1: Set ISR calling convention.
6782 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6783
6784 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006785 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006786
6787 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006788 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006789 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6790 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006791 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006792 }
6793}
6794
Chris Lattner0cf24192010-06-28 20:05:43 +00006795//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006796// MIPS ABI Implementation. This works for both little-endian and
6797// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006798//===----------------------------------------------------------------------===//
6799
John McCall943fae92010-05-27 06:19:26 +00006800namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006801class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006802 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006803 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6804 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006805 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006806 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006807 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006808 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006809public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006810 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006811 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006812 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006813
6814 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006815 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006816 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006817 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6818 QualType Ty) const override;
Alex Bradburye41a5e22018-01-12 20:08:16 +00006819 ABIArgInfo extendType(QualType Ty) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006820};
6821
John McCall943fae92010-05-27 06:19:26 +00006822class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006823 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006824public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006825 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6826 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006827 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006828
Craig Topper4f12f102014-03-12 06:41:41 +00006829 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006830 return 29;
6831 }
6832
Eric Christopher162c91c2015-06-05 22:03:00 +00006833 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006834 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006835 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006836 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006837 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006838
6839 if (FD->hasAttr<MipsLongCallAttr>())
6840 Fn->addFnAttr("long-call");
6841 else if (FD->hasAttr<MipsShortCallAttr>())
6842 Fn->addFnAttr("short-call");
6843
6844 // Other attributes do not have a meaning for declarations.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006845 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006846 return;
6847
Reed Kotler3d5966f2013-03-13 20:40:30 +00006848 if (FD->hasAttr<Mips16Attr>()) {
6849 Fn->addFnAttr("mips16");
6850 }
6851 else if (FD->hasAttr<NoMips16Attr>()) {
6852 Fn->addFnAttr("nomips16");
6853 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006854
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006855 if (FD->hasAttr<MicroMipsAttr>())
6856 Fn->addFnAttr("micromips");
6857 else if (FD->hasAttr<NoMicroMipsAttr>())
6858 Fn->addFnAttr("nomicromips");
6859
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006860 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6861 if (!Attr)
6862 return;
6863
6864 const char *Kind;
6865 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006866 case MipsInterruptAttr::eic: Kind = "eic"; break;
6867 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6868 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6869 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6870 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6871 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6872 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6873 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6874 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6875 }
6876
6877 Fn->addFnAttr("interrupt", Kind);
6878
Reed Kotler373feca2013-01-16 17:10:28 +00006879 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006880
John McCall943fae92010-05-27 06:19:26 +00006881 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006882 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006883
Craig Topper4f12f102014-03-12 06:41:41 +00006884 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006885 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006886 }
John McCall943fae92010-05-27 06:19:26 +00006887};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006888}
John McCall943fae92010-05-27 06:19:26 +00006889
Eric Christopher7565e0d2015-05-29 23:09:49 +00006890void MipsABIInfo::CoerceToIntArgs(
6891 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006892 llvm::IntegerType *IntTy =
6893 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006894
6895 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6896 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6897 ArgList.push_back(IntTy);
6898
6899 // If necessary, add one more integer type to ArgList.
6900 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6901
6902 if (R)
6903 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006904}
6905
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006906// In N32/64, an aligned double precision floating point field is passed in
6907// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006908llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006909 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6910
6911 if (IsO32) {
6912 CoerceToIntArgs(TySize, ArgList);
6913 return llvm::StructType::get(getVMContext(), ArgList);
6914 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006915
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006916 if (Ty->isComplexType())
6917 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006918
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006919 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006920
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006921 // Unions/vectors are passed in integer registers.
6922 if (!RT || !RT->isStructureOrClassType()) {
6923 CoerceToIntArgs(TySize, ArgList);
6924 return llvm::StructType::get(getVMContext(), ArgList);
6925 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006926
6927 const RecordDecl *RD = RT->getDecl();
6928 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006929 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006930
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006931 uint64_t LastOffset = 0;
6932 unsigned idx = 0;
6933 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6934
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006935 // Iterate over fields in the struct/class and check if there are any aligned
6936 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006937 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6938 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006939 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006940 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6941
6942 if (!BT || BT->getKind() != BuiltinType::Double)
6943 continue;
6944
6945 uint64_t Offset = Layout.getFieldOffset(idx);
6946 if (Offset % 64) // Ignore doubles that are not aligned.
6947 continue;
6948
6949 // Add ((Offset - LastOffset) / 64) args of type i64.
6950 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6951 ArgList.push_back(I64);
6952
6953 // Add double type.
6954 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6955 LastOffset = Offset + 64;
6956 }
6957
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006958 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6959 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006960
6961 return llvm::StructType::get(getVMContext(), ArgList);
6962}
6963
Akira Hatanakaddd66342013-10-29 18:41:15 +00006964llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6965 uint64_t Offset) const {
6966 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006967 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006968
Akira Hatanakaddd66342013-10-29 18:41:15 +00006969 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006970}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006971
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006972ABIArgInfo
6973MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006974 Ty = useFirstFieldIfTransparentUnion(Ty);
6975
Akira Hatanaka1632af62012-01-09 19:31:25 +00006976 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006977 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006978 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006979
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006980 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6981 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006982 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6983 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006984
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006985 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006986 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006987 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006988 return ABIArgInfo::getIgnore();
6989
Mark Lacey3825e832013-10-06 01:33:34 +00006990 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006991 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006992 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006993 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006994
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006995 // If we have reached here, aggregates are passed directly by coercing to
6996 // another structure type. Padding is inserted if the offset of the
6997 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006998 ABIArgInfo ArgInfo =
6999 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7000 getPaddingType(OrigOffset, CurrOffset));
7001 ArgInfo.setInReg(true);
7002 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007003 }
7004
7005 // Treat an enum type as its underlying type.
7006 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7007 Ty = EnumTy->getDecl()->getIntegerType();
7008
Daniel Sanders5b445b32014-10-24 14:42:42 +00007009 // All integral types are promoted to the GPR width.
7010 if (Ty->isIntegralOrEnumerationType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00007011 return extendType(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007012
Akira Hatanakaddd66342013-10-29 18:41:15 +00007013 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00007014 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00007015}
7016
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007017llvm::Type*
7018MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00007019 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007020 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007021
Akira Hatanakab6f74432012-02-09 18:49:26 +00007022 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007023 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00007024 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7025 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007026
Akira Hatanakab6f74432012-02-09 18:49:26 +00007027 // N32/64 returns struct/classes in floating point registers if the
7028 // following conditions are met:
7029 // 1. The size of the struct/class is no larger than 128-bit.
7030 // 2. The struct/class has one or two fields all of which are floating
7031 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007032 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00007033 //
7034 // Any other composite results are returned in integer registers.
7035 //
7036 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7037 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7038 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007039 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007040
Akira Hatanakab6f74432012-02-09 18:49:26 +00007041 if (!BT || !BT->isFloatingPoint())
7042 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007043
David Blaikie2d7c57e2012-04-30 02:36:29 +00007044 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00007045 }
7046
7047 if (b == e)
7048 return llvm::StructType::get(getVMContext(), RTList,
7049 RD->hasAttr<PackedAttr>());
7050
7051 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007052 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007053 }
7054
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007055 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007056 return llvm::StructType::get(getVMContext(), RTList);
7057}
7058
Akira Hatanakab579fe52011-06-02 00:09:17 +00007059ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00007060 uint64_t Size = getContext().getTypeSize(RetTy);
7061
Daniel Sandersed39f582014-09-04 13:28:14 +00007062 if (RetTy->isVoidType())
7063 return ABIArgInfo::getIgnore();
7064
7065 // O32 doesn't treat zero-sized structs differently from other structs.
7066 // However, N32/N64 ignores zero sized return values.
7067 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00007068 return ABIArgInfo::getIgnore();
7069
Akira Hatanakac37eddf2012-05-11 21:01:17 +00007070 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007071 if (Size <= 128) {
7072 if (RetTy->isAnyComplexType())
7073 return ABIArgInfo::getDirect();
7074
Daniel Sanderse5018b62014-09-04 15:05:39 +00007075 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00007076 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00007077 if (!IsO32 ||
7078 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7079 ABIArgInfo ArgInfo =
7080 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7081 ArgInfo.setInReg(true);
7082 return ArgInfo;
7083 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007084 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00007085
John McCall7f416cc2015-09-08 08:05:57 +00007086 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007087 }
7088
7089 // Treat an enum type as its underlying type.
7090 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7091 RetTy = EnumTy->getDecl()->getIntegerType();
7092
Stefan Maksimovicb9da8a52018-07-30 10:44:46 +00007093 if (RetTy->isPromotableIntegerType())
7094 return ABIArgInfo::getExtend(RetTy);
7095
7096 if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7097 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7098 return ABIArgInfo::getSignExtend(RetTy);
7099
7100 return ABIArgInfo::getDirect();
Akira Hatanakab579fe52011-06-02 00:09:17 +00007101}
7102
7103void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00007104 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00007105 if (!getCXXABI().classifyReturnType(FI))
7106 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00007107
Eric Christopher7565e0d2015-05-29 23:09:49 +00007108 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007109 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00007110
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007111 for (auto &I : FI.arguments())
7112 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007113}
7114
John McCall7f416cc2015-09-08 08:05:57 +00007115Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7116 QualType OrigTy) const {
7117 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00007118
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007119 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7120 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00007121 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007122 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00007123 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007124 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00007125 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007126 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00007127 DidPromote = true;
7128 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7129 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00007130 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00007131
John McCall7f416cc2015-09-08 08:05:57 +00007132 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007133
John McCall7f416cc2015-09-08 08:05:57 +00007134 // The alignment of things in the argument area is never larger than
7135 // StackAlignInBytes.
7136 TyInfo.second =
7137 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7138
7139 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7140 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7141
7142 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7143 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7144
7145
7146 // If there was a promotion, "unpromote" into a temporary.
7147 // TODO: can we just use a pointer into a subset of the original slot?
7148 if (DidPromote) {
7149 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7150 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7151
7152 // Truncate down to the right width.
7153 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7154 : CGF.IntPtrTy);
7155 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7156 if (OrigTy->isPointerType())
7157 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7158
7159 CGF.Builder.CreateStore(V, Temp);
7160 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007161 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007162
John McCall7f416cc2015-09-08 08:05:57 +00007163 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007164}
7165
Alex Bradburye41a5e22018-01-12 20:08:16 +00007166ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007167 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007168
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007169 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7170 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
Alex Bradburye41a5e22018-01-12 20:08:16 +00007171 return ABIArgInfo::getSignExtend(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007172
Alex Bradburye41a5e22018-01-12 20:08:16 +00007173 return ABIArgInfo::getExtend(Ty);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007174}
7175
John McCall943fae92010-05-27 06:19:26 +00007176bool
7177MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7178 llvm::Value *Address) const {
7179 // This information comes from gcc's implementation, which seems to
7180 // as canonical as it gets.
7181
John McCall943fae92010-05-27 06:19:26 +00007182 // Everything on MIPS is 4 bytes. Double-precision FP registers
7183 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007184 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007185
7186 // 0-31 are the general purpose registers, $0 - $31.
7187 // 32-63 are the floating-point registers, $f0 - $f31.
7188 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7189 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007190 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007191
7192 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7193 // They are one bit wide and ignored here.
7194
7195 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7196 // (coprocessor 1 is the FP unit)
7197 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7198 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7199 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007200 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007201 return false;
7202}
7203
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007204//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007205// AVR ABI Implementation.
7206//===----------------------------------------------------------------------===//
7207
7208namespace {
7209class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7210public:
7211 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7212 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7213
7214 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007215 CodeGen::CodeGenModule &CGM) const override {
7216 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007217 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007218 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7219 if (!FD) return;
7220 auto *Fn = cast<llvm::Function>(GV);
7221
7222 if (FD->getAttr<AVRInterruptAttr>())
7223 Fn->addFnAttr("interrupt");
7224
7225 if (FD->getAttr<AVRSignalAttr>())
7226 Fn->addFnAttr("signal");
7227 }
7228};
7229}
7230
7231//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007232// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007233// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007234// handling.
7235//===----------------------------------------------------------------------===//
7236
7237namespace {
7238
7239class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7240public:
7241 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7242 : DefaultTargetCodeGenInfo(CGT) {}
7243
Eric Christopher162c91c2015-06-05 22:03:00 +00007244 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007245 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007246};
7247
Eric Christopher162c91c2015-06-05 22:03:00 +00007248void TCETargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007249 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7250 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007251 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007252 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007253 if (!FD) return;
7254
7255 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007256
David Blaikiebbafb8a2012-03-11 07:00:24 +00007257 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007258 if (FD->hasAttr<OpenCLKernelAttr>()) {
7259 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007260 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007261 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7262 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007263 // Convert the reqd_work_group_size() attributes to metadata.
7264 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007265 llvm::NamedMDNode *OpenCLMetadata =
7266 M.getModule().getOrInsertNamedMetadata(
7267 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007268
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007269 SmallVector<llvm::Metadata *, 5> Operands;
7270 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007271
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007272 Operands.push_back(
7273 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7274 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7275 Operands.push_back(
7276 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7277 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7278 Operands.push_back(
7279 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7280 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007281
Eric Christopher7565e0d2015-05-29 23:09:49 +00007282 // Add a boolean constant operand for "required" (true) or "hint"
7283 // (false) for implementing the work_group_size_hint attr later.
7284 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007285 Operands.push_back(
7286 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007287 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7288 }
7289 }
7290 }
7291}
7292
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007293}
John McCall943fae92010-05-27 06:19:26 +00007294
Tony Linthicum76329bf2011-12-12 21:14:55 +00007295//===----------------------------------------------------------------------===//
7296// Hexagon ABI Implementation
7297//===----------------------------------------------------------------------===//
7298
7299namespace {
7300
7301class HexagonABIInfo : public ABIInfo {
7302
7303
7304public:
7305 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7306
7307private:
7308
7309 ABIArgInfo classifyReturnType(QualType RetTy) const;
7310 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7311
Craig Topper4f12f102014-03-12 06:41:41 +00007312 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007313
John McCall7f416cc2015-09-08 08:05:57 +00007314 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7315 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007316};
7317
7318class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7319public:
7320 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7321 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7322
Craig Topper4f12f102014-03-12 06:41:41 +00007323 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007324 return 29;
7325 }
7326};
7327
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007328}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007329
7330void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007331 if (!getCXXABI().classifyReturnType(FI))
7332 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007333 for (auto &I : FI.arguments())
7334 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007335}
7336
7337ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7338 if (!isAggregateTypeForABI(Ty)) {
7339 // Treat an enum type as its underlying type.
7340 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7341 Ty = EnumTy->getDecl()->getIntegerType();
7342
Alex Bradburye41a5e22018-01-12 20:08:16 +00007343 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7344 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007345 }
7346
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007347 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7348 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7349
Tony Linthicum76329bf2011-12-12 21:14:55 +00007350 // Ignore empty records.
7351 if (isEmptyRecord(getContext(), Ty, true))
7352 return ABIArgInfo::getIgnore();
7353
Tony Linthicum76329bf2011-12-12 21:14:55 +00007354 uint64_t Size = getContext().getTypeSize(Ty);
7355 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007356 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007357 // Pass in the smallest viable integer type.
7358 else if (Size > 32)
7359 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7360 else if (Size > 16)
7361 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7362 else if (Size > 8)
7363 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7364 else
7365 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7366}
7367
7368ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7369 if (RetTy->isVoidType())
7370 return ABIArgInfo::getIgnore();
7371
7372 // Large vector types should be returned via memory.
7373 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007374 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007375
7376 if (!isAggregateTypeForABI(RetTy)) {
7377 // Treat an enum type as its underlying type.
7378 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7379 RetTy = EnumTy->getDecl()->getIntegerType();
7380
Alex Bradburye41a5e22018-01-12 20:08:16 +00007381 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7382 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007383 }
7384
Tony Linthicum76329bf2011-12-12 21:14:55 +00007385 if (isEmptyRecord(getContext(), RetTy, true))
7386 return ABIArgInfo::getIgnore();
7387
7388 // Aggregates <= 8 bytes are returned in r0; other aggregates
7389 // are returned indirectly.
7390 uint64_t Size = getContext().getTypeSize(RetTy);
7391 if (Size <= 64) {
7392 // Return in the smallest viable integer type.
7393 if (Size <= 8)
7394 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7395 if (Size <= 16)
7396 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7397 if (Size <= 32)
7398 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7399 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7400 }
7401
John McCall7f416cc2015-09-08 08:05:57 +00007402 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007403}
7404
John McCall7f416cc2015-09-08 08:05:57 +00007405Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7406 QualType Ty) const {
7407 // FIXME: Someone needs to audit that this handle alignment correctly.
7408 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7409 getContext().getTypeInfoInChars(Ty),
7410 CharUnits::fromQuantity(4),
7411 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007412}
7413
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007414//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007415// Lanai ABI Implementation
7416//===----------------------------------------------------------------------===//
7417
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007418namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007419class LanaiABIInfo : public DefaultABIInfo {
7420public:
7421 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7422
7423 bool shouldUseInReg(QualType Ty, CCState &State) const;
7424
7425 void computeInfo(CGFunctionInfo &FI) const override {
7426 CCState State(FI.getCallingConvention());
7427 // Lanai uses 4 registers to pass arguments unless the function has the
7428 // regparm attribute set.
7429 if (FI.getHasRegParm()) {
7430 State.FreeRegs = FI.getRegParm();
7431 } else {
7432 State.FreeRegs = 4;
7433 }
7434
7435 if (!getCXXABI().classifyReturnType(FI))
7436 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7437 for (auto &I : FI.arguments())
7438 I.info = classifyArgumentType(I.type, State);
7439 }
7440
Jacques Pienaare74d9132016-04-26 00:09:29 +00007441 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007442 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7443};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007444} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007445
7446bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7447 unsigned Size = getContext().getTypeSize(Ty);
7448 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7449
7450 if (SizeInRegs == 0)
7451 return false;
7452
7453 if (SizeInRegs > State.FreeRegs) {
7454 State.FreeRegs = 0;
7455 return false;
7456 }
7457
7458 State.FreeRegs -= SizeInRegs;
7459
7460 return true;
7461}
7462
Jacques Pienaare74d9132016-04-26 00:09:29 +00007463ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7464 CCState &State) const {
7465 if (!ByVal) {
7466 if (State.FreeRegs) {
7467 --State.FreeRegs; // Non-byval indirects just use one pointer.
7468 return getNaturalAlignIndirectInReg(Ty);
7469 }
7470 return getNaturalAlignIndirect(Ty, false);
7471 }
7472
7473 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007474 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007475 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7476 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7477 /*Realign=*/TypeAlign >
7478 MinABIStackAlignInBytes);
7479}
7480
Jacques Pienaard964cc22016-03-28 21:02:54 +00007481ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7482 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007483 // Check with the C++ ABI first.
7484 const RecordType *RT = Ty->getAs<RecordType>();
7485 if (RT) {
7486 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7487 if (RAA == CGCXXABI::RAA_Indirect) {
7488 return getIndirectResult(Ty, /*ByVal=*/false, State);
7489 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7490 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7491 }
7492 }
7493
7494 if (isAggregateTypeForABI(Ty)) {
7495 // Structures with flexible arrays are always indirect.
7496 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7497 return getIndirectResult(Ty, /*ByVal=*/true, State);
7498
7499 // Ignore empty structs/unions.
7500 if (isEmptyRecord(getContext(), Ty, true))
7501 return ABIArgInfo::getIgnore();
7502
7503 llvm::LLVMContext &LLVMContext = getVMContext();
7504 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7505 if (SizeInRegs <= State.FreeRegs) {
7506 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7507 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7508 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7509 State.FreeRegs -= SizeInRegs;
7510 return ABIArgInfo::getDirectInReg(Result);
7511 } else {
7512 State.FreeRegs = 0;
7513 }
7514 return getIndirectResult(Ty, true, State);
7515 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007516
7517 // Treat an enum type as its underlying type.
7518 if (const auto *EnumTy = Ty->getAs<EnumType>())
7519 Ty = EnumTy->getDecl()->getIntegerType();
7520
Jacques Pienaare74d9132016-04-26 00:09:29 +00007521 bool InReg = shouldUseInReg(Ty, State);
7522 if (Ty->isPromotableIntegerType()) {
7523 if (InReg)
7524 return ABIArgInfo::getDirectInReg();
Alex Bradburye41a5e22018-01-12 20:08:16 +00007525 return ABIArgInfo::getExtend(Ty);
Jacques Pienaare74d9132016-04-26 00:09:29 +00007526 }
7527 if (InReg)
7528 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007529 return ABIArgInfo::getDirect();
7530}
7531
7532namespace {
7533class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7534public:
7535 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7536 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7537};
7538}
7539
7540//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007541// AMDGPU ABI Implementation
7542//===----------------------------------------------------------------------===//
7543
7544namespace {
7545
Matt Arsenault88d7da02016-08-22 19:25:59 +00007546class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007547private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007548 static const unsigned MaxNumRegsForArgsRet = 16;
7549
Matt Arsenault3fe73952017-08-09 21:44:58 +00007550 unsigned numRegsForType(QualType Ty) const;
7551
7552 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7553 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7554 uint64_t Members) const override;
7555
7556public:
7557 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7558 DefaultABIInfo(CGT) {}
7559
7560 ABIArgInfo classifyReturnType(QualType RetTy) const;
7561 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7562 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007563
7564 void computeInfo(CGFunctionInfo &FI) const override;
7565};
7566
Matt Arsenault3fe73952017-08-09 21:44:58 +00007567bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7568 return true;
7569}
7570
7571bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7572 const Type *Base, uint64_t Members) const {
7573 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7574
7575 // Homogeneous Aggregates may occupy at most 16 registers.
7576 return Members * NumRegs <= MaxNumRegsForArgsRet;
7577}
7578
Matt Arsenault3fe73952017-08-09 21:44:58 +00007579/// Estimate number of registers the type will use when passed in registers.
7580unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7581 unsigned NumRegs = 0;
7582
7583 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7584 // Compute from the number of elements. The reported size is based on the
7585 // in-memory size, which includes the padding 4th element for 3-vectors.
7586 QualType EltTy = VT->getElementType();
7587 unsigned EltSize = getContext().getTypeSize(EltTy);
7588
7589 // 16-bit element vectors should be passed as packed.
7590 if (EltSize == 16)
7591 return (VT->getNumElements() + 1) / 2;
7592
7593 unsigned EltNumRegs = (EltSize + 31) / 32;
7594 return EltNumRegs * VT->getNumElements();
7595 }
7596
7597 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7598 const RecordDecl *RD = RT->getDecl();
7599 assert(!RD->hasFlexibleArrayMember());
7600
7601 for (const FieldDecl *Field : RD->fields()) {
7602 QualType FieldTy = Field->getType();
7603 NumRegs += numRegsForType(FieldTy);
7604 }
7605
7606 return NumRegs;
7607 }
7608
7609 return (getContext().getTypeSize(Ty) + 31) / 32;
7610}
7611
Matt Arsenault88d7da02016-08-22 19:25:59 +00007612void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007613 llvm::CallingConv::ID CC = FI.getCallingConvention();
7614
Matt Arsenault88d7da02016-08-22 19:25:59 +00007615 if (!getCXXABI().classifyReturnType(FI))
7616 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7617
Matt Arsenault3fe73952017-08-09 21:44:58 +00007618 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7619 for (auto &Arg : FI.arguments()) {
7620 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7621 Arg.info = classifyKernelArgumentType(Arg.type);
7622 } else {
7623 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7624 }
7625 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007626}
7627
Matt Arsenault3fe73952017-08-09 21:44:58 +00007628ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7629 if (isAggregateTypeForABI(RetTy)) {
7630 // Records with non-trivial destructors/copy-constructors should not be
7631 // returned by value.
7632 if (!getRecordArgABI(RetTy, getCXXABI())) {
7633 // Ignore empty structs/unions.
7634 if (isEmptyRecord(getContext(), RetTy, true))
7635 return ABIArgInfo::getIgnore();
7636
7637 // Lower single-element structs to just return a regular value.
7638 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7639 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7640
7641 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7642 const RecordDecl *RD = RT->getDecl();
7643 if (RD->hasFlexibleArrayMember())
7644 return DefaultABIInfo::classifyReturnType(RetTy);
7645 }
7646
7647 // Pack aggregates <= 4 bytes into single VGPR or pair.
7648 uint64_t Size = getContext().getTypeSize(RetTy);
7649 if (Size <= 16)
7650 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7651
7652 if (Size <= 32)
7653 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7654
7655 if (Size <= 64) {
7656 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7657 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7658 }
7659
7660 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7661 return ABIArgInfo::getDirect();
7662 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007663 }
7664
Matt Arsenault3fe73952017-08-09 21:44:58 +00007665 // Otherwise just do the default thing.
7666 return DefaultABIInfo::classifyReturnType(RetTy);
7667}
7668
7669/// For kernels all parameters are really passed in a special buffer. It doesn't
7670/// make sense to pass anything byval, so everything must be direct.
7671ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7672 Ty = useFirstFieldIfTransparentUnion(Ty);
7673
7674 // TODO: Can we omit empty structs?
7675
Matt Arsenault88d7da02016-08-22 19:25:59 +00007676 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007677 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7678 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007679
7680 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7681 // individual elements, which confuses the Clover OpenCL backend; therefore we
7682 // have to set it to false here. Other args of getDirect() are just defaults.
7683 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7684}
7685
Matt Arsenault3fe73952017-08-09 21:44:58 +00007686ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7687 unsigned &NumRegsLeft) const {
7688 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7689
7690 Ty = useFirstFieldIfTransparentUnion(Ty);
7691
7692 if (isAggregateTypeForABI(Ty)) {
7693 // Records with non-trivial destructors/copy-constructors should not be
7694 // passed by value.
7695 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7696 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7697
7698 // Ignore empty structs/unions.
7699 if (isEmptyRecord(getContext(), Ty, true))
7700 return ABIArgInfo::getIgnore();
7701
7702 // Lower single-element structs to just pass a regular value. TODO: We
7703 // could do reasonable-size multiple-element structs too, using getExpand(),
7704 // though watch out for things like bitfields.
7705 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7706 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7707
7708 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7709 const RecordDecl *RD = RT->getDecl();
7710 if (RD->hasFlexibleArrayMember())
7711 return DefaultABIInfo::classifyArgumentType(Ty);
7712 }
7713
7714 // Pack aggregates <= 8 bytes into single VGPR or pair.
7715 uint64_t Size = getContext().getTypeSize(Ty);
7716 if (Size <= 64) {
7717 unsigned NumRegs = (Size + 31) / 32;
7718 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7719
7720 if (Size <= 16)
7721 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7722
7723 if (Size <= 32)
7724 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7725
7726 // XXX: Should this be i64 instead, and should the limit increase?
7727 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7728 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7729 }
7730
7731 if (NumRegsLeft > 0) {
7732 unsigned NumRegs = numRegsForType(Ty);
7733 if (NumRegsLeft >= NumRegs) {
7734 NumRegsLeft -= NumRegs;
7735 return ABIArgInfo::getDirect();
7736 }
7737 }
7738 }
7739
7740 // Otherwise just do the default thing.
7741 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7742 if (!ArgInfo.isIndirect()) {
7743 unsigned NumRegs = numRegsForType(Ty);
7744 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7745 }
7746
7747 return ArgInfo;
7748}
7749
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007750class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7751public:
7752 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007753 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007754 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007755 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007756 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007757
Yaxun Liu402804b2016-12-15 08:09:08 +00007758 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7759 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007760
Alexander Richardson6d989432017-10-15 18:48:14 +00007761 LangAS getASTAllocaAddressSpace() const override {
7762 return getLangASFromTargetAS(
7763 getABIInfo().getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007764 }
Alexander Richardson6d989432017-10-15 18:48:14 +00007765 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7766 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007767 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7768 llvm::LLVMContext &C) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007769 llvm::Function *
7770 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7771 llvm::Function *BlockInvokeFunc,
7772 llvm::Value *BlockLiteral) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00007773 bool shouldEmitStaticExternCAliases() const override;
Yaxun Liu6c10a662018-06-12 00:16:33 +00007774 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007775};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007776}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007777
Eric Christopher162c91c2015-06-05 22:03:00 +00007778void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007779 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7780 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007781 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007782 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007783 if (!FD)
7784 return;
7785
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007786 llvm::Function *F = cast<llvm::Function>(GV);
7787
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007788 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7789 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
Tony Tye1a3f3a22018-03-23 18:43:15 +00007790
7791 if (M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>() &&
7792 (M.getTriple().getOS() == llvm::Triple::AMDHSA))
Tony Tye68e11a62018-03-23 18:51:45 +00007793 F->addFnAttr("amdgpu-implicitarg-num-bytes", "48");
Tony Tye1a3f3a22018-03-23 18:43:15 +00007794
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007795 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7796 if (ReqdWGS || FlatWGS) {
7797 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7798 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7799 if (ReqdWGS && Min == 0 && Max == 0)
7800 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007801
7802 if (Min != 0) {
7803 assert(Min <= Max && "Min must be less than or equal Max");
7804
7805 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7806 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7807 } else
7808 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007809 }
7810
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007811 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7812 unsigned Min = Attr->getMin();
7813 unsigned Max = Attr->getMax();
7814
7815 if (Min != 0) {
7816 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7817
7818 std::string AttrVal = llvm::utostr(Min);
7819 if (Max != 0)
7820 AttrVal = AttrVal + "," + llvm::utostr(Max);
7821 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7822 } else
7823 assert(Max == 0 && "Max must be zero");
7824 }
7825
7826 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007827 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007828
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007829 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007830 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7831 }
7832
7833 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7834 uint32_t NumVGPR = Attr->getNumVGPR();
7835
7836 if (NumVGPR != 0)
7837 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007838 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007839}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007840
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007841unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7842 return llvm::CallingConv::AMDGPU_KERNEL;
7843}
7844
Yaxun Liu402804b2016-12-15 08:09:08 +00007845// Currently LLVM assumes null pointers always have value 0,
7846// which results in incorrectly transformed IR. Therefore, instead of
7847// emitting null pointers in private and local address spaces, a null
7848// pointer in generic address space is emitted which is casted to a
7849// pointer in local or private address space.
7850llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7851 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7852 QualType QT) const {
7853 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7854 return llvm::ConstantPointerNull::get(PT);
7855
7856 auto &Ctx = CGM.getContext();
7857 auto NPT = llvm::PointerType::get(PT->getElementType(),
7858 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7859 return llvm::ConstantExpr::getAddrSpaceCast(
7860 llvm::ConstantPointerNull::get(NPT), PT);
7861}
7862
Alexander Richardson6d989432017-10-15 18:48:14 +00007863LangAS
Yaxun Liucbf647c2017-07-08 13:24:52 +00007864AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7865 const VarDecl *D) const {
7866 assert(!CGM.getLangOpts().OpenCL &&
7867 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7868 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +00007869 LangAS DefaultGlobalAS = getLangASFromTargetAS(
7870 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007871 if (!D)
7872 return DefaultGlobalAS;
7873
Alexander Richardson6d989432017-10-15 18:48:14 +00007874 LangAS AddrSpace = D->getType().getAddressSpace();
7875 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007876 if (AddrSpace != LangAS::Default)
7877 return AddrSpace;
7878
7879 if (CGM.isTypeConstant(D->getType(), false)) {
7880 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7881 return ConstAS.getValue();
7882 }
7883 return DefaultGlobalAS;
7884}
7885
Yaxun Liu39195062017-08-04 18:16:31 +00007886llvm::SyncScope::ID
7887AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7888 llvm::LLVMContext &C) const {
7889 StringRef Name;
7890 switch (S) {
7891 case SyncScope::OpenCLWorkGroup:
7892 Name = "workgroup";
7893 break;
7894 case SyncScope::OpenCLDevice:
7895 Name = "agent";
7896 break;
7897 case SyncScope::OpenCLAllSVMDevices:
7898 Name = "";
7899 break;
7900 case SyncScope::OpenCLSubGroup:
7901 Name = "subgroup";
7902 }
7903 return C.getOrInsertSyncScopeID(Name);
7904}
7905
Yaxun Liub0eee292018-03-29 14:50:00 +00007906bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7907 return false;
7908}
7909
Yaxun Liu4306f202018-04-20 17:01:03 +00007910void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
Yaxun Liu6c10a662018-06-12 00:16:33 +00007911 const FunctionType *&FT) const {
7912 FT = getABIInfo().getContext().adjustFunctionType(
7913 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
Yaxun Liu4306f202018-04-20 17:01:03 +00007914}
7915
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007916//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007917// SPARC v8 ABI Implementation.
7918// Based on the SPARC Compliance Definition version 2.4.1.
7919//
7920// Ensures that complex values are passed in registers.
7921//
7922namespace {
7923class SparcV8ABIInfo : public DefaultABIInfo {
7924public:
7925 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7926
7927private:
7928 ABIArgInfo classifyReturnType(QualType RetTy) const;
7929 void computeInfo(CGFunctionInfo &FI) const override;
7930};
7931} // end anonymous namespace
7932
7933
7934ABIArgInfo
7935SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7936 if (Ty->isAnyComplexType()) {
7937 return ABIArgInfo::getDirect();
7938 }
7939 else {
7940 return DefaultABIInfo::classifyReturnType(Ty);
7941 }
7942}
7943
7944void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7945
7946 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7947 for (auto &Arg : FI.arguments())
7948 Arg.info = classifyArgumentType(Arg.type);
7949}
7950
7951namespace {
7952class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7953public:
7954 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7955 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7956};
7957} // end anonymous namespace
7958
7959//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007960// SPARC v9 ABI Implementation.
7961// Based on the SPARC Compliance Definition version 2.4.1.
7962//
7963// Function arguments a mapped to a nominal "parameter array" and promoted to
7964// registers depending on their type. Each argument occupies 8 or 16 bytes in
7965// the array, structs larger than 16 bytes are passed indirectly.
7966//
7967// One case requires special care:
7968//
7969// struct mixed {
7970// int i;
7971// float f;
7972// };
7973//
7974// When a struct mixed is passed by value, it only occupies 8 bytes in the
7975// parameter array, but the int is passed in an integer register, and the float
7976// is passed in a floating point register. This is represented as two arguments
7977// with the LLVM IR inreg attribute:
7978//
7979// declare void f(i32 inreg %i, float inreg %f)
7980//
7981// The code generator will only allocate 4 bytes from the parameter array for
7982// the inreg arguments. All other arguments are allocated a multiple of 8
7983// bytes.
7984//
7985namespace {
7986class SparcV9ABIInfo : public ABIInfo {
7987public:
7988 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7989
7990private:
7991 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007992 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007993 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7994 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007995
7996 // Coercion type builder for structs passed in registers. The coercion type
7997 // serves two purposes:
7998 //
7999 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
8000 // in registers.
8001 // 2. Expose aligned floating point elements as first-level elements, so the
8002 // code generator knows to pass them in floating point registers.
8003 //
8004 // We also compute the InReg flag which indicates that the struct contains
8005 // aligned 32-bit floats.
8006 //
8007 struct CoerceBuilder {
8008 llvm::LLVMContext &Context;
8009 const llvm::DataLayout &DL;
8010 SmallVector<llvm::Type*, 8> Elems;
8011 uint64_t Size;
8012 bool InReg;
8013
8014 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
8015 : Context(c), DL(dl), Size(0), InReg(false) {}
8016
8017 // Pad Elems with integers until Size is ToSize.
8018 void pad(uint64_t ToSize) {
8019 assert(ToSize >= Size && "Cannot remove elements");
8020 if (ToSize == Size)
8021 return;
8022
8023 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00008024 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008025 if (Aligned > Size && Aligned <= ToSize) {
8026 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
8027 Size = Aligned;
8028 }
8029
8030 // Add whole 64-bit words.
8031 while (Size + 64 <= ToSize) {
8032 Elems.push_back(llvm::Type::getInt64Ty(Context));
8033 Size += 64;
8034 }
8035
8036 // Final in-word padding.
8037 if (Size < ToSize) {
8038 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
8039 Size = ToSize;
8040 }
8041 }
8042
8043 // Add a floating point element at Offset.
8044 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
8045 // Unaligned floats are treated as integers.
8046 if (Offset % Bits)
8047 return;
8048 // The InReg flag is only required if there are any floats < 64 bits.
8049 if (Bits < 64)
8050 InReg = true;
8051 pad(Offset);
8052 Elems.push_back(Ty);
8053 Size = Offset + Bits;
8054 }
8055
8056 // Add a struct type to the coercion type, starting at Offset (in bits).
8057 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
8058 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
8059 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
8060 llvm::Type *ElemTy = StrTy->getElementType(i);
8061 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
8062 switch (ElemTy->getTypeID()) {
8063 case llvm::Type::StructTyID:
8064 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
8065 break;
8066 case llvm::Type::FloatTyID:
8067 addFloat(ElemOffset, ElemTy, 32);
8068 break;
8069 case llvm::Type::DoubleTyID:
8070 addFloat(ElemOffset, ElemTy, 64);
8071 break;
8072 case llvm::Type::FP128TyID:
8073 addFloat(ElemOffset, ElemTy, 128);
8074 break;
8075 case llvm::Type::PointerTyID:
8076 if (ElemOffset % 64 == 0) {
8077 pad(ElemOffset);
8078 Elems.push_back(ElemTy);
8079 Size += 64;
8080 }
8081 break;
8082 default:
8083 break;
8084 }
8085 }
8086 }
8087
8088 // Check if Ty is a usable substitute for the coercion type.
8089 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00008090 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008091 }
8092
8093 // Get the coercion type as a literal struct type.
8094 llvm::Type *getType() const {
8095 if (Elems.size() == 1)
8096 return Elems.front();
8097 else
8098 return llvm::StructType::get(Context, Elems);
8099 }
8100 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008101};
8102} // end anonymous namespace
8103
8104ABIArgInfo
8105SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
8106 if (Ty->isVoidType())
8107 return ABIArgInfo::getIgnore();
8108
8109 uint64_t Size = getContext().getTypeSize(Ty);
8110
8111 // Anything too big to fit in registers is passed with an explicit indirect
8112 // pointer / sret pointer.
8113 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00008114 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008115
8116 // Treat an enum type as its underlying type.
8117 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8118 Ty = EnumTy->getDecl()->getIntegerType();
8119
8120 // Integer types smaller than a register are extended.
8121 if (Size < 64 && Ty->isIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00008122 return ABIArgInfo::getExtend(Ty);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008123
8124 // Other non-aggregates go in registers.
8125 if (!isAggregateTypeForABI(Ty))
8126 return ABIArgInfo::getDirect();
8127
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008128 // If a C++ object has either a non-trivial copy constructor or a non-trivial
8129 // destructor, it is passed with an explicit indirect pointer / sret pointer.
8130 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00008131 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008132
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008133 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008134 // Build a coercion type from the LLVM struct type.
8135 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8136 if (!StrTy)
8137 return ABIArgInfo::getDirect();
8138
8139 CoerceBuilder CB(getVMContext(), getDataLayout());
8140 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00008141 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008142
8143 // Try to use the original type for coercion.
8144 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8145
8146 if (CB.InReg)
8147 return ABIArgInfo::getDirectInReg(CoerceTy);
8148 else
8149 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008150}
8151
John McCall7f416cc2015-09-08 08:05:57 +00008152Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8153 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008154 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8155 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8156 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8157 AI.setCoerceToType(ArgTy);
8158
John McCall7f416cc2015-09-08 08:05:57 +00008159 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008160
John McCall7f416cc2015-09-08 08:05:57 +00008161 CGBuilderTy &Builder = CGF.Builder;
8162 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8163 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8164
8165 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8166
8167 Address ArgAddr = Address::invalid();
8168 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008169 switch (AI.getKind()) {
8170 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008171 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008172 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008173 llvm_unreachable("Unsupported ABI kind for va_arg");
8174
John McCall7f416cc2015-09-08 08:05:57 +00008175 case ABIArgInfo::Extend: {
8176 Stride = SlotSize;
8177 CharUnits Offset = SlotSize - TypeInfo.first;
8178 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008179 break;
John McCall7f416cc2015-09-08 08:05:57 +00008180 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008181
John McCall7f416cc2015-09-08 08:05:57 +00008182 case ABIArgInfo::Direct: {
8183 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008184 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008185 ArgAddr = Addr;
8186 break;
John McCall7f416cc2015-09-08 08:05:57 +00008187 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008188
8189 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008190 Stride = SlotSize;
8191 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8192 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8193 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008194 break;
8195
8196 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008197 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008198 }
8199
8200 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008201 llvm::Value *NextPtr =
8202 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8203 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008204
John McCall7f416cc2015-09-08 08:05:57 +00008205 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008206}
8207
8208void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8209 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008210 for (auto &I : FI.arguments())
8211 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008212}
8213
8214namespace {
8215class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8216public:
8217 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8218 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008219
Craig Topper4f12f102014-03-12 06:41:41 +00008220 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008221 return 14;
8222 }
8223
8224 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008225 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008226};
8227} // end anonymous namespace
8228
Roman Divackyf02c9942014-02-24 18:46:27 +00008229bool
8230SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8231 llvm::Value *Address) const {
8232 // This is calculated from the LLVM and GCC tables and verified
8233 // against gcc output. AFAIK all ABIs use the same encoding.
8234
8235 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8236
8237 llvm::IntegerType *i8 = CGF.Int8Ty;
8238 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8239 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8240
8241 // 0-31: the 8-byte general-purpose registers
8242 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8243
8244 // 32-63: f0-31, the 4-byte floating-point registers
8245 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8246
8247 // Y = 64
8248 // PSR = 65
8249 // WIM = 66
8250 // TBR = 67
8251 // PC = 68
8252 // NPC = 69
8253 // FSR = 70
8254 // CSR = 71
8255 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008256
Roman Divackyf02c9942014-02-24 18:46:27 +00008257 // 72-87: d0-15, the 8-byte floating-point registers
8258 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8259
8260 return false;
8261}
8262
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008263// ARC ABI implementation.
8264namespace {
8265
8266class ARCABIInfo : public DefaultABIInfo {
8267public:
8268 using DefaultABIInfo::DefaultABIInfo;
8269
8270private:
8271 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8272 QualType Ty) const override;
8273
8274 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
8275 if (!State.FreeRegs)
8276 return;
8277 if (Info.isIndirect() && Info.getInReg())
8278 State.FreeRegs--;
8279 else if (Info.isDirect() && Info.getInReg()) {
8280 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
8281 if (sz < State.FreeRegs)
8282 State.FreeRegs -= sz;
8283 else
8284 State.FreeRegs = 0;
8285 }
8286 }
8287
8288 void computeInfo(CGFunctionInfo &FI) const override {
8289 CCState State(FI.getCallingConvention());
8290 // ARC uses 8 registers to pass arguments.
8291 State.FreeRegs = 8;
8292
8293 if (!getCXXABI().classifyReturnType(FI))
8294 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8295 updateState(FI.getReturnInfo(), FI.getReturnType(), State);
8296 for (auto &I : FI.arguments()) {
8297 I.info = classifyArgumentType(I.type, State.FreeRegs);
8298 updateState(I.info, I.type, State);
8299 }
8300 }
8301
8302 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
8303 ABIArgInfo getIndirectByValue(QualType Ty) const;
8304 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
8305 ABIArgInfo classifyReturnType(QualType RetTy) const;
8306};
8307
8308class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
8309public:
8310 ARCTargetCodeGenInfo(CodeGenTypes &CGT)
8311 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {}
8312};
8313
8314
8315ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
8316 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
8317 getNaturalAlignIndirect(Ty, false);
8318}
8319
8320ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
Daniel Dunbara39bab32019-01-03 23:24:50 +00008321 // Compute the byval alignment.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008322 const unsigned MinABIStackAlignInBytes = 4;
8323 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8324 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8325 TypeAlign > MinABIStackAlignInBytes);
8326}
8327
8328Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8329 QualType Ty) const {
8330 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8331 getContext().getTypeInfoInChars(Ty),
8332 CharUnits::fromQuantity(4), true);
8333}
8334
8335ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
8336 uint8_t FreeRegs) const {
8337 // Handle the generic C++ ABI.
8338 const RecordType *RT = Ty->getAs<RecordType>();
8339 if (RT) {
8340 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8341 if (RAA == CGCXXABI::RAA_Indirect)
8342 return getIndirectByRef(Ty, FreeRegs > 0);
8343
8344 if (RAA == CGCXXABI::RAA_DirectInMemory)
8345 return getIndirectByValue(Ty);
8346 }
8347
8348 // Treat an enum type as its underlying type.
8349 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8350 Ty = EnumTy->getDecl()->getIntegerType();
8351
8352 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
8353
8354 if (isAggregateTypeForABI(Ty)) {
8355 // Structures with flexible arrays are always indirect.
8356 if (RT && RT->getDecl()->hasFlexibleArrayMember())
8357 return getIndirectByValue(Ty);
8358
8359 // Ignore empty structs/unions.
8360 if (isEmptyRecord(getContext(), Ty, true))
8361 return ABIArgInfo::getIgnore();
8362
8363 llvm::LLVMContext &LLVMContext = getVMContext();
8364
8365 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8366 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8367 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8368
8369 return FreeRegs >= SizeInRegs ?
8370 ABIArgInfo::getDirectInReg(Result) :
8371 ABIArgInfo::getDirect(Result, 0, nullptr, false);
8372 }
8373
8374 return Ty->isPromotableIntegerType() ?
8375 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) :
8376 ABIArgInfo::getExtend(Ty)) :
8377 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() :
8378 ABIArgInfo::getDirect());
8379}
8380
8381ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
8382 if (RetTy->isAnyComplexType())
8383 return ABIArgInfo::getDirectInReg();
8384
Daniel Dunbara39bab32019-01-03 23:24:50 +00008385 // Arguments of size > 4 registers are indirect.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008386 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
8387 if (RetSize > 4)
8388 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
8389
8390 return DefaultABIInfo::classifyReturnType(RetTy);
8391}
8392
8393} // End anonymous namespace.
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008394
Robert Lytton0e076492013-08-13 09:43:10 +00008395//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008396// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008397//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008398
Robert Lytton0e076492013-08-13 09:43:10 +00008399namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008400
8401/// A SmallStringEnc instance is used to build up the TypeString by passing
8402/// it by reference between functions that append to it.
8403typedef llvm::SmallString<128> SmallStringEnc;
8404
8405/// TypeStringCache caches the meta encodings of Types.
8406///
8407/// The reason for caching TypeStrings is two fold:
8408/// 1. To cache a type's encoding for later uses;
8409/// 2. As a means to break recursive member type inclusion.
8410///
8411/// A cache Entry can have a Status of:
8412/// NonRecursive: The type encoding is not recursive;
8413/// Recursive: The type encoding is recursive;
8414/// Incomplete: An incomplete TypeString;
8415/// IncompleteUsed: An incomplete TypeString that has been used in a
8416/// Recursive type encoding.
8417///
8418/// A NonRecursive entry will have all of its sub-members expanded as fully
8419/// as possible. Whilst it may contain types which are recursive, the type
8420/// itself is not recursive and thus its encoding may be safely used whenever
8421/// the type is encountered.
8422///
8423/// A Recursive entry will have all of its sub-members expanded as fully as
8424/// possible. The type itself is recursive and it may contain other types which
8425/// are recursive. The Recursive encoding must not be used during the expansion
8426/// of a recursive type's recursive branch. For simplicity the code uses
8427/// IncompleteCount to reject all usage of Recursive encodings for member types.
8428///
8429/// An Incomplete entry is always a RecordType and only encodes its
8430/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8431/// are placed into the cache during type expansion as a means to identify and
8432/// handle recursive inclusion of types as sub-members. If there is recursion
8433/// the entry becomes IncompleteUsed.
8434///
8435/// During the expansion of a RecordType's members:
8436///
8437/// If the cache contains a NonRecursive encoding for the member type, the
8438/// cached encoding is used;
8439///
8440/// If the cache contains a Recursive encoding for the member type, the
8441/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8442///
8443/// If the member is a RecordType, an Incomplete encoding is placed into the
8444/// cache to break potential recursive inclusion of itself as a sub-member;
8445///
8446/// Once a member RecordType has been expanded, its temporary incomplete
8447/// entry is removed from the cache. If a Recursive encoding was swapped out
8448/// it is swapped back in;
8449///
8450/// If an incomplete entry is used to expand a sub-member, the incomplete
8451/// entry is marked as IncompleteUsed. The cache keeps count of how many
8452/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8453///
8454/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8455/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8456/// Else the member is part of a recursive type and thus the recursion has
8457/// been exited too soon for the encoding to be correct for the member.
8458///
8459class TypeStringCache {
8460 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8461 struct Entry {
8462 std::string Str; // The encoded TypeString for the type.
8463 enum Status State; // Information about the encoding in 'Str'.
8464 std::string Swapped; // A temporary place holder for a Recursive encoding
8465 // during the expansion of RecordType's members.
8466 };
8467 std::map<const IdentifierInfo *, struct Entry> Map;
8468 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8469 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8470public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008471 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008472 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8473 bool removeIncomplete(const IdentifierInfo *ID);
8474 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8475 bool IsRecursive);
8476 StringRef lookupStr(const IdentifierInfo *ID);
8477};
8478
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008479/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008480/// FieldEncoding is a helper for this ordering process.
8481class FieldEncoding {
8482 bool HasName;
8483 std::string Enc;
8484public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008485 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008486 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008487 bool operator<(const FieldEncoding &rhs) const {
8488 if (HasName != rhs.HasName) return HasName;
8489 return Enc < rhs.Enc;
8490 }
8491};
8492
Robert Lytton7d1db152013-08-19 09:46:39 +00008493class XCoreABIInfo : public DefaultABIInfo {
8494public:
8495 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008496 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8497 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008498};
8499
Robert Lyttond21e2d72014-03-03 13:45:29 +00008500class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008501 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008502public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008503 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008504 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008505 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8506 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008507};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008508
Robert Lytton2d196952013-10-11 10:29:34 +00008509} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008510
James Y Knight29b5f082016-02-24 02:59:33 +00008511// TODO: this implementation is likely now redundant with the default
8512// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008513Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8514 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008515 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008516
Robert Lytton2d196952013-10-11 10:29:34 +00008517 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008518 CharUnits SlotSize = CharUnits::fromQuantity(4);
8519 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008520
Robert Lytton2d196952013-10-11 10:29:34 +00008521 // Handle the argument.
8522 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008523 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008524 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8525 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8526 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008527 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008528
8529 Address Val = Address::invalid();
8530 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008531 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008532 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008533 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008534 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008535 llvm_unreachable("Unsupported ABI kind for va_arg");
8536 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008537 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8538 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008539 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008540 case ABIArgInfo::Extend:
8541 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008542 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8543 ArgSize = CharUnits::fromQuantity(
8544 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008545 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008546 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008547 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008548 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8549 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8550 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008551 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008552 }
Robert Lytton2d196952013-10-11 10:29:34 +00008553
8554 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008555 if (!ArgSize.isZero()) {
8556 llvm::Value *APN =
8557 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8558 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008559 }
John McCall7f416cc2015-09-08 08:05:57 +00008560
Robert Lytton2d196952013-10-11 10:29:34 +00008561 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008562}
Robert Lytton0e076492013-08-13 09:43:10 +00008563
Robert Lytton844aeeb2014-05-02 09:33:20 +00008564/// During the expansion of a RecordType, an incomplete TypeString is placed
8565/// into the cache as a means to identify and break recursion.
8566/// If there is a Recursive encoding in the cache, it is swapped out and will
8567/// be reinserted by removeIncomplete().
8568/// All other types of encoding should have been used rather than arriving here.
8569void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8570 std::string StubEnc) {
8571 if (!ID)
8572 return;
8573 Entry &E = Map[ID];
8574 assert( (E.Str.empty() || E.State == Recursive) &&
8575 "Incorrectly use of addIncomplete");
8576 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8577 E.Swapped.swap(E.Str); // swap out the Recursive
8578 E.Str.swap(StubEnc);
8579 E.State = Incomplete;
8580 ++IncompleteCount;
8581}
8582
8583/// Once the RecordType has been expanded, the temporary incomplete TypeString
8584/// must be removed from the cache.
8585/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8586/// Returns true if the RecordType was defined recursively.
8587bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8588 if (!ID)
8589 return false;
8590 auto I = Map.find(ID);
8591 assert(I != Map.end() && "Entry not present");
8592 Entry &E = I->second;
8593 assert( (E.State == Incomplete ||
8594 E.State == IncompleteUsed) &&
8595 "Entry must be an incomplete type");
8596 bool IsRecursive = false;
8597 if (E.State == IncompleteUsed) {
8598 // We made use of our Incomplete encoding, thus we are recursive.
8599 IsRecursive = true;
8600 --IncompleteUsedCount;
8601 }
8602 if (E.Swapped.empty())
8603 Map.erase(I);
8604 else {
8605 // Swap the Recursive back.
8606 E.Swapped.swap(E.Str);
8607 E.Swapped.clear();
8608 E.State = Recursive;
8609 }
8610 --IncompleteCount;
8611 return IsRecursive;
8612}
8613
8614/// Add the encoded TypeString to the cache only if it is NonRecursive or
8615/// Recursive (viz: all sub-members were expanded as fully as possible).
8616void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8617 bool IsRecursive) {
8618 if (!ID || IncompleteUsedCount)
8619 return; // No key or it is is an incomplete sub-type so don't add.
8620 Entry &E = Map[ID];
8621 if (IsRecursive && !E.Str.empty()) {
8622 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8623 "This is not the same Recursive entry");
8624 // The parent container was not recursive after all, so we could have used
8625 // this Recursive sub-member entry after all, but we assumed the worse when
8626 // we started viz: IncompleteCount!=0.
8627 return;
8628 }
8629 assert(E.Str.empty() && "Entry already present");
8630 E.Str = Str.str();
8631 E.State = IsRecursive? Recursive : NonRecursive;
8632}
8633
8634/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8635/// are recursively expanding a type (IncompleteCount != 0) and the cached
8636/// encoding is Recursive, return an empty StringRef.
8637StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8638 if (!ID)
8639 return StringRef(); // We have no key.
8640 auto I = Map.find(ID);
8641 if (I == Map.end())
8642 return StringRef(); // We have no encoding.
8643 Entry &E = I->second;
8644 if (E.State == Recursive && IncompleteCount)
8645 return StringRef(); // We don't use Recursive encodings for member types.
8646
8647 if (E.State == Incomplete) {
8648 // The incomplete type is being used to break out of recursion.
8649 E.State = IncompleteUsed;
8650 ++IncompleteUsedCount;
8651 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008652 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008653}
8654
8655/// The XCore ABI includes a type information section that communicates symbol
8656/// type information to the linker. The linker uses this information to verify
8657/// safety/correctness of things such as array bound and pointers et al.
8658/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8659/// This type information (TypeString) is emitted into meta data for all global
8660/// symbols: definitions, declarations, functions & variables.
8661///
8662/// The TypeString carries type, qualifier, name, size & value details.
8663/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008664/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008665/// The output is tested by test/CodeGen/xcore-stringtype.c.
8666///
8667static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8668 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8669
8670/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8671void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8672 CodeGen::CodeGenModule &CGM) const {
8673 SmallStringEnc Enc;
8674 if (getTypeString(Enc, D, CGM, TSC)) {
8675 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008676 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8677 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008678 llvm::NamedMDNode *MD =
8679 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8680 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8681 }
8682}
8683
Xiuli Pan972bea82016-03-24 03:57:17 +00008684//===----------------------------------------------------------------------===//
8685// SPIR ABI Implementation
8686//===----------------------------------------------------------------------===//
8687
8688namespace {
8689class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8690public:
8691 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8692 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008693 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008694};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008695
Xiuli Pan972bea82016-03-24 03:57:17 +00008696} // End anonymous namespace.
8697
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008698namespace clang {
8699namespace CodeGen {
8700void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8701 DefaultABIInfo SPIRABI(CGM.getTypes());
8702 SPIRABI.computeInfo(FI);
8703}
8704}
8705}
8706
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008707unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8708 return llvm::CallingConv::SPIR_KERNEL;
8709}
8710
Robert Lytton844aeeb2014-05-02 09:33:20 +00008711static bool appendType(SmallStringEnc &Enc, QualType QType,
8712 const CodeGen::CodeGenModule &CGM,
8713 TypeStringCache &TSC);
8714
8715/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008716/// Builds a SmallVector containing the encoded field types in declaration
8717/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008718static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8719 const RecordDecl *RD,
8720 const CodeGen::CodeGenModule &CGM,
8721 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008722 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008723 SmallStringEnc Enc;
8724 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008725 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008726 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008727 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008728 Enc += "b(";
8729 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008730 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008731 Enc += ':';
8732 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008733 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008734 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008735 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008736 Enc += ')';
8737 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008738 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008739 }
8740 return true;
8741}
8742
8743/// Appends structure and union types to Enc and adds encoding to cache.
8744/// Recursively calls appendType (via extractFieldType) for each field.
8745/// Union types have their fields ordered according to the ABI.
8746static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8747 const CodeGen::CodeGenModule &CGM,
8748 TypeStringCache &TSC, const IdentifierInfo *ID) {
8749 // Append the cached TypeString if we have one.
8750 StringRef TypeString = TSC.lookupStr(ID);
8751 if (!TypeString.empty()) {
8752 Enc += TypeString;
8753 return true;
8754 }
8755
8756 // Start to emit an incomplete TypeString.
8757 size_t Start = Enc.size();
8758 Enc += (RT->isUnionType()? 'u' : 's');
8759 Enc += '(';
8760 if (ID)
8761 Enc += ID->getName();
8762 Enc += "){";
8763
8764 // We collect all encoded fields and order as necessary.
8765 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008766 const RecordDecl *RD = RT->getDecl()->getDefinition();
8767 if (RD && !RD->field_empty()) {
8768 // An incomplete TypeString stub is placed in the cache for this RecordType
8769 // so that recursive calls to this RecordType will use it whilst building a
8770 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008771 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008772 std::string StubEnc(Enc.substr(Start).str());
8773 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8774 TSC.addIncomplete(ID, std::move(StubEnc));
8775 if (!extractFieldType(FE, RD, CGM, TSC)) {
8776 (void) TSC.removeIncomplete(ID);
8777 return false;
8778 }
8779 IsRecursive = TSC.removeIncomplete(ID);
8780 // The ABI requires unions to be sorted but not structures.
8781 // See FieldEncoding::operator< for sort algorithm.
8782 if (RT->isUnionType())
Fangrui Song55fab262018-09-26 22:16:28 +00008783 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008784 // We can now complete the TypeString.
8785 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008786 for (unsigned I = 0; I != E; ++I) {
8787 if (I)
8788 Enc += ',';
8789 Enc += FE[I].str();
8790 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008791 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008792 Enc += '}';
8793 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8794 return true;
8795}
8796
8797/// Appends enum types to Enc and adds the encoding to the cache.
8798static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8799 TypeStringCache &TSC,
8800 const IdentifierInfo *ID) {
8801 // Append the cached TypeString if we have one.
8802 StringRef TypeString = TSC.lookupStr(ID);
8803 if (!TypeString.empty()) {
8804 Enc += TypeString;
8805 return true;
8806 }
8807
8808 size_t Start = Enc.size();
8809 Enc += "e(";
8810 if (ID)
8811 Enc += ID->getName();
8812 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008813
8814 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008815 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008816 SmallVector<FieldEncoding, 16> FE;
8817 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8818 ++I) {
8819 SmallStringEnc EnumEnc;
8820 EnumEnc += "m(";
8821 EnumEnc += I->getName();
8822 EnumEnc += "){";
8823 I->getInitVal().toString(EnumEnc);
8824 EnumEnc += '}';
8825 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8826 }
Fangrui Song55fab262018-09-26 22:16:28 +00008827 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008828 unsigned E = FE.size();
8829 for (unsigned I = 0; I != E; ++I) {
8830 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008831 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008832 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008833 }
8834 }
8835 Enc += '}';
8836 TSC.addIfComplete(ID, Enc.substr(Start), false);
8837 return true;
8838}
8839
8840/// Appends type's qualifier to Enc.
8841/// This is done prior to appending the type's encoding.
8842static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8843 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008844 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008845 int Lookup = 0;
8846 if (QT.isConstQualified())
8847 Lookup += 1<<0;
8848 if (QT.isRestrictQualified())
8849 Lookup += 1<<1;
8850 if (QT.isVolatileQualified())
8851 Lookup += 1<<2;
8852 Enc += Table[Lookup];
8853}
8854
8855/// Appends built-in types to Enc.
8856static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8857 const char *EncType;
8858 switch (BT->getKind()) {
8859 case BuiltinType::Void:
8860 EncType = "0";
8861 break;
8862 case BuiltinType::Bool:
8863 EncType = "b";
8864 break;
8865 case BuiltinType::Char_U:
8866 EncType = "uc";
8867 break;
8868 case BuiltinType::UChar:
8869 EncType = "uc";
8870 break;
8871 case BuiltinType::SChar:
8872 EncType = "sc";
8873 break;
8874 case BuiltinType::UShort:
8875 EncType = "us";
8876 break;
8877 case BuiltinType::Short:
8878 EncType = "ss";
8879 break;
8880 case BuiltinType::UInt:
8881 EncType = "ui";
8882 break;
8883 case BuiltinType::Int:
8884 EncType = "si";
8885 break;
8886 case BuiltinType::ULong:
8887 EncType = "ul";
8888 break;
8889 case BuiltinType::Long:
8890 EncType = "sl";
8891 break;
8892 case BuiltinType::ULongLong:
8893 EncType = "ull";
8894 break;
8895 case BuiltinType::LongLong:
8896 EncType = "sll";
8897 break;
8898 case BuiltinType::Float:
8899 EncType = "ft";
8900 break;
8901 case BuiltinType::Double:
8902 EncType = "d";
8903 break;
8904 case BuiltinType::LongDouble:
8905 EncType = "ld";
8906 break;
8907 default:
8908 return false;
8909 }
8910 Enc += EncType;
8911 return true;
8912}
8913
8914/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8915static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8916 const CodeGen::CodeGenModule &CGM,
8917 TypeStringCache &TSC) {
8918 Enc += "p(";
8919 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8920 return false;
8921 Enc += ')';
8922 return true;
8923}
8924
8925/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008926static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8927 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008928 const CodeGen::CodeGenModule &CGM,
8929 TypeStringCache &TSC, StringRef NoSizeEnc) {
8930 if (AT->getSizeModifier() != ArrayType::Normal)
8931 return false;
8932 Enc += "a(";
8933 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8934 CAT->getSize().toStringUnsigned(Enc);
8935 else
8936 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8937 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008938 // The Qualifiers should be attached to the type rather than the array.
8939 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008940 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8941 return false;
8942 Enc += ')';
8943 return true;
8944}
8945
8946/// Appends a function encoding to Enc, calling appendType for the return type
8947/// and the arguments.
8948static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8949 const CodeGen::CodeGenModule &CGM,
8950 TypeStringCache &TSC) {
8951 Enc += "f{";
8952 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8953 return false;
8954 Enc += "}(";
8955 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8956 // N.B. we are only interested in the adjusted param types.
8957 auto I = FPT->param_type_begin();
8958 auto E = FPT->param_type_end();
8959 if (I != E) {
8960 do {
8961 if (!appendType(Enc, *I, CGM, TSC))
8962 return false;
8963 ++I;
8964 if (I != E)
8965 Enc += ',';
8966 } while (I != E);
8967 if (FPT->isVariadic())
8968 Enc += ",va";
8969 } else {
8970 if (FPT->isVariadic())
8971 Enc += "va";
8972 else
8973 Enc += '0';
8974 }
8975 }
8976 Enc += ')';
8977 return true;
8978}
8979
8980/// Handles the type's qualifier before dispatching a call to handle specific
8981/// type encodings.
8982static bool appendType(SmallStringEnc &Enc, QualType QType,
8983 const CodeGen::CodeGenModule &CGM,
8984 TypeStringCache &TSC) {
8985
8986 QualType QT = QType.getCanonicalType();
8987
Robert Lytton6adb20f2014-06-05 09:06:21 +00008988 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8989 // The Qualifiers should be attached to the type rather than the array.
8990 // Thus we don't call appendQualifier() here.
8991 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8992
Robert Lytton844aeeb2014-05-02 09:33:20 +00008993 appendQualifier(Enc, QT);
8994
8995 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8996 return appendBuiltinType(Enc, BT);
8997
Robert Lytton844aeeb2014-05-02 09:33:20 +00008998 if (const PointerType *PT = QT->getAs<PointerType>())
8999 return appendPointerType(Enc, PT, CGM, TSC);
9000
9001 if (const EnumType *ET = QT->getAs<EnumType>())
9002 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
9003
9004 if (const RecordType *RT = QT->getAsStructureType())
9005 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9006
9007 if (const RecordType *RT = QT->getAsUnionType())
9008 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9009
9010 if (const FunctionType *FT = QT->getAs<FunctionType>())
9011 return appendFunctionType(Enc, FT, CGM, TSC);
9012
9013 return false;
9014}
9015
9016static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9017 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
9018 if (!D)
9019 return false;
9020
9021 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9022 if (FD->getLanguageLinkage() != CLanguageLinkage)
9023 return false;
9024 return appendType(Enc, FD->getType(), CGM, TSC);
9025 }
9026
9027 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9028 if (VD->getLanguageLinkage() != CLanguageLinkage)
9029 return false;
9030 QualType QT = VD->getType().getCanonicalType();
9031 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
9032 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00009033 // The Qualifiers should be attached to the type rather than the array.
9034 // Thus we don't call appendQualifier() here.
9035 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00009036 }
9037 return appendType(Enc, QT, CGM, TSC);
9038 }
9039 return false;
9040}
9041
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009042//===----------------------------------------------------------------------===//
9043// RISCV ABI Implementation
9044//===----------------------------------------------------------------------===//
9045
9046namespace {
9047class RISCVABIInfo : public DefaultABIInfo {
9048private:
9049 unsigned XLen; // Size of the integer ('x') registers in bits.
9050 static const int NumArgGPRs = 8;
9051
9052public:
9053 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
9054 : DefaultABIInfo(CGT), XLen(XLen) {}
9055
9056 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
9057 // non-virtual, but computeInfo is virtual, so we overload it.
9058 void computeInfo(CGFunctionInfo &FI) const override;
9059
9060 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed,
9061 int &ArgGPRsLeft) const;
9062 ABIArgInfo classifyReturnType(QualType RetTy) const;
9063
9064 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9065 QualType Ty) const override;
9066
9067 ABIArgInfo extendType(QualType Ty) const;
9068};
9069} // end anonymous namespace
9070
9071void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
9072 QualType RetTy = FI.getReturnType();
9073 if (!getCXXABI().classifyReturnType(FI))
9074 FI.getReturnInfo() = classifyReturnType(RetTy);
9075
9076 // IsRetIndirect is true if classifyArgumentType indicated the value should
9077 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128
9078 // is passed direct in LLVM IR, relying on the backend lowering code to
9079 // rewrite the argument list and pass indirectly on RV32.
9080 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect ||
9081 getContext().getTypeSize(RetTy) > (2 * XLen);
9082
9083 // We must track the number of GPRs used in order to conform to the RISC-V
9084 // ABI, as integer scalars passed in registers should have signext/zeroext
9085 // when promoted, but are anyext if passed on the stack. As GPR usage is
9086 // different for variadic arguments, we must also track whether we are
9087 // examining a vararg or not.
9088 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
9089 int NumFixedArgs = FI.getNumRequiredArgs();
9090
9091 int ArgNum = 0;
9092 for (auto &ArgInfo : FI.arguments()) {
9093 bool IsFixed = ArgNum < NumFixedArgs;
9094 ArgInfo.info = classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft);
9095 ArgNum++;
9096 }
9097}
9098
9099ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
9100 int &ArgGPRsLeft) const {
9101 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
9102 Ty = useFirstFieldIfTransparentUnion(Ty);
9103
9104 // Structures with either a non-trivial destructor or a non-trivial
9105 // copy constructor are always passed indirectly.
9106 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
9107 if (ArgGPRsLeft)
9108 ArgGPRsLeft -= 1;
9109 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
9110 CGCXXABI::RAA_DirectInMemory);
9111 }
9112
9113 // Ignore empty structs/unions.
9114 if (isEmptyRecord(getContext(), Ty, true))
9115 return ABIArgInfo::getIgnore();
9116
9117 uint64_t Size = getContext().getTypeSize(Ty);
9118 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
9119 bool MustUseStack = false;
9120 // Determine the number of GPRs needed to pass the current argument
9121 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
9122 // register pairs, so may consume 3 registers.
9123 int NeededArgGPRs = 1;
9124 if (!IsFixed && NeededAlign == 2 * XLen)
9125 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
9126 else if (Size > XLen && Size <= 2 * XLen)
9127 NeededArgGPRs = 2;
9128
9129 if (NeededArgGPRs > ArgGPRsLeft) {
9130 MustUseStack = true;
9131 NeededArgGPRs = ArgGPRsLeft;
9132 }
9133
9134 ArgGPRsLeft -= NeededArgGPRs;
9135
9136 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
9137 // Treat an enum type as its underlying type.
9138 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9139 Ty = EnumTy->getDecl()->getIntegerType();
9140
9141 // All integral types are promoted to XLen width, unless passed on the
9142 // stack.
9143 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
9144 return extendType(Ty);
9145 }
9146
9147 return ABIArgInfo::getDirect();
9148 }
9149
9150 // Aggregates which are <= 2*XLen will be passed in registers if possible,
9151 // so coerce to integers.
9152 if (Size <= 2 * XLen) {
9153 unsigned Alignment = getContext().getTypeAlign(Ty);
9154
9155 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
9156 // required, and a 2-element XLen array if only XLen alignment is required.
9157 if (Size <= XLen) {
9158 return ABIArgInfo::getDirect(
9159 llvm::IntegerType::get(getVMContext(), XLen));
9160 } else if (Alignment == 2 * XLen) {
9161 return ABIArgInfo::getDirect(
9162 llvm::IntegerType::get(getVMContext(), 2 * XLen));
9163 } else {
9164 return ABIArgInfo::getDirect(llvm::ArrayType::get(
9165 llvm::IntegerType::get(getVMContext(), XLen), 2));
9166 }
9167 }
9168 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9169}
9170
9171ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
9172 if (RetTy->isVoidType())
9173 return ABIArgInfo::getIgnore();
9174
9175 int ArgGPRsLeft = 2;
9176
9177 // The rules for return and argument types are the same, so defer to
9178 // classifyArgumentType.
9179 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft);
9180}
9181
9182Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9183 QualType Ty) const {
9184 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
9185
9186 // Empty records are ignored for parameter passing purposes.
9187 if (isEmptyRecord(getContext(), Ty, true)) {
9188 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
9189 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
9190 return Addr;
9191 }
9192
9193 std::pair<CharUnits, CharUnits> SizeAndAlign =
9194 getContext().getTypeInfoInChars(Ty);
9195
9196 // Arguments bigger than 2*Xlen bytes are passed indirectly.
9197 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
9198
9199 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
9200 SlotSize, /*AllowHigherAlign=*/true);
9201}
9202
9203ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
9204 int TySize = getContext().getTypeSize(Ty);
9205 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
9206 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
9207 return ABIArgInfo::getSignExtend(Ty);
9208 return ABIArgInfo::getExtend(Ty);
9209}
9210
9211namespace {
9212class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
9213public:
9214 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
9215 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen)) {}
Ana Pazos1eee1b72018-07-26 17:37:45 +00009216
9217 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9218 CodeGen::CodeGenModule &CGM) const override {
9219 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
9220 if (!FD) return;
9221
9222 const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
9223 if (!Attr)
9224 return;
9225
9226 const char *Kind;
9227 switch (Attr->getInterrupt()) {
9228 case RISCVInterruptAttr::user: Kind = "user"; break;
9229 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
9230 case RISCVInterruptAttr::machine: Kind = "machine"; break;
9231 }
9232
9233 auto *Fn = cast<llvm::Function>(GV);
9234
9235 Fn->addFnAttr("interrupt", Kind);
9236 }
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009237};
9238} // namespace
Robert Lytton844aeeb2014-05-02 09:33:20 +00009239
Robert Lytton0e076492013-08-13 09:43:10 +00009240//===----------------------------------------------------------------------===//
9241// Driver code
9242//===----------------------------------------------------------------------===//
9243
Rafael Espindola9f834732014-09-19 01:54:22 +00009244bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00009245 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00009246}
9247
Chris Lattner2b037972010-07-29 02:01:43 +00009248const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009249 if (TheTargetCodeGenInfo)
9250 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009251
Reid Kleckner9305fd12016-04-13 23:37:17 +00009252 // Helper to set the unique_ptr while still keeping the return value.
9253 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
9254 this->TheTargetCodeGenInfo.reset(P);
9255 return *P;
9256 };
9257
John McCallc8e01702013-04-16 22:48:15 +00009258 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00009259 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00009260 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009261 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00009262
Derek Schuff09338a22012-09-06 17:37:28 +00009263 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009264 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00009265 case llvm::Triple::mips:
9266 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00009267 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00009268 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9269 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009270
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00009271 case llvm::Triple::mips64:
9272 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009273 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009274
Dylan McKaye8232d72017-02-08 05:09:26 +00009275 case llvm::Triple::avr:
9276 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
9277
Tim Northover25e8a672014-05-24 12:51:25 +00009278 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00009279 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00009280 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00009281 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00009282 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00009283 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00009284 return SetCGInfo(
9285 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00009286
Reid Kleckner9305fd12016-04-13 23:37:17 +00009287 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00009288 }
9289
Dan Gohmanc2853072015-09-03 22:51:53 +00009290 case llvm::Triple::wasm32:
9291 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009292 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00009293
Daniel Dunbard59655c2009-09-12 00:59:49 +00009294 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00009295 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00009296 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009297 case llvm::Triple::thumbeb: {
9298 if (Triple.getOS() == llvm::Triple::Win32) {
9299 return SetCGInfo(
9300 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00009301 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00009302
Reid Kleckner9305fd12016-04-13 23:37:17 +00009303 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9304 StringRef ABIStr = getTarget().getABI();
9305 if (ABIStr == "apcs-gnu")
9306 Kind = ARMABIInfo::APCS;
9307 else if (ABIStr == "aapcs16")
9308 Kind = ARMABIInfo::AAPCS16_VFP;
9309 else if (CodeGenOpts.FloatABI == "hard" ||
9310 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009311 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00009312 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009313 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00009314 Kind = ARMABIInfo::AAPCS_VFP;
9315
9316 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9317 }
9318
John McCallea8d8bb2010-03-11 00:10:12 +00009319 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009320 return SetCGInfo(
9321 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00009322 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00009323 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00009324 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00009325 if (getTarget().getABI() == "elfv2")
9326 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009327 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009328 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009329
Hal Finkel415c2a32016-10-02 02:10:45 +00009330 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9331 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009332 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00009333 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009334 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00009335 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00009336 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009337 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00009338 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009339 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009340 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009341
Hal Finkel415c2a32016-10-02 02:10:45 +00009342 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9343 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009344 }
John McCallea8d8bb2010-03-11 00:10:12 +00009345
Peter Collingbournec947aae2012-05-20 23:28:41 +00009346 case llvm::Triple::nvptx:
9347 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009348 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00009349
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009350 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009351 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00009352
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009353 case llvm::Triple::riscv32:
9354 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 32));
9355 case llvm::Triple::riscv64:
9356 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 64));
9357
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009358 case llvm::Triple::systemz: {
9359 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00009360 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009361 }
Ulrich Weigand47445072013-05-06 16:26:41 +00009362
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009363 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00009364 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009365 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009366
Eli Friedman33465822011-07-08 23:31:17 +00009367 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00009368 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00009369 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00009370 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00009371 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00009372
John McCall1fe2a8c2013-06-18 02:46:29 +00009373 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009374 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9375 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9376 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00009377 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009378 return SetCGInfo(new X86_32TargetCodeGenInfo(
9379 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9380 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
9381 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009382 }
Eli Friedman33465822011-07-08 23:31:17 +00009383 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009384
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009385 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009386 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00009387 X86AVXABILevel AVXLevel =
9388 (ABI == "avx512"
9389 ? X86AVXABILevel::AVX512
9390 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009391
Chris Lattner04dc9572010-08-31 16:44:54 +00009392 switch (Triple.getOS()) {
9393 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009394 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00009395 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009396 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009397 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009398 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009399 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00009400 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00009401 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009402 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00009403 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009404 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00009405 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009406 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00009407 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009408 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00009409 case llvm::Triple::sparc:
9410 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00009411 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009412 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00009413 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009414 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00009415 case llvm::Triple::arc:
9416 return SetCGInfo(new ARCTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00009417 case llvm::Triple::spir:
9418 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009419 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009420 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009421}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009422
9423/// Create an OpenCL kernel for an enqueued block.
9424///
9425/// The kernel has the same function type as the block invoke function. Its
9426/// name is the name of the block invoke function postfixed with "_kernel".
9427/// It simply calls the block invoke function then returns.
9428llvm::Function *
9429TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
9430 llvm::Function *Invoke,
9431 llvm::Value *BlockLiteral) const {
9432 auto *InvokeFT = Invoke->getFunctionType();
9433 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9434 for (auto &P : InvokeFT->params())
9435 ArgTys.push_back(P);
9436 auto &C = CGF.getLLVMContext();
9437 std::string Name = Invoke->getName().str() + "_kernel";
9438 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9439 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9440 &CGF.CGM.getModule());
9441 auto IP = CGF.Builder.saveIP();
9442 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9443 auto &Builder = CGF.Builder;
9444 Builder.SetInsertPoint(BB);
9445 llvm::SmallVector<llvm::Value *, 2> Args;
9446 for (auto &A : F->args())
9447 Args.push_back(&A);
9448 Builder.CreateCall(Invoke, Args);
9449 Builder.CreateRetVoid();
9450 Builder.restoreIP(IP);
9451 return F;
9452}
9453
9454/// Create an OpenCL kernel for an enqueued block.
9455///
9456/// The type of the first argument (the block literal) is the struct type
9457/// of the block literal instead of a pointer type. The first argument
9458/// (block literal) is passed directly by value to the kernel. The kernel
9459/// allocates the same type of struct on stack and stores the block literal
9460/// to it and passes its pointer to the block invoke function. The kernel
9461/// has "enqueued-block" function attribute and kernel argument metadata.
9462llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
9463 CodeGenFunction &CGF, llvm::Function *Invoke,
9464 llvm::Value *BlockLiteral) const {
9465 auto &Builder = CGF.Builder;
9466 auto &C = CGF.getLLVMContext();
9467
9468 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
9469 auto *InvokeFT = Invoke->getFunctionType();
9470 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9471 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
9472 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
9473 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
9474 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
9475 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
9476 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
9477
9478 ArgTys.push_back(BlockTy);
9479 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9480 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
9481 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9482 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9483 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9484 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
9485 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
9486 ArgTys.push_back(InvokeFT->getParamType(I));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009487 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
9488 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
9489 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9490 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
9491 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9492 ArgNames.push_back(
Yaxun Liu98f0c432017-10-14 12:51:52 +00009493 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009494 }
9495 std::string Name = Invoke->getName().str() + "_kernel";
9496 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9497 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9498 &CGF.CGM.getModule());
9499 F->addFnAttr("enqueued-block");
9500 auto IP = CGF.Builder.saveIP();
9501 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9502 Builder.SetInsertPoint(BB);
9503 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9504 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9505 BlockPtr->setAlignment(BlockAlign);
9506 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9507 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9508 llvm::SmallVector<llvm::Value *, 2> Args;
9509 Args.push_back(Cast);
9510 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9511 Args.push_back(I);
9512 Builder.CreateCall(Invoke, Args);
9513 Builder.CreateRetVoid();
9514 Builder.restoreIP(IP);
9515
9516 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9517 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9518 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9519 F->setMetadata("kernel_arg_base_type",
9520 llvm::MDNode::get(C, ArgBaseTypeNames));
9521 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9522 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9523 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
9524
9525 return F;
9526}